Skip to content

Commit

Permalink
fix(web-server): cache static files
Browse files Browse the repository at this point in the history
Files in `karma/static/*` were always read from file system.
These files typically don’t change (except when developing Karma itself)
and so it makes sense to cache them in memory.
Especially `./static/context.html`, which is read for every test run.

The main reason for this change is that when using native events
(non-polling), watching can easily hit the EMFILE limit and then this
`fs.readFile()` can be super delayed. This was easily reproducible
problem in AngularJS test suite.
  • Loading branch information
vojtajina committed Aug 5, 2014
1 parent dd1971f commit eb5bd53
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
8 changes: 8 additions & 0 deletions lib/middleware/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,19 @@ var serve404 = function(response, path) {


var createServeFile = function(fs, directory) {
var cache = Object.create(null);

return function(filepath, response, transform, content) {
var responseData;

if (directory) {
filepath = directory + filepath;
}

if (!content && cache[filepath]) {
content = cache[filepath];
}

// serve from cache
if (content) {
response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'));
Expand All @@ -51,6 +57,8 @@ var createServeFile = function(fs, directory) {
return serve404(response, filepath);
}

cache[filepath] = data.toString();

response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'));

// call custom transform fn to transform the data
Expand Down
5 changes: 3 additions & 2 deletions test/unit/middleware/karma.spec.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,17 @@ describe 'middleware.karma', ->
'debug.html': mocks.fs.file(0, 'DEBUG\n%SCRIPTS%\n%X_UA_COMPATIBLE%')
'karma.js': mocks.fs.file(0, 'root: %KARMA_URL_ROOT%, v: %KARMA_VERSION%')

serveFile = require('../../../lib/middleware/common').createServeFile fsMock, '/karma/static'
createServeFile = require('../../../lib/middleware/common').createServeFile
createKarmaMiddleware = require('../../../lib/middleware/karma').create

handler = filesDeferred = nextSpy = response = null
handler = serveFile = filesDeferred = nextSpy = response = null

beforeEach ->
clientConfig = foo: 'bar'
nextSpy = sinon.spy()
response = new HttpResponseMock
filesDeferred = q.defer()
serveFile = createServeFile fsMock, '/karma/static'
handler = createKarmaMiddleware filesDeferred.promise, serveFile,
'/base/path', '/__karma__/', clientConfig

Expand Down

0 comments on commit eb5bd53

Please sign in to comment.