react / react-0.13.3 / examples / basic-commonjs / node_modules / reactify / node_modules / react-tools / node_modules / commoner / test / run.js
81159 viewsvar assert = require("assert");1var Watcher = require("../lib/watcher").Watcher;2var BuildContext = require("../lib/context").BuildContext;3var ModuleReader = require("../lib/reader").ModuleReader;4var ReadFileCache = require("../lib/cache").ReadFileCache;5var grepP = require("../lib/grep");6var util = require("../lib/util");7var fs = require("fs");8var Q = require("q");910var path = require("path");11var sourceDir = path.resolve(__dirname, "source");12var outputDir = path.resolve(__dirname, "output");1314try {15fs.mkdirSync(outputDir);16} catch (exists) {17// pass18}1920var watcher = new Watcher(new ReadFileCache(sourceDir), false);2122// Get a new context. Defaults to setRelativize(true) and setUseProvidesModule(true)23function getNewContext(options) {24var context = new BuildContext({25config: { debug: options.debug },26sourceDir: sourceDir27}, new ReadFileCache(sourceDir));28context.setCacheDirectory(path.join(outputDir, options.cacheDirectory));29context.setRelativize(options.relative === undefined || options.relative);30context.setUseProvidesModule(options.useProvidesModule === undefined || options.useProvidesModule );31return context;32}3334function getNewDebugContext(options) {35options = options || {};36options.debug = true;37options.cacheDirectory = ".debug-module-cache";38return getNewContext(options);39}4041function getNewReleaseContext(options) {42options = options || {};43options.debug = false;44options.cacheDirectory = ".release-module-cache";45return getNewContext(options);46}4748var debugContext = getNewDebugContext();4950var releaseContext = getNewReleaseContext();5152function getProvidedP(id) {53var context = this;54return context.getProvidedP().then(function(idToPath) {55if (idToPath.hasOwnProperty(id))56return context.readFileP(idToPath[id]);57});58}5960function getSourceP(id) {61return this.readModuleP(id);62}6364function waitForHelpers(done, helperP, contextOptions) {65Q.all([66helperP(getNewDebugContext(contextOptions)),67helperP(getNewReleaseContext(contextOptions))68]).done(function() {69done();70});71}7273function checkHome(assert, home) {74return Q(home).then(function(home) {75assert.strictEqual(home.id, "home");76assert.strictEqual(typeof home.source, "string");77assert.notEqual(home.source.indexOf("exports"), -1);78assert.strictEqual(home.source.indexOf('require("./assert");'), 0);79return home;80}).invoke("getRequiredP").then(function(reqs) {81assert.strictEqual(reqs.length, 1);82assert.strictEqual(reqs[0].id, "assert");83});84}8586describe("ModuleReader", function() {87it('should read "home" module correctly', function(done) {88var reader = new ModuleReader(debugContext, [getSourceP], []);89var homeP = reader.readModuleP("home");90checkHome(assert, homeP).done(done);91});9293it("should generate stubs for missing modules", function(done) {94function helperP(context) {95var reader = new ModuleReader(context, [getSourceP], []);96var id = "this/module/should/not/exist";97return reader.readModuleP(id).then(function(module) {98assert.strictEqual(module.id, id);99assert.notEqual(module.source.indexOf("throw new Error"), -1);100});101}102103waitForHelpers(done, helperP);104});105106it("should skip failing resolvers", function(done) {107var reader = new ModuleReader(debugContext, [function(id) {108return this.makePromise(function(callback) {109process.nextTick(function() {110callback(new Error("bad thing happen"));111});112});113}, function(id) {114throw new Error("superbad situation");115}, getSourceP], []);116117var homeP = reader.readModuleP("home");118checkHome(assert, homeP).done(done);119});120121it("should cache previously-read modules", function(done) {122var reader = new ModuleReader(debugContext, [getSourceP], []);123124var homes = [125reader.readModuleP("home"),126reader.readModuleP("home"),127reader.readModuleP.originalFn.call(reader, "home")128];129130assert.strictEqual(homes[0], homes[1]);131assert.notStrictEqual(homes[0], homes[2]);132assert.notStrictEqual(homes[1], homes[2]);133134Q.spread(homes, function(h0, h1, h2) {135assert.strictEqual(h0, h1);136assert.strictEqual(h0, h2);137assert.strictEqual(h1, h2);138139assert.strictEqual(h0.hash, h1.hash);140assert.strictEqual(h1.hash, h2.hash);141}).done(done);142});143144it("should allow multiple file output", function(done) {145var mfSource = [146"function multiFile(foo) {",147" console.log(foo);",148"}"149].join("\n");150151var pkg = require("../package.json");152153function getSourceP(id) {154assert.strictEqual(id, "multi-file");155return Q(mfSource);156}157158function processP1(id, source) {159assert.strictEqual(source, mfSource);160return {161".js": source,162".json": util.readJsonFileP(163path.join(__dirname, "..", "package.json")164)165};166}167168function processP2(id, input) {169assert.strictEqual(input[".js"], mfSource);170171var json = input[".json"];172assert.deepEqual(json, pkg);173174input[".json"] = util.makePromise(function(callback) {175process.nextTick(function() {176callback(null, JSON.stringify(json));177});178});179180return input;181}182183function processP3(id, input) {184assert.strictEqual(input[".js"], mfSource);185assert.strictEqual(typeof input[".json"], "string");186assert.deepEqual(JSON.parse(input[".json"]), pkg);187188return input;189}190191var reader = new ModuleReader(192debugContext,193[getSourceP],194[processP1, processP2, processP3]195);196197reader.readModuleP("multi-file").then(function(mf) {198assert.strictEqual(mf.id, "multi-file");199assert.strictEqual(mf.source, mfSource);200assert.deepEqual(JSON.parse(mf.output[".json"]), pkg);201}).done(done);202});203});204205describe("grepP", function() {206it("should find @providesModule identifiers", function(done) {207Q.spread([208grepP("@providesModule\\s+\\S+", sourceDir),209debugContext.getProvidedP()210], function(pathToMatch, valueToPath) {211assert.deepEqual(pathToMatch, {212"widget/share.js": "@providesModule WidgetShare",213"widget/.bogus.js": "@providesModule WidgetShare",214"widget/bogus.js~": "@providesModule WidgetShare"215});216assert.deepEqual(valueToPath, {217"WidgetShare": "widget/share.js"218});219}).done(done);220});221});222223describe("@providesModule", function() {224it("should parse docblocks correctly", function(done) {225var code = arguments.callee.toString();226227/**228* Look, Ma! A test function that uses itself as input!229* @providesModule230* @providesModule foo/bar231*/232233assert.strictEqual(234code.split("@provides" + "Module").length,2354);236237assert.strictEqual(238debugContext.getProvidedId(code),239"foo/bar");240241assert.strictEqual(242debugContext.getProvidedId(243"no at-providesModule, here"),244null);245246/**247* Just to make sure we only pay attention to the first one.248* @providesModule ignored249*/250251function helper(context) {252var reader = new ModuleReader(context, [253getProvidedP,254getSourceP255], []);256257return Q.all([258Q.spread([259reader.readModuleP("widget/share"),260reader.readModuleP("WidgetShare")261], function(ws1, ws2) {262assert.strictEqual(ws1.id, ws2.id);263assert.strictEqual(ws1.id, "WidgetShare");264assert.strictEqual(ws1, ws2);265}),266267reader.readMultiP([268"widget/share",269"WidgetShare"270]).then(function(modules) {271assert.strictEqual(modules.length, 1);272assert.strictEqual(modules[0].id, "WidgetShare");273}),274275reader.readModuleP(276"widget/gallery"277).then(function(gallery) {278return gallery.getRequiredP();279}).then(function(deps) {280assert.strictEqual(deps.length, 1);281assert.strictEqual(deps[0].id, "WidgetShare");282}),283284Q.spread([285reader.getSourceP("widget/share"),286reader.getSourceP("WidgetShare")287], function(source1, source2) {288assert.strictEqual(source1, source2);289})290]);291}292293waitForHelpers(done, helper);294});295});296297describe("context.makePromise", function() {298it("should make goodly promises", function(done) {299var error = new Error("test");300301function helperP(context) {302return context.makePromise(function(callback) {303process.nextTick(function() {304callback(error, "asdf");305});306}).then(function() {307assert.ok(false, "should have thrown an error");308}, function(err) {309assert.strictEqual(err, error);310311return context.makePromise(function(callback) {312process.nextTick(function() {313callback(null, "success");314});315}).then(function(result) {316assert.strictEqual(result, "success");317});318})319}320321waitForHelpers(done, helperP);322});323});324325describe("util.relativize", function() {326it("should resolve correct relative module identifiers", function(done) {327var moduleId = "some/deeply/nested/module";328var processor = require("../lib/relative").getProcessor(null);329330function makeSource(id) {331var str = JSON.stringify(id);332return "require(" + str + ");\n" +333"require(function(){require(" + str + ")}())";334}335336function helperP(requiredId, expected) {337assert.strictEqual(338util.relativize(moduleId, requiredId),339expected);340341return processor(342moduleId,343makeSource(requiredId)344).then(function(output) {345assert.deepEqual(output, {346".js": makeSource(expected)347});348});349}350351Q.all([352helperP("another/nested/module",353"../../../another/nested/module"),354helperP("../../buried/module/./file",355"../../buried/module/file"),356helperP("../../buried/module/../file",357"../../buried/file"),358helperP("./same/level",359"./same/level"),360helperP("./same/./level",361"./same/level"),362helperP("./same/../level",363"./level"),364helperP("some/deeply/buried/treasure",365"../buried/treasure"),366helperP("./file", "./file"),367helperP("./file/../../../module",368"../../module"),369helperP("./file/../../module",370"../module")371]).done(function() {372done();373});374});375});376377describe("canonical module identifiers", function() {378it("should be returned by reader.getCanonicalIdP", function(done) {379function helperP(context) {380var reader = new ModuleReader(context, [381getProvidedP,382getSourceP383], []);384385return Q.spread([386reader.getCanonicalIdP("widget/share"),387reader.getCanonicalIdP("WidgetShare"),388reader.readModuleP("widget/share").get("id"),389reader.readModuleP("WidgetShare").get("id")390], function(ws1, ws2, ws3, ws4) {391assert.strictEqual(ws1, "WidgetShare");392assert.strictEqual(ws2, "WidgetShare");393assert.strictEqual(ws3, "WidgetShare");394assert.strictEqual(ws4, "WidgetShare");395});396}397398waitForHelpers(done, helperP);399});400401it("should replace non-canonical required identifiers", function(done) {402function helperP(context) {403assert.strictEqual(context.ignoreDependencies, false);404405var reader = new ModuleReader(context, [406getProvidedP,407getSourceP408], []);409410return reader.readModuleP("widget/follow").then(function(follow) {411assert.strictEqual(follow.source.indexOf("widget/share"), -1);412413assert.strictEqual(strCount(414'require("../WidgetShare")',415follow.source416), 4);417418assert.strictEqual(strCount(419'require("./gallery")',420follow.source421), 2);422423assert.strictEqual(strCount(424'require("../assert")',425follow.source426), 2);427});428}429430waitForHelpers(done, helperP);431});432433function strCount(substring, string) {434return string.split(substring).length - 1;435}436});437438describe("canonical module identifiers without --use-provides-module", function() {439it("should not be returned by reader.getCanonicalIdP nor reader.readModuleP", function(done) {440function helperP(context) {441console.log(context.useProvidesModule);442var reader = new ModuleReader(context, [443getProvidedP,444getSourceP445], []);446447return Q.spread([448reader.getCanonicalIdP("widget/share"),449reader.getCanonicalIdP("WidgetShare"),450reader.readModuleP("widget/share").get("id"),451reader.readModuleP("WidgetShare").get("id")452], function(ws1, ws2, ws3, ws4) {453assert.strictEqual(ws1, "widget/share");454assert.strictEqual(ws2, "WidgetShare");455assert.strictEqual(ws3, "widget/share");456assert.strictEqual(ws4, "WidgetShare");457});458}459460waitForHelpers(done, helperP, {useProvidesModule: false});461});462})463464describe("util.flatten", function() {465it("should flatten deeply nested arrays", function() {466function check(input, expected) {467var flat = util.flatten(input);468assert.deepEqual(flat, expected);469}470471check(1, 1);472check([[],,[],1, 2], [1, 2]);473check([[[[[[]]]]]], []);474check([[1,[[[[2]]],3]]], [1, 2, 3]);475check([[1],[[2]],[[[3]]]], [1, 2, 3]);476check([,,,], []);477});478});479480describe("util.testWriteFd", function() {481it("should write non-ASCII file data", function(done) {482var file = path.join(outputDir, "writeFdP.test.txt");483484function check(content) {485function afterUnlink(err) {486return util.openExclusiveP(file).then(function(fd) {487return util.writeFdP(fd, content).then(function(written) {488assert.strictEqual(content, written);489});490});491}492493return function() {494return util.unlinkP(file).then(afterUnlink, afterUnlink);495};496}497498Q("ignored")499.then(check("x"))500.then(check("x\ny"))501.then(check("x\r\ny"))502.then(check("\t\nx\t"))503.then(check("\ufeff")) // zero-width non-breaking space504.then(check("\u2603")) // snowman505.then(check("\ud83d\udc19")) // octopus506.finally(function() {507return util.unlinkP(file);508}).done(done);509});510});511512describe("Watcher", function() {513it("should basically work", function(done) {514var watcher = new Watcher(new ReadFileCache(sourceDir), false);515var dummy = "dummy.js";516var dummyFile = path.join(sourceDir, dummy);517518function waitForChangeP() {519return util.makePromise(function(callback) {520watcher.on("changed", function(path) {521callback(null, path);522});523});524}525526util.unlinkP(dummyFile).then(function() {527return util.openExclusiveP(dummyFile).then(function(fd) {528return util.writeFdP(fd, "dummy");529});530}).then(function() {531return Q.all([532watcher.readFileP("home.js"),533watcher.readFileP(dummy)534]);535}).then(function() {536return Q.all([537util.unlinkP(dummyFile),538waitForChangeP()539]);540}).done(function() {541watcher.close();542done();543});544});545546it("should be able to watch directories", function(done) {547var watcher = new Watcher(new ReadFileCache(sourceDir), false);548var watchMe = "watchMe.js";549var fullPath = path.join(sourceDir, watchMe);550551function waitForChangeP() {552return util.makePromise(function(callback) {553watcher.once("changed", function(path) {554callback(null, path);555});556});557}558559function write(content) {560return util.openFileP(fullPath).then(function(fd) {561var promise = waitForChangeP();562util.writeFdP(fd, content);563return promise;564});565}566567util.unlinkP(fullPath).then(function() {568return watcher.readFileP(watchMe).then(function(source) {569assert.ok(false, "readFileP should have failed");570}, function(err) {571assert.strictEqual(err.code, "ENOENT");572});573}).then(function() {574return write("first");575}).then(function() {576return write("second");577}).then(function() {578var promise = waitForChangeP();579util.unlinkP(fullPath);580return promise;581}).then(function() {582return write("third");583}).finally(function() {584return util.unlinkP(fullPath);585}).done(function() {586watcher.close();587done();588});589});590});591592593