<commit_before>const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESManglePlugin = require('esmangle-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const FailPlugin = require('webpack-fail-plugin');
const OrderAndHashPlugin = require('./order-and-hash-plugin');
const htmlTemplateContent = require('./html-template-content');
const StyleLintPlugin = require('stylelint-webpack-plugin');

const PORT = process.env.PORT || 55555;
const DEFAULT_OPTIONS = {
    appDir    : './app',
    buildDir  : './app-build',
    testDir   : './app-test',
    releaseDir: './app-release',
    port      : PORT,
    names     : 'app*, release'
};
const unminify = process.env.UNMINIFIED || 'false';
const linting = process.env.LINT || 'false';
const publicPath = process.env.PUBLIC_PATH || ('http://localhost:' + PORT + '/');
const outputDir = process.env.MODE === 'release' ? DEFAULT_OPTIONS.releaseDir : DEFAULT_OPTIONS.buildDir;

var plugins = [
    new CleanPlugin([outputDir], {root: process.cwd(), verbose: false}),
    new webpack.DefinePlugin({
        BUILD_VERSION            : process.env.BUILD_VERSION || JSON.stringify('development'),
        DEFINE_LOGGING_IS_ENABLED: process.env.LOGGING_IS_ENABLED || 'false'
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.ProvidePlugin({
        jQuery         : 'jquery',
        $              : 'jquery',
        'window.jQuery': 'jquery'
    }),
    new webpack.optimize.CommonsChunkPlugin('vendor', 'js/vendor-[hash].js'),
    new ExtractTextPlugin('css/[name]-[id]-[contenthash].css'),

    new ExtractTextPlugin('indexhtml.html'),
    new HtmlWebpackPlugin({
        filename       : 'index.html',
        excludeChunks  : ['manifest', 'indexhtml'],
        templateContent: htmlTemplateContent('indexhtml', false), // custom html template with support for inject tag
        minify         : false,
        inject         : false
    }),
    new webpack.optimize.DedupePlugin,
    FailPlugin
];
if (linting === 'true') {
    plugins.push(new StyleLintPlugin({
        failOnError: true,
        syntax     : 'scss'
    }));
}
if (unminify == 'false') {
    plugins.push(new ESManglePlugin({
        exclude: /(test|indexhtml).\w+.js$/i  // breakage occurs if we don't exclude entry points for index.html, test
    }));
    plugins.push(new OrderAndHashPlugin());
}

module.exports = {
    entry        : {
        vendor     : [
            path.join(__dirname, '/app/vendor.js')
        ],
        'index'    : [
            path.join(__dirname, './app/index.js'),
            path.join(__dirname, './app/index.scss')
        ],
        'indexhtml': [
            path.join(__dirname, './app/index.html')
        ]
    },
    devtool      : 'source-map',
    output       : {
        path         : outputDir,
        filename     : '[name]-[chunkhash].js',
        chunkFilename: '[name].[chunkhash].js',
        publicPath   : publicPath
    },
    devServer    : {
        // https://webpack.js.org/configuration/stats
        stats: {
            hash        : true,
            version     : true,
            timings     : true,
            assets      : false,
            chunks      : false,
            modules     : false,
            reasons     : false,
            children    : false,
            source      : false,
            errors      : true,
            errorDetails: true,
            warnings    : true,
            publicPath  : false
        },
        port : PORT
    },
    plugins      : plugins,
    resolve      : {
        extensions        : ['', '.js'],
        modulesDirectories: [
            'node_modules',
            'bower_components'
        ]
    },
    resolveLoader: {
        modulesDirectories: [
            'node_modules',
            'bower_components'
        ]
    },
    // https://github.com/webpack-contrib/jshint-loader
    jshint    : {
        emitErrors: true,
        failOnHint: false,
    },
    module       : {
        preLoaders: [
            //{
            //    test  : /\.css$/,
            //    loader: 'csslint'
            //},
            {
                test   : /\.js$/i,
                loader : 'jshint-loader',
                exclude: /node_modules/
            }
        ],
        loaders   : [
            {
                test   : /\angular.js$/i,
                include: /node_modules\/angular/i,
                loader : 'exports-loader?angular'
            },

            {
                test  : /\.json$/,
                loader: 'json-loader'
            },
            {
                test  : /index\.html$/,
                loader: ExtractTextPlugin.extract('html?minimize=false&attrs=img:src link:href')
            },
            {
                test  : /\.scss$/,
                loader: ExtractTextPlugin.extract('style-loader', '!css-loader?minimize&sourceMap!resolve-url-loader?sourceMap!sass-loader?sourceMap')
            },
            {
                test  : /\.css$/,
                loader: ExtractTextPlugin.extract('style-loader', '!css-loader?minimize&sourceMap!resolve-url-loader?sourceMap')
            },
            {
                test  : /\.(ico|gif|jpg|jpeg|png|svg)$/,
                loader: 'file-loader?name=[md5:hash:hex:20].[ext]!image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
            },
            {
                test  : /\.(eot|ttf|otf)([#?].*)?$/i,
                loader: 'file-loader?name=[md5:hash:hex:20].[ext]'
            },
            {
                test  : /\.woff2?([#?].*)?$/i,
                loader: 'url-loader?limit=10000&mimetype=application/font-woff&name=[md5:hash:hex:20].[ext]'
            },
            {
                test  : /\.(mp3|mp4)$/,
                loader: 'file-loader?name=[md5:hash:hex:20].[ext]'
            },

            {
                test  : /\.js$/,
                loader: 'ng-annotate-loader?sourceMap!adjust-sourcemap-loader?format=absolute!nginject-loader?sourceMap&deprecate&singleQuote!babel-loader?sourceMap&ignore=buffer&compact=false&cacheDirectory=.babel'
            },
            {
                test   : /\.html$/,
                exclude: /index\.html$/,
                loader : 'html-loader?interpolate&removeComments=false&attrs=img:src link:href'
            }
        ]
    }
};<commit_msg>fixed the team city CI script<commit_after>const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESManglePlugin = require('esmangle-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const FailPlugin = require('webpack-fail-plugin');
const OrderAndHashPlugin = require('./order-and-hash-plugin');
const htmlTemplateContent = require('./html-template-content');
const StyleLintPlugin = require('stylelint-webpack-plugin');

const PORT = process.env.PORT || 55555;
const DEFAULT_OPTIONS = {
    appDir    : './app',
    buildDir  : './app-build',
    testDir   : './app-test',
    releaseDir: './app-release',
    port      : PORT,
    names     : 'app*, release'
};
const unminify = process.env.UNMINIFIED || 'false';
const linting = process.env.LINT || 'false';
const publicPath = process.env.PUBLIC_PATH || process.env.publicPath || ('http://localhost:' + PORT + '/');
const outputDir = process.env.MODE === 'release' ? DEFAULT_OPTIONS.releaseDir : DEFAULT_OPTIONS.buildDir;

var plugins = [
    new CleanPlugin([outputDir], {root: process.cwd(), verbose: false}),
    new webpack.DefinePlugin({
        BUILD_VERSION            : process.env.BUILD_VERSION || JSON.stringify('development'),
        DEFINE_LOGGING_IS_ENABLED: process.env.LOGGING_IS_ENABLED || 'false'
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.ProvidePlugin({
        jQuery         : 'jquery',
        $              : 'jquery',
        'window.jQuery': 'jquery'
    }),
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor-[hash].js'),
    new ExtractTextPlugin('[name]-[id]-[contenthash].css'),

    new ExtractTextPlugin('indexhtml.html'),
    new HtmlWebpackPlugin({
        filename       : 'index.html',
        excludeChunks  : ['manifest', 'indexhtml'],
        templateContent: htmlTemplateContent('indexhtml', false), // custom html template with support for inject tag
        minify         : false,
        inject         : false
    }),
    new webpack.optimize.DedupePlugin,
    FailPlugin
];
if (linting === 'true') {
    plugins.push(new StyleLintPlugin({
        failOnError: true,
        syntax     : 'scss'
    }));
}
if (unminify == 'false') {
    plugins.push(new ESManglePlugin({
        exclude: /(test|indexhtml).\w+.js$/i  // breakage occurs if we don't exclude entry points for index.html, test
    }));
    plugins.push(new OrderAndHashPlugin());
}

module.exports = {
    entry        : {
        vendor     : [
            path.join(__dirname, '/app/vendor.js')
        ],
        'index'    : [
            path.join(__dirname, './app/index.js'),
            path.join(__dirname, './app/index.scss')
        ],
        'indexhtml': [
            path.join(__dirname, './app/index.html')
        ]
    },
    devtool      : 'source-map',
    output       : {
        path         : outputDir,
        filename     : '[name]-[chunkhash].js',
        chunkFilename: '[name].[chunkhash].js',
        publicPath   : publicPath
    },
    devServer    : {
        // https://webpack.js.org/configuration/stats
        stats: {
            hash        : true,
            version     : true,
            timings     : true,
            assets      : false,
            chunks      : false,
            modules     : false,
            reasons     : false,
            children    : false,
            source      : false,
            errors      : true,
            errorDetails: true,
            warnings    : true,
            publicPath  : false
        },
        port : PORT
    },
    plugins      : plugins,
    resolve      : {
        extensions        : ['', '.js'],
        modulesDirectories: [
            'node_modules',
            'bower_components'
        ]
    },
    resolveLoader: {
        modulesDirectories: [
            'node_modules',
            'bower_components'
        ]
    },
    // https://github.com/webpack-contrib/jshint-loader
    jshint       : {
        emitErrors: true,
        failOnHint: false,
    },
    module       : {
        preLoaders: [
            //{
            //    test  : /\.css$/,
            //    loader: 'csslint'
            //},
            {
                test   : /\.js$/i,
                loader : 'jshint-loader',
                exclude: /node_modules/
            }
        ],
        loaders   : [
            {
                test   : /\angular.js$/i,
                include: /node_modules\/angular/i,
                loader : 'exports-loader?angular'
            },

            {
                test  : /\.json$/,
                loader: 'json-loader'
            },
            {
                test  : /index\.html$/,
                loader: ExtractTextPlugin.extract('html?minimize=false&attrs=img:src link:href')
            },
            {
                test  : /\.scss$/,
                loader: ExtractTextPlugin.extract('style-loader', '!css-loader?minimize&sourceMap!resolve-url-loader?sourceMap!sass-loader?sourceMap')
            },
            {
                test  : /\.css$/,
                loader: ExtractTextPlugin.extract('style-loader', '!css-loader?minimize&sourceMap!resolve-url-loader?sourceMap')
            },
            {
                test  : /\.(ico|gif|jpg|jpeg|png|svg)$/,
                loader: 'file-loader?name=[md5:hash:hex:20].[ext]!image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
            },
            {
                test  : /\.(eot|ttf|otf)([#?].*)?$/i,
                loader: 'file-loader?name=[md5:hash:hex:20].[ext]'
            },
            {
                test  : /\.woff2?([#?].*)?$/i,
                loader: 'url-loader?limit=10000&mimetype=application/font-woff&name=[md5:hash:hex:20].[ext]'
            },
            {
                test  : /\.(mp3|mp4)$/,
                loader: 'file-loader?name=[md5:hash:hex:20].[ext]'
            },

            {
                test  : /\.js$/,
                loader: 'ng-annotate-loader?sourceMap!adjust-sourcemap-loader?format=absolute!nginject-loader?sourceMap&deprecate&singleQuote!babel-loader?sourceMap&ignore=buffer&compact=false&cacheDirectory=.babel'
            },
            {
                test   : /\.html$/,
                exclude: /index\.html$/,
                loader : 'html-loader?interpolate&removeComments=false&attrs=img:src link:href'
            }
        ]
    }
};<|endoftext|>


<commit_before>import expect, { spyOn } from 'expect'
import StyleValidator from '../src/StyleValidator'

describe('StyleValidator', () => {
  it('returns an error when strict and an unknown style prop is used', () => {
    const val = new StyleValidator()
    const result = val.validate({ transform: 'scale(2)' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result.message).toBe('Unknown style property `transform` supplied to `<Test>`.')
  })

  it('does not return an error when not strict and an unknown style prop is used', () => {
    const val = new StyleValidator({ strict: false })
    const result = val.validate({ transform: 'scale(2)' }, '<Test>')
    expect(result).toBe(undefined)
  })

  it('returns an error when an unsupported style prop is used', () => {
    const val = new StyleValidator()
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result.message).toBe('Style property `list-style-position` supplied to `<Test>` unsupported in: outlook, outlook-web.')
  })

  it('does not return an error when no platforms specified', () => {
    const val = new StyleValidator({ platforms: [] })
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result).toBe(undefined)
  })

  it('does not return an error on a known property, but warns with comments', () => {
    const spy = spyOn(console, 'warn')
    const val = new StyleValidator({ platforms: ['gmail-android', 'yahoo-mail'] })
    const result = val.validate({ backgroundSize: '11px' }, '<Test>')
    expect(spy).toHaveBeenCalledWith('Warning: Style property `background-size` supplied to `<Test>`, in gmail-android, yahoo-mail: image not stretched')
    expect(result).toBe(undefined)
    spy.restore()
  })

  it('treats hyphenated-lowercase property names the same as camelCase', () => {
    const val = new StyleValidator()
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    const result2 = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result2 instanceof Error).toBe(true)
    expect(result.message).toBe(result2.message)
  })

  it('changes requirements after setConfig called', () => {
    const val = new StyleValidator()
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result.message).toBe('Style property `list-style-position` supplied to `<Test>` unsupported in: outlook, outlook-web.')
    val.setConfig({ platforms: ['gmail'] })
    const result2 = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result2).toBe(undefined)
  })
})
<commit_msg>Move console.warn spy as tightly as possible around usage<commit_after>import expect, { spyOn } from 'expect'
import StyleValidator from '../src/StyleValidator'

describe('StyleValidator', () => {
  it('returns an error when strict and an unknown style prop is used', () => {
    const val = new StyleValidator()
    const result = val.validate({ transform: 'scale(2)' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result.message).toBe('Unknown style property `transform` supplied to `<Test>`.')
  })

  it('does not return an error when not strict and an unknown style prop is used', () => {
    const val = new StyleValidator({ strict: false })
    const result = val.validate({ transform: 'scale(2)' }, '<Test>')
    expect(result).toBe(undefined)
  })

  it('returns an error when an unsupported style prop is used', () => {
    const val = new StyleValidator()
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result.message).toBe('Style property `list-style-position` supplied to `<Test>` unsupported in: outlook, outlook-web.')
  })

  it('does not return an error when no platforms specified', () => {
    const val = new StyleValidator({ platforms: [] })
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result).toBe(undefined)
  })

  it('does not return an error on a known property, but warns with comments', () => {
    const val = new StyleValidator({ platforms: ['gmail-android', 'yahoo-mail'] })
    const spy = spyOn(console, 'warn')
    const result = val.validate({ backgroundSize: '11px' }, '<Test>')
    spy.restore()
    expect(spy).toHaveBeenCalledWith('Warning: Style property `background-size` supplied to `<Test>`, in gmail-android, yahoo-mail: image not stretched')
    expect(result).toBe(undefined)
  })

  it('treats hyphenated-lowercase property names the same as camelCase', () => {
    const val = new StyleValidator()
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    const result2 = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result2 instanceof Error).toBe(true)
    expect(result.message).toBe(result2.message)
  })

  it('changes requirements after setConfig called', () => {
    const val = new StyleValidator()
    const result = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result instanceof Error).toBe(true)
    expect(result.message).toBe('Style property `list-style-position` supplied to `<Test>` unsupported in: outlook, outlook-web.')
    val.setConfig({ platforms: ['gmail'] })
    const result2 = val.validate({ listStylePosition: 'inside' }, '<Test>')
    expect(result2).toBe(undefined)
  })
})
<|endoftext|>


<commit_before>"use strict";

require("should");
const path = require("path");
const fs = require("fs");
const vm = require("vm");
const Test = require("mocha/lib/test");
const mkdirp = require("mkdirp");
const checkArrayExpectation = require("./checkArrayExpectation");

const Stats = require("../lib/Stats");
const webpack = require("../lib/webpack");

function copyDiff(src, dest) {
	if (!fs.existsSync(dest)) fs.mkdirSync(dest);
	const files = fs.readdirSync(src);
	files.forEach(filename => {
		const srcFile = path.join(src, filename);
		const destFile = path.join(dest, filename);
		const directory = fs.statSync(srcFile).isDirectory();
		if (directory) {
			copyDiff(srcFile, destFile);
		} else {
			var content = fs.readFileSync(srcFile);
			if (/^DELETE\s*$/.test(content.toString("utf-8")))
				fs.unlinkSync(destFile);
			else fs.writeFileSync(destFile, content);
		}
	});
}

function remove(src) {
	if (!fs.existsSync(src)) return;
	const files = fs.readdirSync(src);
	files.forEach(filename => {
		const srcFile = path.join(src, filename);
		const directory = fs.statSync(srcFile).isDirectory();
		if (directory) {
			remove(srcFile);
		} else {
			fs.unlinkSync(srcFile);
		}
	});
}

describe("WatchTestCases", () => {
	if (process.env.NO_WATCH_TESTS) {
		it("long running tests excluded");
		return;
	}

	const casesPath = path.join(__dirname, "watchCases");
	let categories = fs.readdirSync(casesPath);

	categories = categories.map(cat => {
		return {
			name: cat,
			tests: fs
				.readdirSync(path.join(casesPath, cat))
				.filter(folder => folder.indexOf("_") < 0)
				.sort()
		};
	});
	before(() => {
		let dest = path.join(__dirname, "js");
		if (!fs.existsSync(dest)) fs.mkdirSync(dest);
		dest = path.join(__dirname, "js", "watch-src");
		if (!fs.existsSync(dest)) fs.mkdirSync(dest);
	});
	categories.forEach(category => {
		before(() => {
			const dest = path.join(__dirname, "js", "watch-src", category.name);
			if (!fs.existsSync(dest)) fs.mkdirSync(dest);
		});
		describe(category.name, () => {
			category.tests.forEach(testName => {
				describe(testName, () => {
					const tempDirectory = path.join(
						__dirname,
						"js",
						"watch-src",
						category.name,
						testName
					);
					const testDirectory = path.join(casesPath, category.name, testName);
					const runs = fs
						.readdirSync(testDirectory)
						.sort()
						.filter(name => {
							return fs.statSync(path.join(testDirectory, name)).isDirectory();
						})
						.map(name => {
							return {
								name: name,
								suite: describe(name, () => {})
							};
						});
					before(() => remove(tempDirectory));
					it("should compile", function(done) {
						this.timeout(45000);
						const outputDirectory = path.join(
							__dirname,
							"js",
							"watch",
							category.name,
							testName
						);

						let options = {};
						const configPath = path.join(testDirectory, "webpack.config.js");
						if (fs.existsSync(configPath)) options = require(configPath);
						const applyConfig = options => {
							if (!options.mode) options.mode = "development";
							if (!options.context) options.context = tempDirectory;
							if (!options.entry) options.entry = "./index.js";
							if (!options.target) options.target = "async-node";
							if (!options.output) options.output = {};
							if (!options.output.path) options.output.path = outputDirectory;
							if (typeof options.output.pathinfo === "undefined")
								options.output.pathinfo = true;
							if (!options.output.filename)
								options.output.filename = "bundle.js";
						};
						if (Array.isArray(options)) {
							options.forEach(applyConfig);
						} else {
							applyConfig(options);
						}

						const state = {};
						let runIdx = 0;
						let waitMode = false;
						let run = runs[runIdx];
						let triggeringFilename;
						let lastHash = "";
						const currentWatchStepModule = require("./helpers/currentWatchStep");
						currentWatchStepModule.step = run.name;
						copyDiff(path.join(testDirectory, run.name), tempDirectory);

						setTimeout(() => {
							const compiler = webpack(options);
							compiler.hooks.invalid.tap(
								"WatchTestCasesTest",
								(filename, mtime) => {
									triggeringFilename = filename;
								}
							);
							const watching = compiler.watch(
								{
									aggregateTimeout: 1000
								},
								(err, stats) => {
									if (err) return done(err);
									if (!stats)
										return done(new Error("No stats reported from Compiler"));
									if (stats.hash === lastHash) return;
									lastHash = stats.hash;
									if (run.done && lastHash !== stats.hash) {
										return done(
											new Error(
												"Compilation changed but no change was issued " +
													lastHash +
													" != " +
													stats.hash +
													" (run " +
													runIdx +
													")\n" +
													"Triggering change: " +
													triggeringFilename
											)
										);
									}
									if (waitMode) return;
									run.done = true;
									if (err) return done(err);
									const statOptions = Stats.presetToOptions("verbose");
									statOptions.colors = false;
									mkdirp.sync(outputDirectory);
									fs.writeFileSync(
										path.join(outputDirectory, "stats.txt"),
										stats.toString(statOptions),
										"utf-8"
									);
									const jsonStats = stats.toJson({
										errorDetails: true
									});
									if (
										checkArrayExpectation(
											path.join(testDirectory, run.name),
											jsonStats,
											"error",
											"Error",
											done
										)
									)
										return;
									if (
										checkArrayExpectation(
											path.join(testDirectory, run.name),
											jsonStats,
											"warning",
											"Warning",
											done
										)
									)
										return;
									let exportedTests = 0;

									function _it(title, fn) {
										const test = new Test(title, fn);
										run.suite.addTest(test);
										exportedTests++;
										return test;
									}

									const globalContext = {
										console: console
									};

									function _require(currentDirectory, module) {
										if (Array.isArray(module) || /^\.\.?\//.test(module)) {
											let fn;
											let content;
											let p;
											if (Array.isArray(module)) {
												p = path.join(currentDirectory, module[0]);
												content = module
													.map(arg => {
														p = path.join(currentDirectory, arg);
														return fs.readFileSync(p, "utf-8");
													})
													.join("\n");
											} else {
												p = path.join(currentDirectory, module);
												content = fs.readFileSync(p, "utf-8");
											}
											if (
												options.target === "web" ||
												options.target === "webworker"
											) {
												fn = vm.runInNewContext(
													"(function(require, module, exports, __dirname, __filename, it, WATCH_STEP, STATS_JSON, STATE, window) {" +
														content +
														"\n})",
													globalContext,
													p
												);
											} else {
												fn = vm.runInThisContext(
													"(function(require, module, exports, __dirname, __filename, it, WATCH_STEP, STATS_JSON, STATE) {" +
														content +
														"\n})",
													p
												);
											}
											const m = {
												exports: {}
											};
											fn.call(
												m.exports,
												_require.bind(null, path.dirname(p)),
												m,
												m.exports,
												path.dirname(p),
												p,
												_it,
												run.name,
												jsonStats,
												state,
												globalContext
											);
											return module.exports;
										} else if (
											testConfig.modules &&
											module in testConfig.modules
										) {
											return testConfig.modules[module];
										} else return require(module);
									}

									let testConfig = {};
									try {
										// try to load a test file
										testConfig = require(path.join(
											testDirectory,
											"test.config.js"
										));
									} catch (e) {} // eslint-disable-line no-empty

									if (testConfig.noTests) return process.nextTick(done);
									_require(
										outputDirectory,
										testConfig.bundlePath || "./bundle.js"
									);

									if (exportedTests < 1)
										return done(new Error("No tests exported by test case"));
									runIdx++;
									if (runIdx < runs.length) {
										run = runs[runIdx];
										waitMode = true;
										setTimeout(() => {
											waitMode = false;
											currentWatchStepModule.step = run.name;
											copyDiff(
												path.join(testDirectory, run.name),
												tempDirectory
											);
										}, 1500);
									} else {
										watching.close();
										process.nextTick(done);
									}
								}
							);
						}, 300);
					});
				});
			});
		});
	});
});
<commit_msg>fix timestamp issue in WatchTestCases<commit_after>"use strict";

require("should");
const path = require("path");
const fs = require("fs");
const vm = require("vm");
const Test = require("mocha/lib/test");
const mkdirp = require("mkdirp");
const checkArrayExpectation = require("./checkArrayExpectation");

const Stats = require("../lib/Stats");
const webpack = require("../lib/webpack");

function copyDiff(src, dest, initial) {
	if (!fs.existsSync(dest)) fs.mkdirSync(dest);
	const files = fs.readdirSync(src);
	files.forEach(filename => {
		const srcFile = path.join(src, filename);
		const destFile = path.join(dest, filename);
		const directory = fs.statSync(srcFile).isDirectory();
		if (directory) {
			copyDiff(srcFile, destFile, initial);
		} else {
			var content = fs.readFileSync(srcFile);
			if (/^DELETE\s*$/.test(content.toString("utf-8"))) {
				fs.unlinkSync(destFile);
			} else {
				fs.writeFileSync(destFile, content);
				if (initial) {
					const longTimeAgo = Date.now() - 1000 * 60 * 60 * 24;
					fs.utimesSync(
						destFile,
						Date.now() - longTimeAgo,
						Date.now() - longTimeAgo
					);
				}
			}
		}
	});
}

function remove(src) {
	if (!fs.existsSync(src)) return;
	const files = fs.readdirSync(src);
	files.forEach(filename => {
		const srcFile = path.join(src, filename);
		const directory = fs.statSync(srcFile).isDirectory();
		if (directory) {
			remove(srcFile);
		} else {
			fs.unlinkSync(srcFile);
		}
	});
}

describe("WatchTestCases", () => {
	if (process.env.NO_WATCH_TESTS) {
		it("long running tests excluded");
		return;
	}

	const casesPath = path.join(__dirname, "watchCases");
	let categories = fs.readdirSync(casesPath);

	categories = categories.map(cat => {
		return {
			name: cat,
			tests: fs
				.readdirSync(path.join(casesPath, cat))
				.filter(folder => folder.indexOf("_") < 0)
				.sort()
		};
	});
	before(() => {
		let dest = path.join(__dirname, "js");
		if (!fs.existsSync(dest)) fs.mkdirSync(dest);
		dest = path.join(__dirname, "js", "watch-src");
		if (!fs.existsSync(dest)) fs.mkdirSync(dest);
	});
	categories.forEach(category => {
		before(() => {
			const dest = path.join(__dirname, "js", "watch-src", category.name);
			if (!fs.existsSync(dest)) fs.mkdirSync(dest);
		});
		describe(category.name, () => {
			category.tests.forEach(testName => {
				describe(testName, () => {
					const tempDirectory = path.join(
						__dirname,
						"js",
						"watch-src",
						category.name,
						testName
					);
					const testDirectory = path.join(casesPath, category.name, testName);
					const runs = fs
						.readdirSync(testDirectory)
						.sort()
						.filter(name => {
							return fs.statSync(path.join(testDirectory, name)).isDirectory();
						})
						.map(name => {
							return {
								name: name,
								suite: describe(name, () => {})
							};
						});
					before(() => remove(tempDirectory));
					it("should compile", function(done) {
						this.timeout(45000);
						const outputDirectory = path.join(
							__dirname,
							"js",
							"watch",
							category.name,
							testName
						);

						let options = {};
						const configPath = path.join(testDirectory, "webpack.config.js");
						if (fs.existsSync(configPath)) options = require(configPath);
						const applyConfig = options => {
							if (!options.mode) options.mode = "development";
							if (!options.context) options.context = tempDirectory;
							if (!options.entry) options.entry = "./index.js";
							if (!options.target) options.target = "async-node";
							if (!options.output) options.output = {};
							if (!options.output.path) options.output.path = outputDirectory;
							if (typeof options.output.pathinfo === "undefined")
								options.output.pathinfo = true;
							if (!options.output.filename)
								options.output.filename = "bundle.js";
						};
						if (Array.isArray(options)) {
							options.forEach(applyConfig);
						} else {
							applyConfig(options);
						}

						const state = {};
						let runIdx = 0;
						let waitMode = false;
						let run = runs[runIdx];
						let triggeringFilename;
						let lastHash = "";
						const currentWatchStepModule = require("./helpers/currentWatchStep");
						currentWatchStepModule.step = run.name;
						copyDiff(path.join(testDirectory, run.name), tempDirectory, true);

						setTimeout(() => {
							const compiler = webpack(options);
							compiler.hooks.invalid.tap(
								"WatchTestCasesTest",
								(filename, mtime) => {
									triggeringFilename = filename;
								}
							);
							const watching = compiler.watch(
								{
									aggregateTimeout: 1000
								},
								(err, stats) => {
									if (err) return done(err);
									if (!stats)
										return done(new Error("No stats reported from Compiler"));
									if (stats.hash === lastHash) return;
									lastHash = stats.hash;
									if (run.done && lastHash !== stats.hash) {
										return done(
											new Error(
												"Compilation changed but no change was issued " +
													lastHash +
													" != " +
													stats.hash +
													" (run " +
													runIdx +
													")\n" +
													"Triggering change: " +
													triggeringFilename
											)
										);
									}
									if (waitMode) return;
									run.done = true;
									if (err) return done(err);
									const statOptions = Stats.presetToOptions("verbose");
									statOptions.colors = false;
									mkdirp.sync(outputDirectory);
									fs.writeFileSync(
										path.join(outputDirectory, "stats.txt"),
										stats.toString(statOptions),
										"utf-8"
									);
									const jsonStats = stats.toJson({
										errorDetails: true
									});
									if (
										checkArrayExpectation(
											path.join(testDirectory, run.name),
											jsonStats,
											"error",
											"Error",
											done
										)
									)
										return;
									if (
										checkArrayExpectation(
											path.join(testDirectory, run.name),
											jsonStats,
											"warning",
											"Warning",
											done
										)
									)
										return;
									let exportedTests = 0;

									function _it(title, fn) {
										const test = new Test(title, fn);
										run.suite.addTest(test);
										exportedTests++;
										return test;
									}

									const globalContext = {
										console: console
									};

									function _require(currentDirectory, module) {
										if (Array.isArray(module) || /^\.\.?\//.test(module)) {
											let fn;
											let content;
											let p;
											if (Array.isArray(module)) {
												p = path.join(currentDirectory, module[0]);
												content = module
													.map(arg => {
														p = path.join(currentDirectory, arg);
														return fs.readFileSync(p, "utf-8");
													})
													.join("\n");
											} else {
												p = path.join(currentDirectory, module);
												content = fs.readFileSync(p, "utf-8");
											}
											if (
												options.target === "web" ||
												options.target === "webworker"
											) {
												fn = vm.runInNewContext(
													"(function(require, module, exports, __dirname, __filename, it, WATCH_STEP, STATS_JSON, STATE, window) {" +
														content +
														"\n})",
													globalContext,
													p
												);
											} else {
												fn = vm.runInThisContext(
													"(function(require, module, exports, __dirname, __filename, it, WATCH_STEP, STATS_JSON, STATE) {" +
														content +
														"\n})",
													p
												);
											}
											const m = {
												exports: {}
											};
											fn.call(
												m.exports,
												_require.bind(null, path.dirname(p)),
												m,
												m.exports,
												path.dirname(p),
												p,
												_it,
												run.name,
												jsonStats,
												state,
												globalContext
											);
											return module.exports;
										} else if (
											testConfig.modules &&
											module in testConfig.modules
										) {
											return testConfig.modules[module];
										} else return require(module);
									}

									let testConfig = {};
									try {
										// try to load a test file
										testConfig = require(path.join(
											testDirectory,
											"test.config.js"
										));
									} catch (e) {} // eslint-disable-line no-empty

									if (testConfig.noTests) return process.nextTick(done);
									_require(
										outputDirectory,
										testConfig.bundlePath || "./bundle.js"
									);

									if (exportedTests < 1)
										return done(new Error("No tests exported by test case"));
									runIdx++;
									if (runIdx < runs.length) {
										run = runs[runIdx];
										waitMode = true;
										setTimeout(() => {
											waitMode = false;
											currentWatchStepModule.step = run.name;
											copyDiff(
												path.join(testDirectory, run.name),
												tempDirectory,
												false
											);
										}, 1500);
									} else {
										watching.close();
										process.nextTick(done);
									}
								}
							);
						}, 300);
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>define(['squire', 'jquery'], function (Squire, $) {
    describe('amdInitializer', function () {
        var amdInitializer;
        var initializerApi;
        var module1;
        var module2;

        beforeEach(function (done) {
            var injector = new Squire();

            module1 = jasmine.createSpyObj('module1', ['load']);
            module2 = jasmine.createSpyObj('module2', ['load']);
            var require = function () {
                injector.require.apply(injector, arguments);
            };
            var mocks = {
                'amdInitializer/require': require,
                'path/to/module1': module1,
                'path/to/module2': module2
            };

            injector.mock(mocks);
            injector.require(['amdInitializer'], function (loadedAmdInitializer) {
                amdInitializer = loadedAmdInitializer;
                done();
            });
        });

        afterEach(function () {
            initializerApi.unload();
        });

        var insertIntoDom = function (markup) {
            setFixtures('
' + markup + '
');
            return $('.target');
        };

        var invokeLoad = function (options) {
            initializerApi = amdInitializer.load(options);
        };

        it('should call load on the loaded module', function (done) {
            var $target = insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalled();
                var loadArgs = module1.load.calls.mostRecent().args;
                expect(loadArgs[0][0]).toBe($target.find('.module')[0], 'the element passed to the module');
                expect(loadArgs[1]).toEqual({}, 'the parameters passed to the module');
                done();
            });
        });

        it('should pass parameters indicated by the markup to the loaded module', function (done) {

            insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalledWith(jasmine.any(Object), {
                    parameterOne: 'param-1',
                    parameterTwo: 'param2'
                });
                done();
            });
        });

        it('should raise an event when the module has loaded', function (done) {
            insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.onModuleLoaded(function (moduleDetails) {
                expect(moduleDetails.name).toBe('path/to/module1');
                done();
            });
        });

        it('should load multiple modules', function (done) {
            insertIntoDom('

' +
                '

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalled();
                expect(module2.load).toHaveBeenCalled();
                done();
            });
        });

        it('should allow callers to register to errors thrown by modules', function (done) {
            insertIntoDom('

' +
                '

');
            var error = new Error('module1 failed to load');
            module1.load.and.throwError(error);
            invokeLoad({ selector: '.module' });
            var onModuleError = jasmine.createSpy('onModuleError');
            initializerApi.onModuleError(onModuleError);

            initializerApi.initialModulesLoaded.then(function () {
                expect(onModuleError).toHaveBeenCalledWith({ exception: error });
                done();
            });
        });

        it('should continue loading other modules if the first one throws an exception', function (done) {
            insertIntoDom('

' +
                '

');
            module1.load.and.throwError('module1 failed to load');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalled();
                expect(module2.load).toHaveBeenCalled();
                done();
            });
        });

        it('should load a module whose markup is added after initialize has been invoked', function (done) {
            var $target = insertIntoDom('');
            invokeLoad({ selector: '.module' });
            $target.append('

');

            initializerApi.onModuleLoaded(function () {
                expect(module1.load.calls.count()).toBe(1, 'the number of times module1.load gets called');
                done();
            });
        });

        it('should mark modules that have been loaded with a data-module-loaded attribute', function (done) {
            var $target = insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect($target.find('.module')).toHaveAttr('data-module-loaded', 'true');
                done();
            });
        });

        it('should not load modules marked with the data-module-loaded attribute', function (done) {
            insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).not.toHaveBeenCalled();
                done();
            });
        });

        it('should allow watching the dom to be disabled', function (done) {
            invokeLoad({ selector: '.module', watchDom: false });
            insertIntoDom('

');

            //TODO: Find a way to test this without using setTimeout
            setTimeout(function () {
                expect(module1.load).not.toHaveBeenCalled();
                done();
            }, 100);
        });
    });
});<commit_msg>Refactor disable dom watching test to not use set timeout<commit_after>define(['squire', 'jquery', 'skate'], function (Squire, $, Skate) {
    describe('amdInitializer', function () {
        var amdInitializer;
        var initializerApi;
        var module1;
        var module2;
        var injectedSkate;

        beforeEach(function (done) {
            var injector = new Squire();

            module1 = jasmine.createSpyObj('module1', ['load']);
            module2 = jasmine.createSpyObj('module2', ['load']);
            injectedSkate = jasmine.createSpy('skate').and.callFake(function () {
                return Skate.apply(Skate, arguments);
            });
            var require = function () {
                injector.require.apply(injector, arguments);
            };
            var mocks = {
                'amdInitializer/require': require,
                'path/to/module1': module1,
                'path/to/module2': module2,
                'skate': injectedSkate
            };

            injector.mock(mocks);
            injector.require(['amdInitializer'], function (loadedAmdInitializer) {
                amdInitializer = loadedAmdInitializer;
                done();
            });
        });

        afterEach(function () {
            initializerApi.unload();
        });

        var insertIntoDom = function (markup) {
            setFixtures('
' + markup + '
');
            return $('.target');
        };

        var invokeLoad = function (options) {
            initializerApi = amdInitializer.load(options);
        };

        it('should call load on the loaded module', function (done) {
            var $target = insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalled();
                var loadArgs = module1.load.calls.mostRecent().args;
                expect(loadArgs[0][0]).toBe($target.find('.module')[0], 'the element passed to the module');
                expect(loadArgs[1]).toEqual({}, 'the parameters passed to the module');
                done();
            });
        });

        it('should pass parameters indicated by the markup to the loaded module', function (done) {

            insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalledWith(jasmine.any(Object), {
                    parameterOne: 'param-1',
                    parameterTwo: 'param2'
                });
                done();
            });
        });

        it('should raise an event when the module has loaded', function (done) {
            insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.onModuleLoaded(function (moduleDetails) {
                expect(moduleDetails.name).toBe('path/to/module1');
                done();
            });
        });

        it('should load multiple modules', function (done) {
            insertIntoDom('

' +
                '

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalled();
                expect(module2.load).toHaveBeenCalled();
                done();
            });
        });

        it('should allow callers to register to errors thrown by modules', function (done) {
            insertIntoDom('

' +
                '

');
            var error = new Error('module1 failed to load');
            module1.load.and.throwError(error);
            invokeLoad({ selector: '.module' });
            var onModuleError = jasmine.createSpy('onModuleError');
            initializerApi.onModuleError(onModuleError);

            initializerApi.initialModulesLoaded.then(function () {
                expect(onModuleError).toHaveBeenCalledWith({ exception: error });
                done();
            });
        });

        it('should continue loading other modules if the first one throws an exception', function (done) {
            insertIntoDom('

' +
                '

');
            module1.load.and.throwError('module1 failed to load');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).toHaveBeenCalled();
                expect(module2.load).toHaveBeenCalled();
                done();
            });
        });

        it('should load a module whose markup is added after initialize has been invoked', function (done) {
            var $target = insertIntoDom('');
            invokeLoad({ selector: '.module' });
            $target.append('

');

            initializerApi.onModuleLoaded(function () {
                expect(module1.load.calls.count()).toBe(1, 'the number of times module1.load gets called');
                done();
            });
        });

        it('should mark modules that have been loaded with a data-module-loaded attribute', function (done) {
            var $target = insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect($target.find('.module')).toHaveAttr('data-module-loaded', 'true');
                done();
            });
        });

        it('should not load modules marked with the data-module-loaded attribute', function (done) {
            insertIntoDom('

');
            invokeLoad({ selector: '.module' });

            initializerApi.initialModulesLoaded.then(function () {
                expect(module1.load).not.toHaveBeenCalled();
                done();
            });
        });

        it('should allow watching the dom to be disabled', function () {
            invokeLoad({ selector: '.module', watchDom: false });
            insertIntoDom('

');

            expect(injectedSkate).not.toHaveBeenCalled();
        });
    });
});<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var dns = require('dns');
var net = require('net');
var crypto = require('crypto');
var FakeSocket = require('./fake-socket').FakeSocket;

function passthroughApi(message, callback) {
	var args;
	if (typeof message.data === 'string') {
		args = [message.data];
	} else if (typeof message.data === 'object') {
		args = message.data;
	}

  var method = (message.method || '').replace(/sync/i, '');

	args.push(callback);

  switch(message.api) {
    case 'fs':
      // Make absolute paths relative
      // (They are absolute from the perspect of the sandboxed code)
      if (args[0].indexOf('/') === 0) {
        args[0] = '.' + args[0];
      }
      fs[method].apply(null, args);
      break;
    case 'dns':
      dns[method].apply(null, args);
      break;
    case 'net':
    	var sock;
      switch (method) {
    		case 'socket':
    			sock = new FakeSocket(args[0], args[1], args[2]);
      		var connectionId = this._connections.length;
      		this._connections.push(sock);
    			args[3](null, connectionId);
    			break;
        case 'write':
          if (args[2]==="hex") {
            args[1] = new Buffer(args[1], "hex");
            args.splice(2, 1);
          }
          sock = this._connections[args[0]];
    			sock[method].apply(sock, args.slice(1));
          break;
        case 'connect':
        case 'read':
        case 'close':
          //TODO-CODIUS: If 'close', remove socket from _connections array
    			sock = this._connections[args[0]];
    			sock[method].apply(sock, args.slice(1));
    			break;
    		default:
    			callback(new Error('Unhandled net method: ' + message.method));
    	}
      break;
    case 'crypto':
      switch(method) {
        case 'randomBytes':
          // Convert the resulting buffer to hex
          function randomBytesCallback(error, result){
            if (error) {
              callback(error);
            } else if (Buffer.isBuffer(result)) {
              result = result.toString('hex');
              callback(null, result);
            }
          }

          args[args.length - 1] = randomBytesCallback;
          crypto.randomBytes.apply(null, args);
          break;
        default:
    			callback(new Error('Unhandled net method: ' + message.method));
      }
      break;
    default:
      callback(new Error('Unhandled api type: ' + message.api));
  }
}

exports.passthroughApi = passthroughApi;
<commit_msg>[FIX] FakeSocket connections array<commit_after>var fs = require('fs');
var path = require('path');
var dns = require('dns');
var net = require('net');
var crypto = require('crypto');
var FakeSocket = require('./fake-socket').FakeSocket;

var socket_connections = [null, null, null, null, null];

function passthroughApi(message, callback) {
	var args;
	if (typeof message.data === 'string') {
		args = [message.data];
	} else if (typeof message.data === 'object') {
		args = message.data;
	}

  var method = (message.method || '').replace(/Sync$/, '');

	args.push(callback);

  switch(message.api) {
    case 'fs':
      // Make absolute paths relative
      // (They are absolute from the perspect of the sandboxed code)
      if (typeof args[0] === 'string' && args[0].indexOf('/') === 0) {
        args[0] = '.' + args[0];
      }
      fs[method].apply(null, args);
      break;
    case 'dns':
      dns[method].apply(null, args);
      break;
    case 'net':
    	var sock;
      switch (method) {
    		case 'socket':
    			sock = new FakeSocket(args[0], args[1], args[2]);
      		var connectionId = socket_connections.length;
      		socket_connections.push(sock);
    			args[3](null, connectionId);
    			break;
        case 'write':
          if (args[2]==="hex") {
            args[1] = new Buffer(args[1], "hex");
            args.splice(2, 1);
          }
          sock = socket_connections[args[0]];
    			sock[method].apply(sock, args.slice(1));
          break;
        case 'connect':
        case 'read':
        case 'close':
          //TODO-CODIUS: If 'close', remove socket from _connections array
    			sock = socket_connections[args[0]];
    			sock[method].apply(sock, args.slice(1));
    			break;
    		default:
    			callback(new Error('Unhandled net method: ' + message.method));
    	}
      break;
    case 'crypto':
      switch(method) {
        case 'randomBytes':
          // Convert the resulting buffer to hex
          function randomBytesCallback(error, result){
            if (error) {
              callback(error);
            } else if (Buffer.isBuffer(result)) {
              result = result.toString('hex');
              callback(null, result);
            }
          }

          args[args.length - 1] = randomBytesCallback;
          crypto.randomBytes.apply(null, args);
          break;
        default:
    			callback(new Error('Unhandled net method: ' + message.method));
      }
      break;
    default:
      callback(new Error('Unhandled api type: ' + message.api));
  }
}

exports.passthroughApi = passthroughApi;
<|endoftext|>


<commit_before>// Adapted from: https://github.com/h5bp/html5-boilerplate/blob/master/test/file_existence.js
// Adapted parts: Copyright (c) HTML5 Boilerplate
"use strict";

var assert = require("assert");
var fs = require("fs");
var path = require("path");

var pkg = require("./../../package.json");
var dirs = pkg.projectConfig.dirs;

var defaultExpectedFiles = [
    "index.html",

    "js/",
        "js/main.js",
];

var expectedFilesInDistDirs = [

    {
        dir: "basic-example",
        files: defaultExpectedFiles
    },
    {
        dir: "basic-with-require-example",
        files: defaultExpectedFiles
    },
    {
        dir: "js-hint-example",
        files: defaultExpectedFiles
    },
    {
        dir: "jscs-example",
        files: defaultExpectedFiles
    },
    {
        dir: "webpack-dev-server-example",
        files: defaultExpectedFiles
    },
    {
        dir: "jsx-example",
        files: defaultExpectedFiles
    },
    {
        dir: "jsx-imports-example",
        files: defaultExpectedFiles
    },
    {
        dir: "html-plugin-example",
        files: defaultExpectedFiles
    },
    {
        dir: "style-css-inline-example",
        files: defaultExpectedFiles
    },
    {
        dir: "style-css-link-example",
        files: defaultExpectedFiles.concat([
            "css/",
                /css\/[a-zA-Z0-9]+\.css/
        ])
    },
    {
        dir: "html-plugin-with-hashes-example",
        files: [
            "index.html",

            "js/",
                /js\/main-[a-zA-Z0-9]+\.js/,
        ]
    },
    {
        dir: "coffeescript-example",
        files: [
            "index.html",

            "js/",
                /js\/main-[a-zA-Z0-9]+\.js/,
        ]
    },
    {
        dir: "typescript-example",
        files: [
            "index.html",

            "js/",
                /js\/main-[a-zA-Z0-9]+\.js/,
        ]
    }

];

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

function checkFiles(directory, expectedFiles) {

    // Get the list of files from the specified directory
    var files = require("glob").sync("**/*", {
        cwd: directory,
        dot: true,      // include hidden files
        mark: true      // add a `/` character to directory matches
    });
    var filesAsString = files.join("|");

    // Check if all expected files are present in the
    // specified directory, and are of the expected type
    expectedFiles.forEach(function(file) {

        var ok = false;

        // If file exists
        if (files.indexOf(file) !== -1) {
            var expectedFileType = "/" !== file.slice(-1) ? "regular file" : "directory";

            // Check if the file is of the correct type
            if ("/" !== file.slice(-1)) {
                // Check if the file is really a regular file
                ok = fs.statSync(path.resolve(directory, file)).isFile();
            } else {
                // Check if the file is a directory
                // (Since glob adds the `/` character to directory matches,
                // we can simply check if the `/` character is present)
                ok = "/" === files[files.indexOf(file)].slice(-1);
            }

            it('"' + file + '" should be present and should be a ' + expectedFileType, function() {
                assert.equal(true, ok);
            });

            return;

        } else if ("[object RegExp]" === Object.prototype.toString.call(file)) {
            ok = file.test(filesAsString);
            // remove matches to avoid the non-found rule
            filesAsString = filesAsString.replace(file, "");
        }

        it('"' + file + '" should be present', function() {
            assert.equal(true, ok);
        });

    });

    // List all files that should be NOT
    // be present in the specified directory
    (filesAsString.split("|").filter(function(file) {
        return "" !== file && expectedFiles.indexOf(file) === -1;
    })).forEach(function(file) {
        it('"' + file + '" should NOT be present', function() {
            assert(false);
        });
    });

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

describe("Test if all the expected files, and only them, are present in the build directories", function() {

    expectedFilesInDistDirs.forEach(function(distDir) {
        var distDirName = path.join(distDir.dir, dirs.dist);
        describe(distDirName, function() {
            checkFiles(distDirName, distDir.files);
        });
    });

});
<commit_msg>Refactor built files tests for hashed js<commit_after>// Adapted from: https://github.com/h5bp/html5-boilerplate/blob/master/test/file_existence.js
// Adapted parts: Copyright (c) HTML5 Boilerplate
"use strict";

var assert = require("assert");
var fs = require("fs");
var path = require("path");

var pkg = require("./../../package.json");
var dirs = pkg.projectConfig.dirs;

var defaultExpectedFiles = [
    "index.html",

    "js/",
        "js/main.js",
];

var defaultExpectedFilesWithHashedJs = [
    "index.html",

    "js/",
        /js\/main-[a-zA-Z0-9]+\.js/,
];

var expectedFilesInDistDirs = [

    {
        dir: "basic-example",
        files: defaultExpectedFiles
    },
    {
        dir: "basic-with-require-example",
        files: defaultExpectedFiles
    },
    {
        dir: "js-hint-example",
        files: defaultExpectedFiles
    },
    {
        dir: "jscs-example",
        files: defaultExpectedFiles
    },
    {
        dir: "webpack-dev-server-example",
        files: defaultExpectedFiles
    },
    {
        dir: "jsx-example",
        files: defaultExpectedFiles
    },
    {
        dir: "jsx-imports-example",
        files: defaultExpectedFiles
    },
    {
        dir: "html-plugin-example",
        files: defaultExpectedFiles
    },
    {
        dir: "style-css-inline-example",
        files: defaultExpectedFiles
    },
    {
        dir: "style-css-link-example",
        files: defaultExpectedFiles.concat([
            "css/",
                /css\/[a-zA-Z0-9]+\.css/
        ])
    },
    {
        dir: "html-plugin-with-hashes-example",
        files: defaultExpectedFilesWithHashedJs
    },
    {
        dir: "coffeescript-example",
        files: defaultExpectedFilesWithHashedJs
    },
    {
        dir: "typescript-example",
        files: defaultExpectedFilesWithHashedJs
    }

];

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

function checkFiles(directory, expectedFiles) {

    // Get the list of files from the specified directory
    var files = require("glob").sync("**/*", {
        cwd: directory,
        dot: true,      // include hidden files
        mark: true      // add a `/` character to directory matches
    });
    var filesAsString = files.join("|");

    // Check if all expected files are present in the
    // specified directory, and are of the expected type
    expectedFiles.forEach(function(file) {

        var ok = false;

        // If file exists
        if (files.indexOf(file) !== -1) {
            var expectedFileType = "/" !== file.slice(-1) ? "regular file" : "directory";

            // Check if the file is of the correct type
            if ("/" !== file.slice(-1)) {
                // Check if the file is really a regular file
                ok = fs.statSync(path.resolve(directory, file)).isFile();
            } else {
                // Check if the file is a directory
                // (Since glob adds the `/` character to directory matches,
                // we can simply check if the `/` character is present)
                ok = "/" === files[files.indexOf(file)].slice(-1);
            }

            it('"' + file + '" should be present and should be a ' + expectedFileType, function() {
                assert.equal(true, ok);
            });

            return;

        } else if ("[object RegExp]" === Object.prototype.toString.call(file)) {
            ok = file.test(filesAsString);
            // remove matches to avoid the non-found rule
            filesAsString = filesAsString.replace(file, "");
        }

        it('"' + file + '" should be present', function() {
            assert.equal(true, ok);
        });

    });

    // List all files that should be NOT
    // be present in the specified directory
    (filesAsString.split("|").filter(function(file) {
        return "" !== file && expectedFiles.indexOf(file) === -1;
    })).forEach(function(file) {
        it('"' + file + '" should NOT be present', function() {
            assert(false);
        });
    });

}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

describe("Test if all the expected files, and only them, are present in the build directories", function() {

    expectedFilesInDistDirs.forEach(function(distDir) {
        var distDirName = path.join(distDir.dir, dirs.dist);
        describe(distDirName, function() {
            checkFiles(distDirName, distDir.files);
        });
    });

});
<|endoftext|>


<commit_before>var assert = require('chai').assert,
    Reflux = require('../src'),
    Action = Reflux.createAction,
    Store = Reflux.createStore,
    fn = function(){},
    sinon = require('sinon');

describe('Stopping',function(){
    describe('a join',function(){
        var store = Store(),
            action1 = Action({sync:true}),
            action2 = Action({sync:true}),
            action3 = Action({sync:true}),
            indivcallback = sinon.spy(),
            joincallback = sinon.spy(),
            subobj;
        store.listenTo(action2,indivcallback);
        subobj = store.joinLeading(action1,action2,action3,joincallback);
        subobj.stop();
        action1("A");
        action2("B");
        action3("C");
        it('should leave the individual listening intact',function(){
            assert.equal(store.subscriptions.length,1);
            assert.equal(store.subscriptions[0].listenable,action2);
            action2("foo","bar");
            assert.deepEqual(["foo","bar"],indivcallback.lastCall.args);
        });
        it('should not fire join callback anymore',function(done){
            setTimeout(function(){
                assert.equal(joincallback.callCount,0);
                done();
            },10);
        });
    });
    describe('a single listen', function(){
        describe('by calling stop directly',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(Action(),fn);
                store.listenTo(action3,fn);
                it('should remove that listener from the list but keep the others',function(){
                    store.subscriptions[1].stop();
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
            });
            describe('when the listener has already been removed from the list somehow',function(){
                var store = Store();
                store.listenTo(Action(),fn);
                store.listenTo(Action(),fn);
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.subscriptions.pop().stop();
                    });
                });
            });
        });
        describe('by using stopListenTo',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action2 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(action2,fn);
                store.listenTo(action3,fn);
                var result = store.stopListeningTo(action2);
                it('should remove that listener from the list but keep the others',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
                it('should return true',function(){
                    assert.equal(true,result);
                });
            });
            describe('when the stop method won\'t remove it from the array',function(){
                var store = Store(),
                    action = Action();
                store.listenTo(action,fn);
                store.subscriptions[0].stop = fn;
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.stopListeningTo(action);
                    });
                });
            });
            describe('when we weren\'t actually listening to the given listenable',function(){
                var action1 = Action(),
                    action2 = Action(),
                    store = Store(),
                    result;
                store.listenTo(action1);
                store.listenTo(action2);
                result = Store().stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(false,result);
                });
                it('should leave the other listens intact',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action2,store.subscriptions[1].listenable);
                });
            });
            describe('when we don\'t have a subscriptions list',function(){
                var store = Store(), result;
                delete store.subscriptions;
                result = store.stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(result,false);
                });
            });
        });
    });
    describe('all listens',function(){
        describe('when all is well',function(){
            var store = Store();
            store.listenTo(Action(),fn);
            store.listenTo(Action(),fn);
            it('should clear the subscriptions list',function(){
                store.stopListeningToAll();
                assert.deepEqual([],store.subscriptions);
            });
        });
        describe('when a stop fails to remove the subscription object from the list',function(){
            var store = Store();
            store.listenTo(Action());
            store.subscriptions[0].stop = fn;
            it('should throw an error',function(){
                assert.throws(function(){
                    store.stopListeningToAll();
                });
            });
        });
        describe('when we don\'t have a subscriptions list',function(){
            var store = Store();
            delete store.subscriptions;
            it('should be a noop',function(){
                store.stopListeningToAll();
            });
        });
    });
});
<commit_msg>added test to prevent stopping join part<commit_after>var assert = require('chai').assert,
    Reflux = require('../src'),
    Action = Reflux.createAction,
    Store = Reflux.createStore,
    fn = function(){},
    sinon = require('sinon');

describe('Stopping',function(){
    describe('listening to a publisher that\'s only part of a join',function(){
        var store = Store(),
            action1 = Action(),
            action2 = Action();
        store.joinTrailing(action1,action2,function(){});
        it('should fail',function(){
            assert.equal(store.stopListeningTo(action1),false);
            assert.equal(store.subscriptions.length,1);
        });
    });
    describe('a join',function(){
        var store = Store(),
            action1 = Action({sync:true}),
            action2 = Action({sync:true}),
            action3 = Action({sync:true}),
            indivcallback = sinon.spy(),
            joincallback = sinon.spy(),
            subobj;
        store.listenTo(action2,indivcallback);
        subobj = store.joinLeading(action1,action2,action3,joincallback);
        subobj.stop();
        action1("A");
        action2("B");
        action3("C");
        it('should leave the individual listening intact',function(){
            assert.equal(store.subscriptions.length,1);
            assert.equal(store.subscriptions[0].listenable,action2);
            action2("foo","bar");
            assert.deepEqual(["foo","bar"],indivcallback.lastCall.args);
        });
        it('should not fire join callback anymore',function(done){
            setTimeout(function(){
                assert.equal(joincallback.callCount,0);
                done();
            },10);
        });
    });
    describe('a single listen', function(){
        describe('by calling stop directly',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(Action(),fn);
                store.listenTo(action3,fn);
                it('should remove that listener from the list but keep the others',function(){
                    store.subscriptions[1].stop();
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
            });
            describe('when the listener has already been removed from the list somehow',function(){
                var store = Store();
                store.listenTo(Action(),fn);
                store.listenTo(Action(),fn);
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.subscriptions.pop().stop();
                    });
                });
            });
        });
        describe('by using stopListenTo',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action2 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(action2,fn);
                store.listenTo(action3,fn);
                var result = store.stopListeningTo(action2);
                it('should remove that listener from the list but keep the others',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
                it('should return true',function(){
                    assert.equal(true,result);
                });
            });
            describe('when the stop method won\'t remove it from the array',function(){
                var store = Store(),
                    action = Action();
                store.listenTo(action,fn);
                store.subscriptions[0].stop = fn;
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.stopListeningTo(action);
                    });
                });
            });
            describe('when we weren\'t actually listening to the given listenable',function(){
                var action1 = Action(),
                    action2 = Action(),
                    store = Store(),
                    result;
                store.listenTo(action1);
                store.listenTo(action2);
                result = Store().stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(false,result);
                });
                it('should leave the other listens intact',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action2,store.subscriptions[1].listenable);
                });
            });
            describe('when we don\'t have a subscriptions list',function(){
                var store = Store(), result;
                delete store.subscriptions;
                result = store.stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(result,false);
                });
            });
        });
    });
    describe('all listens',function(){
        describe('when all is well',function(){
            var store = Store();
            store.listenTo(Action(),fn);
            store.listenTo(Action(),fn);
            it('should clear the subscriptions list',function(){
                store.stopListeningToAll();
                assert.deepEqual([],store.subscriptions);
            });
        });
        describe('when a stop fails to remove the subscription object from the list',function(){
            var store = Store();
            store.listenTo(Action());
            store.subscriptions[0].stop = fn;
            it('should throw an error',function(){
                assert.throws(function(){
                    store.stopListeningToAll();
                });
            });
        });
        describe('when we don\'t have a subscriptions list',function(){
            var store = Store();
            delete store.subscriptions;
            it('should be a noop',function(){
                store.stopListeningToAll();
            });
        });
    });
});
<|endoftext|>


<commit_before>// 'use strict';

describe('Routing', function () {
  var $route;

  beforeEach(function(){
    module('genome');

    inject(function ($injector) {
      // $routeProvider = $injector.get('$routeProvider');
      // $location = $injector.get('$location');
      // $routeParams = $injector.get('$routeParams');
      $route = $injector.get('$route');
    });
  });

  it('Should have /signin route, template, and controller', function () {
    expect($route.routes['/']).to.be.defined;
    expect($route.routes['/'].controller).to.equal('AuthController');
    expect($route.routes['/'].templateUrl).to.equal('/');
    // expect($route).to.exist;
  });

});
<commit_msg>Tests now working<commit_after>// 'use strict';

describe('Routing', function () {
  var $route;
  var AuthController;

  beforeEach(function(){
    module('genome');

    inject(function ($injector) {
      // $routeProvider = $injector.get('$routeProvider');
      // $location = $injector.get('$location');
      // $routeParams = $injector.get('$routeParams');
      $route = $injector.get('$route');
      // AuthController = $injector.get('AuthController')
      console.log('piggy piggy piggy ',$route.routes['/self']);
    });
  });

  it('Should have /signin route, template, and controller', function () {
    expect($route.routes['/']).to.be.defined;
    expect($route.routes['/'].redirectTo).to.equal('/self');
    expect($route.routes['/signin'].controller).to.equal('AuthController');
    expect($route.routes['/signin'].templateUrl).to.equal('/');
  });

  it('Should make proper http requests', function(){

  })

});
<|endoftext|>


<commit_before>describe('service', function () {
    beforeEach(module('myApp'));

    describe('UserService', function () {
        it('should be defined', inject(function (UserService) {
            expect(UserService).toBeDefined();
        }));
    });

    describe('ProductService', function () {
        it('should be defined', inject(function (ProductService) {
            expect(ProductService).toBeDefined();
        }));
    });

});
<commit_msg>expect service methods to be defined<commit_after>describe('service', function () {
    beforeEach(module('myApp'));

    describe('UserService', function () {
        it('should be defined', inject(function (UserService) {
            expect(UserService).toBeDefined();
            expect(UserService.find).toBeDefined();
            expect(UserService.get).toBeDefined();
        }));
    });

    describe('ProductService', function () {
        it('should be defined', inject(function (ProductService) {
            expect(ProductService).toBeDefined();
            expect(ProductService.find).toBeDefined();
            expect(ProductService.get).toBeDefined();
        }));
    });

});
<|endoftext|>


<commit_before>import React from 'react';
import sinon from 'sinon';
import expect from 'expect';
import TestUtils from 'react/lib/ReactTestUtils';
import AppFlux from '../../ui/flux';
import TaskList from '../../ui/components/TaskList';
import TestBackend from 'react-dnd/modules/backends/Test';
import {DragDropContext} from 'react-dnd';

function wrapContext(DecoratedComponent) {
    @DragDropContext(TestBackend)
    class TestContextContainer extends React.Component {
        render() {
            return <DecoratedComponent {...this.props} />;
        }
    }
    return TestContextContainer;
}

describe('task list', function() {
    it('handles a new task', function() {
        const flux = new AppFlux(),
              actions = flux.getActions("taskLists");

        const connect = function(el) { return el; };

        const list = {
            name: "testing",
            tasks: [
            ]
        };

        const TaskListContext = wrapContext(TaskList);

        const component = TestUtils.renderIntoDocument(
                <TaskListContext flux={flux}
                                 list={list}
                                 isOver={false}
                                 connectDropTarget={connect} />);

        sinon.stub(actions, "createTask");

        component.refs.newTask.getInputDOMNode().value = "new task!";
        TestUtils.simulate.submit(component.refs.newTaskForm.getDOMNode());
        assert(actions.createTask.calledOnce);

    });

    it('renders a list with tasks', function() {

        const flux = new AppFlux();

        const connect = function(el) { return el; };

        const list = {
            name: "testing",
            tasks: [
                {
                    text: "test1"
                }
            ]
        };

        const TaskListContext = wrapContext(TaskList);

        const component = TestUtils.renderIntoDocument(
                <TaskListContext flux={flux}
                                 list={list}
                                 isOver={false}
                                 connectDropTarget={connect} />
        );

    });
});

<commit_msg>task list tests<commit_after>import React from 'react';
import sinon from 'sinon';
import expect from 'expect';
import TestUtils from 'react/lib/ReactTestUtils';
import AppFlux from '../../ui/flux';
import TaskList from '../../ui/components/TaskList';
import TestBackend from 'react-dnd/modules/backends/Test';
import {DragDropContext} from 'react-dnd';

function wrapContext(DecoratedComponent) {
    @DragDropContext(TestBackend)
    class TestContextContainer extends React.Component {
        render() {
            return <DecoratedComponent {...this.props} />;
        }
    }
    return TestContextContainer;
}

describe('task list', function() {
    it('handles a new task', function() {
        const flux = new AppFlux(),
              actions = flux.getActions("taskLists");

        const connect = function(el) { return el; };

        const list = {
            name: "testing",
            tasks: [
            ]
        };

        const TaskListContext = wrapContext(TaskList);

        const component = TestUtils.renderIntoDocument(
                <TaskListContext flux={flux}
                                 list={list}
                                 isOver={false}
                                 connectDropTarget={connect} />);

        console.log(component)
        sinon.stub(actions, "createTask");

        component.refs.newTask.getInputDOMNode().value = "new task!";
        TestUtils.simulate.submit(component.refs.newTaskForm.getDOMNode());
        assert(actions.createTask.calledOnce);

    });

    it('renders a list with tasks', function() {

        const flux = new AppFlux();

        const connect = function(el) { return el; };

        const list = {
            name: "testing",
            tasks: [
                {
                    text: "test1"
                }
            ]
        };

        const TaskListContext = wrapContext(TaskList);

        const component = TestUtils.renderIntoDocument(
                <TaskListContext flux={flux}
                                 list={list}
                                 isOver={false}
                                 connectDropTarget={connect} />
        );

    });
});

<|endoftext|>


<commit_before>self.addEventListener('install', function() {
  self.skipWaiting();
});

self.addEventListener('activate', function(event) {
  event.waitUntil(self.clients.claim());
});
<commit_msg>Update skip-and-claim.js<commit_after>self.addEventListener('install', function() {
  event.waitUntil(self.skipWaiting());
});

self.addEventListener('activate', function(event) {
  event.waitUntil(self.clients.claim());
});
<|endoftext|>


<commit_before>var casper = require('casper').create({
    verbose: true,
    faultTolerant: false,
    onError: function () {  //(self, m) {
      this.capture('error.png');
      // these lines aren't needed. phantom will log the same msg.
      //console.log("FATAL: " + m);
      //self.exit();
    }
});

// This causes problems:
//var casper2 = Object.create(casper);

//Trying to add extensions to the casper.test object:
// (included here just for demonstration)
casper.test.assertNotVisible = function(selector) {
  casper.test.assertNot(casper.visible(selector), "expected " + selector + " to not be visible");
  // this client side util stuff didn't work for me here...
  //return !__utils__.visible(selector);
};

casper.waitAndClick = function(selector) {
  this.waitForSelector(selector, function() {
    this.click(selector);
  });
};

// doesn't seem to work
casper.on('timeout', function() {
  this.capture('timeout.png');
});

//using the simple web server started by grunt
casper.start('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment('test calendar grid is not visible at first');
  //this.capture('tmp.png');

  //this.test.assertNotVisible('.dl-grid');
  casper.test.assertNot( casper.exists('.dl-grid'), 'calendar grid does not exist');
});

casper.thenOpen('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment("test date selected is set back to the original form");
  //this.debugHTML();
  this.waitForSelector('#dateField', function() {
    this.click('#dateField');
  });
  this.waitForSelector('.dl-grid', function() {
    // simple screen capture:
    //this.capture('tmp.png');
    // TODO: figure out the xpath selectors...
    //this.click({type: "xpath", path: "//*[text()='14']"});
    //this.test.assertExists({type: "xpath", path: "//*[text()='14']"}, 'YAY for xpath');

    //HIDEOUS
    this.click('.dl-grid .dl-week:nth-child(3) .dl-day:nth-child(4)');
  });

  this.waitWhileVisible('.dl-grid', function() {
    this.test.assertEvalEquals(function() {
      return document.querySelector('#dateField').value;
    }, "05/16/2012", "date selected in picker is reflected in original field");
    this.test.assertNotVisible('.dl-grid');
  });
  //this.debugPage();
});

casper.thenOpen('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment('test we can not select an invalid date');
  casper.capture('tmp.png');

  this.waitForSelector('#dateField', function() {
    this.click('#dateField');
  });
  this.waitForSelector('.dl-grid', function() {
    // simple screen capture:
    //this.capture('tmp.png');
    this.click('.dl-grid div:nth-child(2)');

  });
  casper.then( function() {
    casper.capture('tmp.png');
    this.test.assertTextExists('May 2012', 'May is displayed');
    this.test.assertEvalEquals(function() {
      return document.querySelector('#dateField').value;
    }, "5/2/2012", "date in original field does not change");
  });
});

function assertNextMonth(displayMonth) {
  casper.then(function() {
    casper.waitAndClick('.dl-next');
  });
  casper.then(function() {
    casper.test.assertTextExists(displayMonth, displayMonth + ' is displayed');
  })  ;
}

casper.thenOpen('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment('test we can only navigate to a valid month');
  this.waitAndClick('#dateField');
  this.waitAndClick('.dl-prev');
  casper.then(function() {
    this.test.assertTextExists('May 2012', 'May is displayed');
  });
  assertNextMonth('June 2012');
  assertNextMonth('July 2012');
  assertNextMonth('August 2012');
  casper.repeat(2, function() {
    assertNextMonth('August 2012');
  });
  casper.then(function() {
    this.click('.dl-grid .dl-week:nth-child(2) .dl-day:nth-child(3)');
  });
});

casper.run(function() {
  this.test.renderResults(true);
  this.test.done();
  this.exit();
});

<commit_msg>started work on some more ui tests.<commit_after>var casper = require('casper').create({
    verbose: true,
    faultTolerant: false,
    onError: function () {  //(self, m) {
      this.capture('error.png');
      // these lines aren't needed. phantom will log the same msg.
      //console.log("FATAL: " + m);
      //self.exit();
    }
});

// This causes problems:
//var casper2 = Object.create(casper);

//Trying to add extensions to the casper.test object:
// (included here just for demonstration)
casper.test.assertNotVisible = function(selector) {
  casper.test.assertNot(casper.visible(selector), "expected " + selector + " to not be visible");
  // this client side util stuff didn't work for me here...
  //return !__utils__.visible(selector);
};

casper.waitAndClick = function(selector) {
  this.waitForSelector(selector, function() {
    this.click(selector);
  });
};

// doesn't seem to work
casper.on('timeout', function() {
  this.capture('timeout.png');
});

//using the simple web server started by grunt
casper.start('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment('test calendar grid is not visible at first');
  //this.capture('tmp.png');

  //this.test.assertNotVisible('.dl-grid');
  casper.test.assertNot( casper.exists('.dl-grid'), 'calendar grid does not exist');
});

casper.thenOpen('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment("test date selected is set back to the original form");
  //this.debugHTML();
  this.waitForSelector('#dateField', function() {
    this.click('#dateField');
  });
  this.waitForSelector('.dl-grid', function() {
    // simple screen capture:
    //this.capture('tmp.png');
    // TODO: figure out the xpath selectors...
    //this.click({type: "xpath", path: "//*[text()='14']"});
    //this.test.assertExists({type: "xpath", path: "//*[text()='14']"}, 'YAY for xpath');

    //HIDEOUS
    this.click('.dl-grid .dl-week:nth-child(3) .dl-day:nth-child(4)');
  });

  this.waitWhileVisible('.dl-grid', function() {
    this.test.assertEvalEquals(function() {
      return document.querySelector('#dateField').value;
    }, "05/16/2012", "date selected in picker is reflected in original field");
    this.test.assertNotVisible('.dl-grid');
  });
  //this.debugPage();
});

casper.thenOpen('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment('test we can not select an invalid date');
  //casper.capture('tmp.png');

  this.waitForSelector('#dateField', function() {
    this.click('#dateField');
  });
  this.waitForSelector('.dl-grid', function() {
    // simple screen capture:
    //this.capture('tmp.png');
    this.click('.dl-grid div:nth-child(2)');

  });
  casper.then( function() {
    //casper.capture('tmp.png');
    this.test.assertTextExists('May 2012', 'May is displayed');
    this.test.assertEvalEquals(function() {
      return document.querySelector('#dateField').value;
    }, "5/2/2012", "date in original field does not change");
  });
});

function assertNextMonth(displayMonth) {
  casper.then(function() {
    casper.waitAndClick('.dl-next');
  });
  casper.then(function() {
    casper.test.assertTextExists(displayMonth, displayMonth + ' is displayed');
  })  ;
}

casper.thenOpen('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment('test we can only navigate to a valid month');
  this.waitAndClick('#dateField');
  this.waitAndClick('.dl-prev');
  casper.then(function() {
    this.test.assertTextExists('May 2012', 'May is displayed');
  });
  assertNextMonth('June 2012');
  assertNextMonth('July 2012');
  assertNextMonth('August 2012');
  casper.repeat(2, function() {
    assertNextMonth('August 2012');
  });
  casper.then(function() {
    this.click('.dl-grid .dl-week:nth-child(2) .dl-day:nth-child(3)');
  });
});

// TODO:
casper.thenOpen('http://localhost:8000/daylite.html').then( function() {
  casper.test.comment('Make sure selected date is highlighted, only in the right month.');
  this.waitAndClick("#dateField");
  casper.then(function() {
    casper.test.assertTextExists('May 2012', 'May is displayed');
    // assert may 9 is highlighted
    // click may 17
    // open calendar again
    // assert may 17 is selected
  });
});
//  Make sure calendars don't collide.

casper.run(function() {
  this.test.renderResults(true);
  this.test.done();
  this.exit();
});

<|endoftext|>