<commit_before>/**common -- iServer**/
import './common/iServer/AddressMatchServiceSpec.js';
import './common/iServer/AggQueryBuilderParameterSpec.js';
import './common/iServer/AggregationParameterSpec.js';
import './common/iServer/AreaSolarRadiationParametersSpec.js';
import './common/iServer/BufferAnalystServiceSpec.js';
import './common/iServer/BufferDistanceSpec.js';
import './common/iServer/BufferSettingSpec.js';
import './common/iServer/BurstPipelineAnalystServiceSpec.js';
import './common/iServer/ChartQueryFilterParameterSpec.js';
import './common/iServer/ChartQueryParametersSpec.js';
import './common/iServer/ClipParameterSpec.js';
import './common/iServer/ComputeWeightMatrixServiceSpec.js';
import './common/iServer/DensityAnalystServiceSpec.js';
import './common/iServer/EditFeaturesServiceSpec.js';
import './common/iServer/FacilityAnalystStreamParametersSpec.js';
import './common/iServer/FacilityAnalystUpstream3DParametersSpec.js';
import './common/iServer/FieldStatisticServiceSpec.js';
import './common/iServer/FilterAggParameterSpec.js';
import './common/iServer/FindClosestFacilitiesServiceSpec.js';
import './common/iServer/FindLocationServiceSpec.js';
import './common/iServer/FindMTSPPathsServiceSpec.js';
import './common/iServer/FindPathServiceSpec.js';
import './common/iServer/FindServiceAreasServiceSpec.js';
import './common/iServer/FindTSPPathsServiceSpec.js';
import './common/iServer/GenerateSpatialDataServiceSpec.js';
import './common/iServer/GeoBoundingBoxQueryBuilderParameterSpec.js';
import './common/iServer/GeoHashGridAggParameterSpec.js';
import './common/iServer/GeometryBatchAnalystServiceSpec.js';
import './common/iServer/GeoRelationAnalystServiceSpec.js';
import './common/iServer/GetFeaturesByBoundsServiceSpec.js';
import './common/iServer/GetFeaturesByBufferServiceSpec.js';
import './common/iServer/GetFeaturesByGeometryServiceSpec.js';
import './common/iServer/GetFeaturesByIDsServiceSpec.js';
import './common/iServer/GetFeaturesBySQLServiceSpec.js';
import './common/iServer/GetFieldsServiceSpec.js';
import './common/iServer/GetGridCellInfosServiceSpec.js';
import './common/iServer/GetLayersInfoServiceSpec.js';
import './common/iServer/GridSpec.js';
import './common/iServer/ImageSpec.js';
import './common/iServer/InterpolationAnalystServiceSpec.js';
import './common/iServer/LabelImageCellSpec.js';
import './common/iServer/LabelMixedStyleSpec.js';
import './common/iServer/LinkItemSpec.js';
import './common/iServer/MapServiceSpec.js';
import './common/iServer/MathExpressionAnalysisServiceSpec.js';
import './common/iServer/MeasureServiceSpec.js';
import './common/iServer/OverlapDisplayedOptionsSpec.js';
import './common/iServer/OverlayAnalystServiceSpec.js';
import './common/iServer/QueryByBoundsServiceSpec.js';
import './common/iServer/QueryByDistanceServiceSpec.js';
import './common/iServer/QueryByGeometryServiceSpec.js';
import './common/iServer/QueryBySQLServiceSpec.js';
import './common/iServer/QueryServiceSpec.js';
import './common/iServer/RouteCalculateMeasureServiceSpec.js';
import './common/iServer/RouteLocatorServiceSpec.js';
import './common/iServer/RouteSpec.js';
import './common/iServer/ServerGeometrySpec.js';
import './common/iServer/SetLayerInfoServiceSpec.js';
import './common/iServer/SetLayersInfoServiceSpec.js';
import './common/iServer/SetLayerStatusServiceSpec.js';
import './common/iServer/StopQueryServiceSpec.js';
import './common/iServer/SummaryAttributesJobsParameterSpec.js';
import './common/iServer/SurfaceAnalystServiceSpec.js';
import './common/iServer/TerrainCurvatureCalculationServiceSpec.js';
import './common/iServer/ThemeDotDensitySpec.js';
import './common/iServer/ThemeGridRangeSpec.js';
import './common/iServer/ThemeGridUniqueSpec.js';
import './common/iServer/ThemeLabelUniqueItemSpec.js';
import './common/iServer/ThemeRangeSpec.js';
import './common/iServer/ThemeServiceSpec.js';
import './common/iServer/ThiessenAnalystServiceSpec.js';
import './common/iServer/TilesetsServiceSpec.js';
import './common/iServer/TransferLineSpec.js';
import './common/iServer/TransferPathServiceSpec.js';
import './common/iServer/TransferSolutionServiceSpec.js';
import './common/iServer/UpdateEdgeWeightServiceSpec.js';
import './common/iServer/UpdateTurnNodeWeightServiceSpec.js';
// import './common/iServer/AreaSolarRadiationServiceSpec.js';       //iclient8注释掉
// import './common/iServer/ChartFeatureInfoSpecsServiceSpec.js';    //iclient8注释掉,海图测试LayerServices相关的类，等待服务端支持后添加
// import './common/iServer/ChartQueryServiceSpec.js';
// import './common/iServer/FacilityAnalystSinks3DServiceSpec.js';   //三维网络分析Facility系列的测试全部被iClient8注释掉
// import './common/iServer/FacilityAnalystSources3DServiceSpec.js';
// import './common/iServer/FacilityAnalystStreamServiceSpec.js';
// import './common/iServer/FacilityAnalystTracedown3DServiceSpec.js';
// import './common/iServer/FacilityAnalystTraceup3DServiceSpec.js';
// import './common/iServer/FacilityAnalystUpstream3DServiceSpec.js';

/**common -- control**/
import './common/control/TimeControlBaseSpec.js';
import './common/control/TimeFlowControlSpec.js';

/**common -- format**/
import './common/format/GeoJSONSpec.js';
import './common/format/JSONSpec.js';
import './common/format/WKTSpec.js';

/**common -- style**/
import './common/style/CartoCSSSpec.js';

/**common -- security**/
import './common/security/KeyServiceParameterSpec.js';
import './common/security/SecurityManagerSpec.js';

/**common -- commontypes**/
import './common/commontypes/BaseTypesSpec.js';
import './common/commontypes/BoundsSpec.js';
import './common/commontypes/DateSpec.js';
import './common/commontypes/LonLatSpec.js';
import './common/commontypes/PixelSpec.js';
import './common/commontypes/VectorSpec.js';
import './common/commontypes/UtilSpec.js';
import './common/commontypes/geometry/CollectionSpec.js';
import './common/commontypes/geometry/GeoTextSpec.js';
import './common/commontypes/geometry/LineStringSpec.js';
import './common/commontypes/geometry/LinearRingSpec.js';

/**common -- overlay**/
import './common/overlay/feature/ShapeFactorySpec.js';
import './common/overlay/levelRenderer/AreaSpec.js';
import './common/overlay/levelRenderer/ClipSpec.js';
import './common/overlay/levelRenderer/AnimationSpec.js';
import './common/overlay/levelRenderer/ColorSpec.js';
import './common/overlay/levelRenderer/ComputeBoundingBoxSpec';
import './common/overlay/levelRenderer/CurveSpec.js';
import './common/overlay/levelRenderer/EasingSpec.js';
import './common/overlay/levelRenderer/GroupSpec.js';
import './common/overlay/levelRenderer/LevelRendererSpec.js';
import './common/overlay/levelRenderer/MatrixSpec.js';
import './common/overlay/levelRenderer/PainterSpec.js';
import './common/overlay/levelRenderer/RenderSpec.js';
import './common/overlay/levelRenderer/ShapeSepc.js';
import './common/overlay/levelRenderer/SmicBrokenLineSpec.js';
import './common/overlay/levelRenderer/SmicCircleSpec.js';
import './common/overlay/levelRenderer/SmicEllipseSpec';
import './common/overlay/levelRenderer/SmicImageSpec.js';
import './common/overlay/levelRenderer/SmicIsogonSpec.js';
import './common/overlay/levelRenderer/SmicPointSpec.js';
import './common/overlay/levelRenderer/SmicPolygonSpec.js';
import './common/overlay/levelRenderer/SmicRectangleSpec.js';
import './common/overlay/levelRenderer/SmicRingSpec.js';
import './common/overlay/levelRenderer/SmicSectorSpec.js';
import './common/overlay/levelRenderer/SmicStarSpec.js';
import './common/overlay/levelRenderer/SmicTextSpec.js';
import './common/overlay/levelRenderer/StorageSpec.js';
import './common/overlay/levelRenderer/TransformableSpec.js';
import './common/overlay/levelRenderer/UtilSpec.js';
import './common/overlay/levelRenderer/VectorSpec.js';
import './common/overlay/GraphSpec';

/**common -- online**/
import './common/online/OnlineDataSpec.js';
import './common/online/OnlineSpec.js';
import './common/online/OnlineQueryDatasParameterSpec';

/**common -- iManager**/
import './common/iManager/iManagerCreateNodeParamSpec.js';

/**common -- iPortal**/
import './common/iPortal/iPortalQueryParamSpec.js';
import './common/iPortal/iPortalUserSpec.js';
// import './common/iPortal/iPortalShareEntitySpec.js';
import './common/iPortal/iPortalShareParamSpec.js';
import './common/iPortal/iPortalResourceSpec.js';
import './common/iPortal/iPortalQueryResultSpec.js';
import './common/iPortal/iPortalSpec.js';
import './common/iPortal/iPortalAddResourceParamSpec';
// import './common/iPortal/iPortalRegisterServiceParamSpec';
// import './common/iPortal/iPortalAddDataParamSpec.js';
import './common/iPortal/iPortalDataMetaInfoParamSpec.js';
import './common/iPortal/iPortalDataStoreInfoParamSpec.js';
import './common/iPortal/iPortalDataConnectionInfoParamSpec.js';

/**common -- thirdparty**/
import './common/thirdparty/elasticsearch/ElasticSearchSpec.js';

/**common -- component**/
import './common/components/templates/IndexTabsPageContainerSpec.js';
import './common/components/templates/NavTabsPageSpec.js';
// import './common/components/templates/CommonContainerSpec.js';
import './common/components/chart/ChartModelSpec.js';
import './common/components/chart/ChartViewModelSpec';
import './common/components/chart/ChartViewSpec';

import './common/util/FetchRequestSpec';

<commit_msg>Update test-main-common.js<commit_after>/**common -- iServer**/
import './common/iServer/AddressMatchServiceSpec.js';
import './common/iServer/AggQueryBuilderParameterSpec.js';
import './common/iServer/AggregationParameterSpec.js';
import './common/iServer/AreaSolarRadiationParametersSpec.js';
import './common/iServer/BufferAnalystServiceSpec.js';
import './common/iServer/BufferDistanceSpec.js';
import './common/iServer/BufferSettingSpec.js';
import './common/iServer/BurstPipelineAnalystServiceSpec.js';
import './common/iServer/ChartQueryFilterParameterSpec.js';
import './common/iServer/ChartQueryParametersSpec.js';
import './common/iServer/ClipParameterSpec.js';
import './common/iServer/ComputeWeightMatrixServiceSpec.js';
import './common/iServer/DensityAnalystServiceSpec.js';
import './common/iServer/EditFeaturesServiceSpec.js';
import './common/iServer/FacilityAnalystStreamParametersSpec.js';
import './common/iServer/FacilityAnalystUpstream3DParametersSpec.js';
import './common/iServer/FieldStatisticServiceSpec.js';
import './common/iServer/FilterAggParameterSpec.js';
import './common/iServer/FindClosestFacilitiesServiceSpec.js';
import './common/iServer/FindLocationServiceSpec.js';
import './common/iServer/FindMTSPPathsServiceSpec.js';
import './common/iServer/FindPathServiceSpec.js';
import './common/iServer/FindServiceAreasServiceSpec.js';
import './common/iServer/FindTSPPathsServiceSpec.js';
import './common/iServer/GenerateSpatialDataServiceSpec.js';
import './common/iServer/GeoBoundingBoxQueryBuilderParameterSpec.js';
import './common/iServer/GeoHashGridAggParameterSpec.js';
import './common/iServer/GeometryBatchAnalystServiceSpec.js';
import './common/iServer/GeoRelationAnalystServiceSpec.js';
import './common/iServer/GetFeaturesByBoundsServiceSpec.js';
import './common/iServer/GetFeaturesByBufferServiceSpec.js';
import './common/iServer/GetFeaturesByGeometryServiceSpec.js';
import './common/iServer/GetFeaturesByIDsServiceSpec.js';
import './common/iServer/GetFeaturesBySQLServiceSpec.js';
import './common/iServer/GetFieldsServiceSpec.js';
import './common/iServer/GetGridCellInfosServiceSpec.js';
import './common/iServer/GetLayersInfoServiceSpec.js';
import './common/iServer/GridSpec.js';
import './common/iServer/ImageSpec.js';
import './common/iServer/InterpolationAnalystServiceSpec.js';
import './common/iServer/LabelImageCellSpec.js';
import './common/iServer/LabelMixedStyleSpec.js';
import './common/iServer/LinkItemSpec.js';
import './common/iServer/MapServiceSpec.js';
import './common/iServer/MathExpressionAnalysisServiceSpec.js';
import './common/iServer/MeasureServiceSpec.js';
import './common/iServer/OverlapDisplayedOptionsSpec.js';
import './common/iServer/OverlayAnalystServiceSpec.js';
import './common/iServer/QueryByBoundsServiceSpec.js';
import './common/iServer/QueryByDistanceServiceSpec.js';
import './common/iServer/QueryByGeometryServiceSpec.js';
import './common/iServer/QueryBySQLServiceSpec.js';
import './common/iServer/QueryServiceSpec.js';
import './common/iServer/RouteCalculateMeasureServiceSpec.js';
import './common/iServer/RouteLocatorServiceSpec.js';
import './common/iServer/RouteSpec.js';
import './common/iServer/ServerGeometrySpec.js';
import './common/iServer/SetLayerInfoServiceSpec.js';
import './common/iServer/SetLayersInfoServiceSpec.js';
import './common/iServer/SetLayerStatusServiceSpec.js';
import './common/iServer/StopQueryServiceSpec.js';
import './common/iServer/SummaryAttributesJobsParameterSpec.js';
import './common/iServer/SurfaceAnalystServiceSpec.js';
import './common/iServer/TerrainCurvatureCalculationServiceSpec.js';
import './common/iServer/ThemeDotDensitySpec.js';
import './common/iServer/ThemeGridRangeSpec.js';
import './common/iServer/ThemeGridUniqueSpec.js';
import './common/iServer/ThemeLabelUniqueItemSpec.js';
import './common/iServer/ThemeRangeSpec.js';
import './common/iServer/ThemeServiceSpec.js';
import './common/iServer/ThiessenAnalystServiceSpec.js';
import './common/iServer/TilesetsServiceSpec.js';
import './common/iServer/TransferLineSpec.js';
import './common/iServer/TransferPathServiceSpec.js';
import './common/iServer/TransferSolutionServiceSpec.js';
import './common/iServer/UpdateEdgeWeightServiceSpec.js';
import './common/iServer/UpdateTurnNodeWeightServiceSpec.js';
// import './common/iServer/AreaSolarRadiationServiceSpec.js';       //iclient8注释掉
// import './common/iServer/ChartFeatureInfoSpecsServiceSpec.js';    //iclient8注释掉,海图测试LayerServices相关的类，等待服务端支持后添加
// import './common/iServer/ChartQueryServiceSpec.js';
// import './common/iServer/FacilityAnalystSinks3DServiceSpec.js';   //三维网络分析Facility系列的测试全部被iClient8注释掉
// import './common/iServer/FacilityAnalystSources3DServiceSpec.js';
// import './common/iServer/FacilityAnalystStreamServiceSpec.js';
// import './common/iServer/FacilityAnalystTracedown3DServiceSpec.js';
// import './common/iServer/FacilityAnalystTraceup3DServiceSpec.js';
// import './common/iServer/FacilityAnalystUpstream3DServiceSpec.js';

/**common -- control**/
import './common/control/TimeControlBaseSpec.js';
import './common/control/TimeFlowControlSpec.js';

/**common -- format**/
import './common/format/GeoJSONSpec.js';
import './common/format/JSONSpec.js';
import './common/format/WKTSpec.js';

/**common -- style**/
import './common/style/CartoCSSSpec.js';

/**common -- security**/
import './common/security/KeyServiceParameterSpec.js';
import './common/security/SecurityManagerSpec.js';

/**common -- commontypes**/
import './common/commontypes/BaseTypesSpec.js';
import './common/commontypes/BoundsSpec.js';
import './common/commontypes/DateSpec.js';
import './common/commontypes/LonLatSpec.js';
import './common/commontypes/PixelSpec.js';
import './common/commontypes/VectorSpec.js';
import './common/commontypes/UtilSpec.js';
import './common/commontypes/geometry/CollectionSpec.js';
import './common/commontypes/geometry/GeoTextSpec.js';
import './common/commontypes/geometry/LineStringSpec.js';
import './common/commontypes/geometry/LinearRingSpec.js';

/**common -- overlay**/
import './common/overlay/feature/ShapeFactorySpec.js';
import './common/overlay/levelRenderer/AreaSpec.js';
import './common/overlay/levelRenderer/ClipSpec.js';
import './common/overlay/levelRenderer/AnimationSpec.js';
import './common/overlay/levelRenderer/ColorSpec.js';
import './common/overlay/levelRenderer/ComputeBoundingBoxSpec';
import './common/overlay/levelRenderer/CurveSpec.js';
import './common/overlay/levelRenderer/EasingSpec.js';
import './common/overlay/levelRenderer/GroupSpec.js';
import './common/overlay/levelRenderer/LevelRendererSpec.js';
import './common/overlay/levelRenderer/MatrixSpec.js';
import './common/overlay/levelRenderer/PainterSpec.js';
import './common/overlay/levelRenderer/RenderSpec.js';
import './common/overlay/levelRenderer/ShapeSepc.js';
import './common/overlay/levelRenderer/SmicBrokenLineSpec.js';
import './common/overlay/levelRenderer/SmicCircleSpec.js';
import './common/overlay/levelRenderer/SmicEllipseSpec';
import './common/overlay/levelRenderer/SmicImageSpec.js';
import './common/overlay/levelRenderer/SmicIsogonSpec.js';
import './common/overlay/levelRenderer/SmicPointSpec.js';
import './common/overlay/levelRenderer/SmicPolygonSpec.js';
import './common/overlay/levelRenderer/SmicRectangleSpec.js';
import './common/overlay/levelRenderer/SmicRingSpec.js';
import './common/overlay/levelRenderer/SmicSectorSpec.js';
import './common/overlay/levelRenderer/SmicStarSpec.js';
import './common/overlay/levelRenderer/SmicTextSpec.js';
import './common/overlay/levelRenderer/StorageSpec.js';
import './common/overlay/levelRenderer/TransformableSpec.js';
import './common/overlay/levelRenderer/UtilSpec.js';
import './common/overlay/levelRenderer/VectorSpec.js';
import './common/overlay/GraphSpec';

/**common -- online**/
import './common/online/OnlineDataSpec.js';
import './common/online/OnlineSpec.js';
import './common/online/OnlineQueryDatasParameterSpec';

/**common -- iManager**/
import './common/iManager/iManagerCreateNodeParamSpec.js';

/**common -- iPortal**/
import './common/iPortal/iPortalQueryParamSpec.js';
import './common/iPortal/iPortalUserSpec.js';
// import './common/iPortal/iPortalShareEntitySpec.js';
import './common/iPortal/iPortalShareParamSpec.js';
import './common/iPortal/iPortalResourceSpec.js';
// import './common/iPortal/iPortalQueryResultSpec.js';
import './common/iPortal/iPortalSpec.js';
import './common/iPortal/iPortalAddResourceParamSpec';
// import './common/iPortal/iPortalRegisterServiceParamSpec';
// import './common/iPortal/iPortalAddDataParamSpec.js';
import './common/iPortal/iPortalDataMetaInfoParamSpec.js';
import './common/iPortal/iPortalDataStoreInfoParamSpec.js';
import './common/iPortal/iPortalDataConnectionInfoParamSpec.js';

/**common -- thirdparty**/
import './common/thirdparty/elasticsearch/ElasticSearchSpec.js';

/**common -- component**/
import './common/components/templates/IndexTabsPageContainerSpec.js';
import './common/components/templates/NavTabsPageSpec.js';
// import './common/components/templates/CommonContainerSpec.js';
import './common/components/chart/ChartModelSpec.js';
import './common/components/chart/ChartViewModelSpec';
import './common/components/chart/ChartViewSpec';

import './common/util/FetchRequestSpec';

<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        done();
    });
});
<commit_msg>add basic package-file testing<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        done();
    });
});
<|endoftext|>


<commit_before>var appModulePath = Npm.require('app-module-path');
appModulePath.addPath(process.cwd() + '/node_modules/');

var Future = Npm.require('fibers/future');
var fs = Plugin.fs;
var path = Plugin.path;
var postCSS = Npm.require('postcss');
var sourcemap = Npm.require('source-map');

Plugin.registerMinifier({
    extensions: ["css"]
}, function () {
    var minifier = new CssToolsMinifier();
    return minifier;
});

var PACKAGES_FILE = 'package.json';

var packageFile = path.resolve(process.cwd(), PACKAGES_FILE);

var loadJSONFile = function (filePath) {
    var content = fs.readFileSync(filePath);
    try {
        return JSON.parse(content);
    } catch (e) {
        console.log('Error: failed to parse ', filePath, ' as JSON');
        return {};
    }
};

var configPackages = {};
var configOptions = {};

if (fs.existsSync(packageFile)) {
    configPackages = loadJSONFile(packageFile).devDependencies;
    configOptions = loadJSONFile(packageFile).postcss;
}

var getPostCSSPlugins = function () {
    var plugins = [];
    var pluginsOptions = configOptions.pluginsOptions;
    if (configPackages) {
        Object.keys(configPackages).forEach(function (pluginName) {
            let postCSSPlugin = Npm.require(pluginName);
            if (postCSSPlugin.name === 'creator' && postCSSPlugin().postcssPlugin) {
                plugins.push(postCSSPlugin(pluginsOptions ? pluginsOptions[pluginName] : {}));
            }
        });
    }
    return plugins;
};

var isNotImport = function (inputFileUrl) {
    return !(/\.import\.css$/.test(inputFileUrl) ||
             /(?:^|\/)imports\//.test(inputFileUrl));
};

function CssToolsMinifier() {};

CssToolsMinifier.prototype.processFilesForBundle = function (files, options) {
    var mode = options.minifyMode;

    if (!files.length) return;

    var notImportFiles = [];

    files.forEach(function (file) {
        if (isNotImport(file._source.url)) {
            notImportFiles.push(file);
        }
    });

    var merged = mergeCss(notImportFiles);

    if (mode === 'development') {
        files[0].addStylesheet({
            data: merged.code,
            sourceMap: merged.sourceMap,
            path: 'merged-stylesheets.css'
        });
        return;
    }

    var minifiedFiles = CssTools.minifyCss(merged.code);

    if (files.length) {
        minifiedFiles.forEach(function (minified) {
            files[0].addStylesheet({
                data: minified
            });
        });
    }
};

// Lints CSS files and merges them into one file, fixing up source maps and
// pulling any @import directives up to the top since the CSS spec does not
// allow them to appear in the middle of a file.
var mergeCss = function (css) {
    // Filenames passed to AST manipulator mapped to their original files
    var originals = {};

    var cssAsts = css.map(function (file) {
        var filename = file.getPathInBundle();
        originals[filename] = file;

        var f = new Future;

        var css;
        var postres;

        postCSS(getPostCSSPlugins())
            .process(file.getContentsAsString(), {
                from: process.cwd() + file._source.url
            })
            .then(function (result) {
                result.warnings().forEach(function (warn) {
                    process.stderr.write(warn.toString());
                });
                f.return(result);
            })
            .catch(function (error) {
                var errMsg = error.message;
                if (error.name === 'CssSyntaxError') {
                    errMsg = error.message + '\n\n' + 'Css Syntax Error.' + '\n\n' + error.message + error.showSourceCode()
                }
                error.message = errMsg;
                f.return(error);
            });

        try {
            var parseOptions = {
                source: filename,
                position: true
            };

            postres = f.wait();

            if (postres.name === 'CssSyntaxError') {
                throw postres;
            }

            css = postres.css;

            var ast = CssTools.parseCss(css, parseOptions);
            ast.filename = filename;
        } catch (e) {

            if (e.name === 'CssSyntaxError') {
                file.error({
                    message: e.message,
                    line: e.line,
                    column: e.column
                });
            } else if (e.reason) {
                file.error({
                    message: e.reason,
                    line: e.line,
                    column: e.column
                });
            } else {
                // Just in case it's not the normal error the library makes.
                file.error({
                    message: e.message
                });
            }

            return {
                type: "stylesheet",
                stylesheet: {
                    rules: []
                },
                filename: filename
            };
        }

        return ast;
    });

    var warnCb = function (filename, msg) {
        // XXX make this a buildmessage.warning call rather than a random log.
        //     this API would be like buildmessage.error, but wouldn't cause
        //     the build to fail.
        console.log(filename + ': warn: ' + msg);
    };

    var mergedCssAst = CssTools.mergeCssAsts(cssAsts, warnCb);

    // Overwrite the CSS files list with the new concatenated file
    var stringifiedCss = CssTools.stringifyCss(mergedCssAst, {
        sourcemap: true,
        // don't try to read the referenced sourcemaps from the input
        inputSourcemaps: false
    });

    if (!stringifiedCss.code) {
        return {
            code: ''
        };
    }

    // Add the contents of the input files to the source map of the new file
    stringifiedCss.map.sourcesContent =
        stringifiedCss.map.sources.map(function (filename) {
            return originals[filename].getContentsAsString();
        });

    // If any input files had source maps, apply them.
    // Ex.: less -> css source map should be composed with css -> css source map
    var newMap = sourcemap.SourceMapGenerator.fromSourceMap(
        new sourcemap.SourceMapConsumer(stringifiedCss.map));

    Object.keys(originals).forEach(function (name) {
        var file = originals[name];
        if (!file.getSourceMap())
            return;
        try {
            newMap.applySourceMap(
                new sourcemap.SourceMapConsumer(file.getSourceMap()), name);
        } catch (err) {
            // If we can't apply the source map, silently drop it.
            //
            // XXX This is here because there are some less files that
            // produce source maps that throw when consumed. We should
            // figure out exactly why and fix it, but this will do for now.
        }
    });

    return {
        code: stringifiedCss.code,
        sourceMap: newMap.toString()
    };
};
<commit_msg>Update minify-css.js<commit_after>var appModulePath = Npm.require('app-module-path');
appModulePath.addPath(process.cwd() + '/node_modules/');

var Future = Npm.require('fibers/future');
var fs = Plugin.fs;
var path = Plugin.path;
var postCSS = Npm.require('postcss');
var sourcemap = Npm.require('source-map');

Plugin.registerMinifier({
    extensions: ["css"]
}, function () {
    var minifier = new CssToolsMinifier();
    return minifier;
});

var PACKAGES_FILE = 'package.json';

var packageFile = path.resolve(process.cwd(), PACKAGES_FILE);

var loadJSONFile = function (filePath) {
    var content = fs.readFileSync(filePath);
    try {
        return JSON.parse(content);
    } catch (e) {
        console.log('Error: failed to parse ', filePath, ' as JSON');
        return {};
    }
};

var configPackages = {};
var configOptions = {};

if (fs.existsSync(packageFile)) {
    configPackages = loadJSONFile(packageFile).devDependencies;
    configOptions = loadJSONFile(packageFile).postcss;
}

var getPostCSSPlugins = function () {
    var plugins = [];
    var pluginsOptions = configOptions.pluginsOptions;
    if (configPackages) {
        Object.keys(configPackages).forEach(function (pluginName) {
            let postCSSPlugin = Npm.require(pluginName);
            if (postCSSPlugin && postCSSPlugin.name === 'creator' && postCSSPlugin().postcssPlugin) {
                plugins.push(postCSSPlugin(pluginsOptions ? pluginsOptions[pluginName] : {}));
            }
        });
    }
    return plugins;
};

var isNotImport = function (inputFileUrl) {
    return !(/\.import\.css$/.test(inputFileUrl) ||
             /(?:^|\/)imports\//.test(inputFileUrl));
};

function CssToolsMinifier() {};

CssToolsMinifier.prototype.processFilesForBundle = function (files, options) {
    var mode = options.minifyMode;

    if (!files.length) return;

    var notImportFiles = [];

    files.forEach(function (file) {
        if (isNotImport(file._source.url)) {
            notImportFiles.push(file);
        }
    });

    var merged = mergeCss(notImportFiles);

    if (mode === 'development') {
        files[0].addStylesheet({
            data: merged.code,
            sourceMap: merged.sourceMap,
            path: 'merged-stylesheets.css'
        });
        return;
    }

    var minifiedFiles = CssTools.minifyCss(merged.code);

    if (files.length) {
        minifiedFiles.forEach(function (minified) {
            files[0].addStylesheet({
                data: minified
            });
        });
    }
};

// Lints CSS files and merges them into one file, fixing up source maps and
// pulling any @import directives up to the top since the CSS spec does not
// allow them to appear in the middle of a file.
var mergeCss = function (css) {
    // Filenames passed to AST manipulator mapped to their original files
    var originals = {};

    var cssAsts = css.map(function (file) {
        var filename = file.getPathInBundle();
        originals[filename] = file;

        var f = new Future;

        var css;
        var postres;

        postCSS(getPostCSSPlugins())
            .process(file.getContentsAsString(), {
                from: process.cwd() + file._source.url
            })
            .then(function (result) {
                result.warnings().forEach(function (warn) {
                    process.stderr.write(warn.toString());
                });
                f.return(result);
            })
            .catch(function (error) {
                var errMsg = error.message;
                if (error.name === 'CssSyntaxError') {
                    errMsg = error.message + '\n\n' + 'Css Syntax Error.' + '\n\n' + error.message + error.showSourceCode()
                }
                error.message = errMsg;
                f.return(error);
            });

        try {
            var parseOptions = {
                source: filename,
                position: true
            };

            postres = f.wait();

            if (postres.name === 'CssSyntaxError') {
                throw postres;
            }

            css = postres.css;

            var ast = CssTools.parseCss(css, parseOptions);
            ast.filename = filename;
        } catch (e) {

            if (e.name === 'CssSyntaxError') {
                file.error({
                    message: e.message,
                    line: e.line,
                    column: e.column
                });
            } else if (e.reason) {
                file.error({
                    message: e.reason,
                    line: e.line,
                    column: e.column
                });
            } else {
                // Just in case it's not the normal error the library makes.
                file.error({
                    message: e.message
                });
            }

            return {
                type: "stylesheet",
                stylesheet: {
                    rules: []
                },
                filename: filename
            };
        }

        return ast;
    });

    var warnCb = function (filename, msg) {
        // XXX make this a buildmessage.warning call rather than a random log.
        //     this API would be like buildmessage.error, but wouldn't cause
        //     the build to fail.
        console.log(filename + ': warn: ' + msg);
    };

    var mergedCssAst = CssTools.mergeCssAsts(cssAsts, warnCb);

    // Overwrite the CSS files list with the new concatenated file
    var stringifiedCss = CssTools.stringifyCss(mergedCssAst, {
        sourcemap: true,
        // don't try to read the referenced sourcemaps from the input
        inputSourcemaps: false
    });

    if (!stringifiedCss.code) {
        return {
            code: ''
        };
    }

    // Add the contents of the input files to the source map of the new file
    stringifiedCss.map.sourcesContent =
        stringifiedCss.map.sources.map(function (filename) {
            return originals[filename].getContentsAsString();
        });

    // If any input files had source maps, apply them.
    // Ex.: less -> css source map should be composed with css -> css source map
    var newMap = sourcemap.SourceMapGenerator.fromSourceMap(
        new sourcemap.SourceMapConsumer(stringifiedCss.map));

    Object.keys(originals).forEach(function (name) {
        var file = originals[name];
        if (!file.getSourceMap())
            return;
        try {
            newMap.applySourceMap(
                new sourcemap.SourceMapConsumer(file.getSourceMap()), name);
        } catch (err) {
            // If we can't apply the source map, silently drop it.
            //
            // XXX This is here because there are some less files that
            // produce source maps that throw when consumed. We should
            // figure out exactly why and fix it, but this will do for now.
        }
    });

    return {
        code: stringifiedCss.code,
        sourceMap: newMap.toString()
    };
};
<|endoftext|>


<commit_before>var childProcess  = require('child_process'),
    fs            = require('fs'),
    util          = require('util'),
    logger        = require('log4js').getLogger(),
    path          = require('path');

exports.init = function(config, cimpler) {
   var paths = config.repoPaths;
   paths = Array.isArray(paths) ? paths : [paths]
   paths.forEach(function(repoPath) {
      var consumer = buildConsumer(config, cimpler, repoPath);
      cimpler.consumeBuild(consumer, config.repoRegex);
   });
}

function buildConsumer(config, cimpler, repoPath) {
   return function(build, started, finished) {
      var execOptions = {
         env: {
            BUILD_REPO:   build.repo,
            BUILD_COMMIT: build.commit,
            BUILD_BRANCH: build.branch,
            BUILD_STATUS: build.status
         },
         timeout: config.timeout || 0
      },
      cdToRepo = 'set -v; set -x; cd "' + repoPath + '"';

      for(var key in process.env) {
         execOptions.env[key] = process.env[key];
      }

      if (!repoPath) {
         throw new Error("Missing the 'path' option of git-build config");
      }

      logger.info(id(build) + " -- Building with git");

      startFetch();

      function startFetch() {
         var commands = '(cd "' + repoPath + '" && ' +
            "git fetch --quiet && " +
            "git rev-parse origin/" + build.branch + ") 2>&1";

         exec(commands, function(err, stdout) {
            if (err) {
               var failed = "Fetch Failed";
               build.status = 'error';
               build.error = failed;
               stdout += "\n\n" + failed;
               logger.warn(id(build) + " -- " + failed);
               if (logFilePath(build)) {
                  fs.writeFileSync(logFilePath(build), stdout);
               }
               finishedBuild();
            } else {
               if (!build.commit) {
                  build.commit = stdout.trim();
               }
               startMerge();
            }
         });
      }

      function startMerge() {
         var commands = '(' + cdToRepo + " && " +
            "git reset --hard && " +
            "git clean -ffd && " +
            "git checkout "+build.commit+" && " +
            "git merge origin/master && " +
            "git submodule update --init --recursive ) 2>&1";

         exec(commands, function(err, stdout) {
            var nextStep, message;

            if (err) {
               message = "Merge Failed";
               nextStep = finishedBuild;
               build.status = 'error';
               build.error = message;
               stdout += "\n\n" + message;

            } else {
               message = "Merge Successful";
               nextStep = startBuild;
               stdout = message + "\n";

            }

            // Assigns a log file to this build
            var logPath = logFilePath(build);

            logger.info(id(build) + " -- " + message);
            if (logPath) {
               fs.writeFileSync(logPath, stdout);
            }

            nextStep(started);
         });
      }

      function startBuild(started) {
         var buildCommand = build.buildCommand || config.cmd;
         var commands = cdToRepo + " && (" + buildCommand + ")" +
                        echoStatusCmd('Build');

         var proc = exec(commands, function(err, stdout, stderr) {
            build.status = err ? 'failure' : 'success';
            logger.info(id(build) + " -- Build " + build.status);
            finishedBuild();
         });

         /**
          * Use piping instead of shell redirection to capture output
          * in case of a syntax error in cmd
          */
         proc.stdout.pipe(logFile(), {end:false});
         proc.stderr.pipe(logFile(), {end:false});
         if (build._control.tail_log) {
            build._control.logs = {
               stdout : proc.stdout,
               stderr : proc.stderr
            };
         }

         // Fire the started event now that our build has a log.
         started();
      }

      function logFilePath(inBuild) {
         if (!config.logs || !config.logs.path)
            return null;

         var logFilename = (inBuild.branch || 'HEAD') + "--" +
                           (inBuild.commit || 'unknown') + ".log";

         if (config.logs.url) {
            inBuild.logUrl = path.join(config.logs.url, logFilename);
         }

         inBuild.logPath = path.join(config.logs.path, logFilename);
         return inBuild.logPath;
      }

      var logFileStream;
      function logFile() {
         return logFileStream  =
            logFileStream ||
            fs.createWriteStream(logFilePath(build), {flags:'a+'});
      }

      function finishedBuild() {
         if (logFileStream) logFileStream.end();
         finished();
      }

      function exec(cmd, callback) {
         return childProcess.exec(cmd, execOptions,
            function(err, stdout, stderr) {
               callback(err, stdout.toString());
            });
      }

      function id(inBuild) {
         return inBuild.branch +
            (inBuild.commit ? ' (' + inBuild.commit.substr(0,10) + ')' : '');
      }
   };
};

function echoStatusCmd(noun) {
   return " && echo '"+noun+" Successful' || ( echo '"+noun+" Failed'; exit 1 )";
}
<commit_msg>git-build: run 'git submodule sync' after merge<commit_after>var childProcess  = require('child_process'),
    fs            = require('fs'),
    util          = require('util'),
    logger        = require('log4js').getLogger(),
    path          = require('path');

exports.init = function(config, cimpler) {
   var paths = config.repoPaths;
   paths = Array.isArray(paths) ? paths : [paths]
   paths.forEach(function(repoPath) {
      var consumer = buildConsumer(config, cimpler, repoPath);
      cimpler.consumeBuild(consumer, config.repoRegex);
   });
}

function buildConsumer(config, cimpler, repoPath) {
   return function(build, started, finished) {
      var execOptions = {
         env: {
            BUILD_REPO:   build.repo,
            BUILD_COMMIT: build.commit,
            BUILD_BRANCH: build.branch,
            BUILD_STATUS: build.status
         },
         timeout: config.timeout || 0
      },
      cdToRepo = 'set -v; set -x; cd "' + repoPath + '"';

      for(var key in process.env) {
         execOptions.env[key] = process.env[key];
      }

      if (!repoPath) {
         throw new Error("Missing the 'path' option of git-build config");
      }

      logger.info(id(build) + " -- Building with git");

      startFetch();

      function startFetch() {
         var commands = '(cd "' + repoPath + '" && ' +
            "git fetch --quiet && " +
            "git rev-parse origin/" + build.branch + ") 2>&1";

         exec(commands, function(err, stdout) {
            if (err) {
               var failed = "Fetch Failed";
               build.status = 'error';
               build.error = failed;
               stdout += "\n\n" + failed;
               logger.warn(id(build) + " -- " + failed);
               if (logFilePath(build)) {
                  fs.writeFileSync(logFilePath(build), stdout);
               }
               finishedBuild();
            } else {
               if (!build.commit) {
                  build.commit = stdout.trim();
               }
               startMerge();
            }
         });
      }

      function startMerge() {
         var commands = '(' + cdToRepo + " && " +
            "git reset --hard && " +
            "git clean -ffd && " +
            "git checkout "+build.commit+" && " +
            "git merge origin/master && " +
            "git submodule sync && " +
            "git submodule update --init --recursive ) 2>&1";

         exec(commands, function(err, stdout) {
            var nextStep, message;

            if (err) {
               message = "Merge Failed";
               nextStep = finishedBuild;
               build.status = 'error';
               build.error = message;
               stdout += "\n\n" + message;

            } else {
               message = "Merge Successful";
               nextStep = startBuild;
               stdout = message + "\n";

            }

            // Assigns a log file to this build
            var logPath = logFilePath(build);

            logger.info(id(build) + " -- " + message);
            if (logPath) {
               fs.writeFileSync(logPath, stdout);
            }

            nextStep(started);
         });
      }

      function startBuild(started) {
         var buildCommand = build.buildCommand || config.cmd;
         var commands = cdToRepo + " && (" + buildCommand + ")" +
                        echoStatusCmd('Build');

         var proc = exec(commands, function(err, stdout, stderr) {
            build.status = err ? 'failure' : 'success';
            logger.info(id(build) + " -- Build " + build.status);
            finishedBuild();
         });

         /**
          * Use piping instead of shell redirection to capture output
          * in case of a syntax error in cmd
          */
         proc.stdout.pipe(logFile(), {end:false});
         proc.stderr.pipe(logFile(), {end:false});
         if (build._control.tail_log) {
            build._control.logs = {
               stdout : proc.stdout,
               stderr : proc.stderr
            };
         }

         // Fire the started event now that our build has a log.
         started();
      }

      function logFilePath(inBuild) {
         if (!config.logs || !config.logs.path)
            return null;

         var logFilename = (inBuild.branch || 'HEAD') + "--" +
                           (inBuild.commit || 'unknown') + ".log";

         if (config.logs.url) {
            inBuild.logUrl = path.join(config.logs.url, logFilename);
         }

         inBuild.logPath = path.join(config.logs.path, logFilename);
         return inBuild.logPath;
      }

      var logFileStream;
      function logFile() {
         return logFileStream  =
            logFileStream ||
            fs.createWriteStream(logFilePath(build), {flags:'a+'});
      }

      function finishedBuild() {
         if (logFileStream) logFileStream.end();
         finished();
      }

      function exec(cmd, callback) {
         return childProcess.exec(cmd, execOptions,
            function(err, stdout, stderr) {
               callback(err, stdout.toString());
            });
      }

      function id(inBuild) {
         return inBuild.branch +
            (inBuild.commit ? ' (' + inBuild.commit.substr(0,10) + ')' : '');
      }
   };
};

function echoStatusCmd(noun) {
   return " && echo '"+noun+" Successful' || ( echo '"+noun+" Failed'; exit 1 )";
}
<|endoftext|>


<commit_before>import React from 'react';
import { expect } from 'chai';
import TestUtils from 'react-addons-test-utils';
import * as components from 'components';

describe('themability', () => {
  Object.keys(components).forEach((key) => {
    let componentClass = components[key];

    describe(key, () => {
      describe('_mixTheme', () => {
        before(() => {
          global.oldTheme = componentClass.defaultTheme;
          componentClass.defaultTheme = {
            one: 'one',
            three: {
              test: 'three'
            }
          };
        });

        after(() => {
          componentClass.defaultTheme = global.oldTheme;
        });

        it('returns an object with combined themes', () => {
          let component = TestUtils.renderIntoDocument(React.createElement(componentClass, {theme: {two: 'two'}}));
          expect(component._mixTheme()).to.deep.equal({
            one: 'one',
            two: 'two',
            three: {
              test: 'three'
            }
          });
        });
      });
    });
  });
});<commit_msg>Remove themability spec<commit_after><|endoftext|>


<commit_before>'use strict'

const t = require('tap')
const test = t.test
const sget = require('simple-get').concat
const fastify = require('..')

const sgetForwardedRequest = (app, forHeader, path) => {
  sget({
    method: 'GET',
    headers: {
      'X-Forwarded-For': forHeader,
      'X-Forwarded-Host': 'example.com'
    },
    url: 'http://localhost:' + app.server.address().port + path
  }, () => {})
}

const testRequestValues = (t, req, options) => {
  if (options.ip) {
    t.ok(req.raw.ip, 'ip is defined')
    t.equal(req.raw.ip, options.ip, 'gets ip from x-forwarder-for')
  }
  if (options.hostname) {
    t.ok(req.raw.hostname, 'hostname is defined')
    t.equal(req.raw.hostname, options.hostname, 'gets hostname from x-forwarded-host')
  }
  if (options.ips) {
    t.deepEqual(req.raw.ips, options.ips, 'gets ips from x-forwarder-for')
  }
}

test('trust proxy', (t) => {
  t.plan(8)
  const app = fastify({
    trustProxy: true
  })
  app.get('/trustproxy', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1', hostname: 'example.com'})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  app.get('/trustproxychain', function (req, reply) {
    testRequestValues(t, req, {ip: '2.2.2.2', ips: ['127.0.0.1', '1.1.1.1', '2.2.2.2']})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '1.1.1.1', '/trustproxy')
    sgetForwardedRequest(app, '2.2.2.2, 1.1.1.1', '/trustproxychain')
  })
})

test('trust proxy chain', (t) => {
  t.plan(3)
  const app = fastify({
    trustProxy: ['127.0.0.1', '192.168.1.1']
  })

  app.get('/trustproxychain', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1'})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '192.168.1.1, 1.1.1.1', '/trustproxychain')
  })
})

test('trust proxy function', (t) => {
  t.plan(3)
  const app = fastify({
    trustProxy: (address) => address === '127.0.0.1'
  })
  app.get('/trustproxyfunc', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1'})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '1.1.1.1', '/trustproxyfunc')
  })
})

test('trust proxy number', (t) => {
  t.plan(4)
  const app = fastify({
    trustProxy: 1
  })
  app.get('/trustproxynumber', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1', ips: ['127.0.0.1', '1.1.1.1']})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '2.2.2.2, 1.1.1.1', '/trustproxynumber')
  })
})
<commit_msg>Add test for trust proxy with ip addresses (#1111)<commit_after>'use strict'

const t = require('tap')
const test = t.test
const sget = require('simple-get').concat
const fastify = require('..')

const sgetForwardedRequest = (app, forHeader, path) => {
  sget({
    method: 'GET',
    headers: {
      'X-Forwarded-For': forHeader,
      'X-Forwarded-Host': 'example.com'
    },
    url: 'http://localhost:' + app.server.address().port + path
  }, () => {})
}

const testRequestValues = (t, req, options) => {
  if (options.ip) {
    t.ok(req.raw.ip, 'ip is defined')
    t.equal(req.raw.ip, options.ip, 'gets ip from x-forwarder-for')
  }
  if (options.hostname) {
    t.ok(req.raw.hostname, 'hostname is defined')
    t.equal(req.raw.hostname, options.hostname, 'gets hostname from x-forwarded-host')
  }
  if (options.ips) {
    t.deepEqual(req.raw.ips, options.ips, 'gets ips from x-forwarder-for')
  }
}

test('trust proxy', (t) => {
  t.plan(8)
  const app = fastify({
    trustProxy: true
  })
  app.get('/trustproxy', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1', hostname: 'example.com'})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  app.get('/trustproxychain', function (req, reply) {
    testRequestValues(t, req, {ip: '2.2.2.2', ips: ['127.0.0.1', '1.1.1.1', '2.2.2.2']})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '1.1.1.1', '/trustproxy')
    sgetForwardedRequest(app, '2.2.2.2, 1.1.1.1', '/trustproxychain')
  })
})

test('trust proxy chain', (t) => {
  t.plan(3)
  const app = fastify({
    trustProxy: ['127.0.0.1', '192.168.1.1']
  })

  app.get('/trustproxychain', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1'})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '192.168.1.1, 1.1.1.1', '/trustproxychain')
  })
})

test('trust proxy function', (t) => {
  t.plan(3)
  const app = fastify({
    trustProxy: (address) => address === '127.0.0.1'
  })
  app.get('/trustproxyfunc', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1'})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '1.1.1.1', '/trustproxyfunc')
  })
})

test('trust proxy number', (t) => {
  t.plan(4)
  const app = fastify({
    trustProxy: 1
  })
  app.get('/trustproxynumber', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1', ips: ['127.0.0.1', '1.1.1.1']})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '2.2.2.2, 1.1.1.1', '/trustproxynumber')
  })
})

test('trust proxy IP addresses', (t) => {
  t.plan(4)
  const app = fastify({
    trustProxy: '127.0.0.1, 2.2.2.2'
  })
  app.get('/trustproxyipaddrs', function (req, reply) {
    testRequestValues(t, req, {ip: '1.1.1.1', ips: ['127.0.0.1', '1.1.1.1']})
    reply.code(200).send({ip: req.ip, hostname: req.hostname})
  })

  t.tearDown(app.close.bind(app))

  app.listen(0, (err) => {
    app.server.unref()
    t.error(err)
    sgetForwardedRequest(app, '3.3.3.3, 2.2.2.2, 1.1.1.1', '/trustproxyipaddrs')
  })
})
<|endoftext|>


<commit_before>"use strict";

var eol = require('os').EOL;
var Pattern = require('../core/lib/object_factory').Pattern;
var extend = require('util')._extend;

function createFakePatternLab(customProps) {
  var pl = {
    config: {
      paths: {
        source: {
          patterns: './test/files/_patterns'
        },
        public: {
          patterns: './test/output'
        }
      },
      styleGuideExcludes: [ 'templates' ],
      debug: false,
      outputFileSuffixes: {
        rendered: '.rendered',
        rawTemplate: '',
        markupOnly: '.markup-only'
      }
    }
  };
  return extend(pl, customProps);
}

var ui = require('../core/lib/ui_builder')();

exports['ui_builder'] = {

  'isPatternExcluded - returns true when pattern filename starts with underscore': function (test) {
    //arrange
    var patternlab = createFakePatternLab({});
    var pattern = new Pattern('00-test/_ignored-pattern.mustache');

    //act
    var result = ui.isPatternExcluded(pattern, patternlab);

    //assert
    test.equals(result, true);
    test.done();
  },

  'isPatternExcluded - returns true when pattern is defaultPattern': function (test) {
    //arrange
    var patternlab = createFakePatternLab({});
    var pattern = new Pattern('00-test/foo.mustache');
    patternlab.config.defaultPattern = 'test-foo';

    //act
    var result = ui.isPatternExcluded(pattern, patternlab);

    //assert
    test.equals(result, true);
    test.done();
  },

  'isPatternExcluded - returns true when pattern within underscored directory - top level': function (test) {
    //arrange
    var patternlab = createFakePatternLab({});
    var pattern = Pattern.createEmpty({
      relPath: '_hidden/patternsubtype/foo.mustache',
      isPattern: true,
      fileName : 'foo.mustache',
      patternPartial: 'hidden-foo'
    });

    //act
    var result = ui.isPatternExcluded(pattern, patternlab);

    //assert
    test.equals(result, true);
    test.done();
  },

  'isPatternExcluded - returns true when pattern within underscored directory - subtype level': function (test) {
    //arrange
    var patternlab = createFakePatternLab({});
    var pattern = Pattern.createEmpty({
      relPath: 'shown/_patternsubtype/foo.mustache',
      isPattern: true,
      fileName : 'foo.mustache',
      patternPartial: 'shown-foo'
    });

    //act
    var result = ui.isPatternExcluded(pattern, patternlab);

    //assert
    test.equals(result, true);
    test.done();
  },

  'groupPatterns - creates pattern groups correctly': function (test) {
    //arrange
    var patternlab = createFakePatternLab({
      patterns: [],
      patternGroups: {},
      subtypePatterns: {}
    });

    patternlab.patterns.push(
      new Pattern('00-test/foo.mustache'),
      new Pattern('00-test/bar.mustache'),
      new Pattern('patternType1/patternSubType1/blue.mustache'),
      new Pattern('patternType1/patternSubType1/red.mustache'),
      new Pattern('patternType1/patternSubType1/yellow.mustache'),
      new Pattern('patternType1/patternSubType2/black.mustache'),
      new Pattern('patternType1/patternSubType2/grey.mustache'),
      new Pattern('patternType1/patternSubType2/white.mustache')
    );
    ui.resetUIBuilderState(patternlab);

    //act
    var result = ui.groupPatterns(patternlab);

    //assert
    test.equals(result.patternGroups.patternType1.patternSubType1.blue.patternPartial, 'patternType1-blue');
    test.equals(result.patternGroups.patternType1.patternSubType1.red.patternPartial, 'patternType1-red');
    test.equals(result.patternGroups.patternType1.patternSubType1.yellow.patternPartial, 'patternType1-yellow');
    test.equals(result.patternGroups.patternType1.patternSubType2.black.patternPartial, 'patternType1-black');
    test.equals(result.patternGroups.patternType1.patternSubType2.grey.patternPartial, 'patternType1-grey');
    test.equals(result.patternGroups.patternType1.patternSubType2.white.patternPartial, 'patternType1-white');

    test.equals(patternlab.patternTypes[0].patternItems[0].patternPartial, 'test-bar');
    test.equals(patternlab.patternTypes[0].patternItems[1].patternPartial, 'test-foo');

    //todo: patternlab.patternTypes[0].patternItems[1] looks malformed

    test.done();
  },

  'groupPatterns - creates documentation patterns for each type and subtype if not exists': function (test) {
    //arrange
    var patternlab = createFakePatternLab({
      patterns: [],
      patternGroups: {},
      subtypePatterns: {}
    });

    patternlab.patterns.push(
      new Pattern('00-test/foo.mustache'),
      new Pattern('00-test/bar.mustache'),
      new Pattern('patternType1/patternSubType1/blue.mustache'),
      new Pattern('patternType1/patternSubType1/red.mustache'),
      new Pattern('patternType1/patternSubType1/yellow.mustache'),
      new Pattern('patternType1/patternSubType2/black.mustache'),
      new Pattern('patternType1/patternSubType2/grey.mustache'),
      new Pattern('patternType1/patternSubType2/white.mustache')
    );
    ui.resetUIBuilderState(patternlab);

    //act
    var result = ui.groupPatterns(patternlab);

    //assert
    test.equals(result.patternGroups.patternType1.patternSubType1['viewall-patternType1-patternSubType1'].patternPartial, 'viewall-patternType1-patternSubType1');
    test.equals(result.patternGroups.patternType1.patternSubType2['viewall-patternType1-patternSubType2'].patternPartial, 'viewall-patternType1-patternSubType2');

    test.done();
  },

  'groupPatterns - adds each pattern to the patternPaths object': function (test) {
    //arrange
    var patternlab = createFakePatternLab({
      patterns: [],
      patternGroups: {},
      subtypePatterns: {}
    });

    patternlab.patterns.push(
      new Pattern('00-test/foo.mustache'),
      new Pattern('00-test/bar.mustache'),
      new Pattern('patternType1/patternSubType1/blue.mustache'),
      new Pattern('patternType1/patternSubType1/red.mustache'),
      new Pattern('patternType1/patternSubType1/yellow.mustache'),
      new Pattern('patternType1/patternSubType2/black.mustache'),
      new Pattern('patternType1/patternSubType2/grey.mustache'),
      new Pattern('patternType1/patternSubType2/white.mustache')
    );
    ui.resetUIBuilderState(patternlab);

    //act
    var result = ui.groupPatterns(patternlab);

    //assert
    test.equals(patternlab.patternPaths['test']['foo'], '00-test-foo');
    test.equals(patternlab.patternPaths['test']['bar'], '00-test-bar');
    test.equals(patternlab.patternPaths['patternType1']['blue'], 'patternType1-patternSubType1-blue');
    test.equals(patternlab.patternPaths['patternType1']['red'], 'patternType1-patternSubType1-red');
    test.equals(patternlab.patternPaths['patternType1']['yellow'], 'patternType1-patternSubType1-yellow');
    test.equals(patternlab.patternPaths['patternType1']['black'], 'patternType1-patternSubType2-black');
    test.equals(patternlab.patternPaths['patternType1']['grey'], 'patternType1-patternSubType2-grey');
    test.equals(patternlab.patternPaths['patternType1']['white'], 'patternType1-patternSubType2-white');

    test.done();
  },

  'groupPatterns - adds each pattern to the view all paths object': function (test) {
    //arrange
    var patternlab = createFakePatternLab({
      patterns: [],
      patternGroups: {},
      subtypePatterns: {}
    });

    patternlab.patterns.push(
      new Pattern('00-test/foo.mustache'),
      new Pattern('00-test/bar.mustache'),
      new Pattern('patternType1/patternSubType1/blue.mustache'),
      new Pattern('patternType1/patternSubType1/red.mustache'),
      new Pattern('patternType1/patternSubType1/yellow.mustache'),
      new Pattern('patternType1/patternSubType2/black.mustache'),
      new Pattern('patternType1/patternSubType2/grey.mustache'),
      new Pattern('patternType1/patternSubType2/white.mustache')
    );
    ui.resetUIBuilderState(patternlab);

    //act
    var result = ui.groupPatterns(patternlab);

    //assert
    test.equals('todo', 'todo');

    test.done();
  },

  'resetUIBuilderState - reset global objects' : function (test) {
    //arrange
    var patternlab = createFakePatternLab({
      patternPaths: { foo: 1},
      viewAllPaths: { bar: 2},
      patternTypes: ['baz']
    });

    //act
    ui.resetUIBuilderState(patternlab);

    //assert
    test.equals(patternlab.patternPaths.foo, undefined);
    test.equals(patternlab.viewAllPaths.bar, undefined);
    test.equals(patternlab.patternTypes.length, 0);

    test.done();
  }

};
<commit_msg>closes #516<commit_after>"use strict";

var tap = require('tap');

var eol = require('os').EOL;
var Pattern = require('../core/lib/object_factory').Pattern;
var extend = require('util')._extend;

function createFakePatternLab(customProps) {
  var pl = {
    config: {
      paths: {
        source: {
          patterns: './test/files/_patterns'
        },
        public: {
          patterns: './test/output'
        }
      },
      styleGuideExcludes: [ 'templates' ],
      debug: false,
      outputFileSuffixes: {
        rendered: '.rendered',
        rawTemplate: '',
        markupOnly: '.markup-only'
      }
    }
  };
  return extend(pl, customProps);
}

var ui = require('../core/lib/ui_builder')();

tap.test('isPatternExcluded - returns true when pattern filename starts with underscore', function (test) {
  //arrange
  var patternlab = createFakePatternLab({});
  var pattern = new Pattern('00-test/_ignored-pattern.mustache');

  //act
  var result = ui.isPatternExcluded(pattern, patternlab);

  //assert
  test.equals(result, true);
  test.end();
});

tap.test('isPatternExcluded - returns true when pattern is defaultPattern', function (test) {
  //arrange
  var patternlab = createFakePatternLab({});
  var pattern = new Pattern('00-test/foo.mustache');
  patternlab.config.defaultPattern = 'test-foo';

  //act
  var result = ui.isPatternExcluded(pattern, patternlab);

  //assert
  test.equals(result, true);
  test.end();
});

tap.test('isPatternExcluded - returns true when pattern within underscored directory - top level', function (test) {
  //arrange
  var patternlab = createFakePatternLab({});
  var pattern = Pattern.createEmpty({
    relPath: '_hidden/patternsubtype/foo.mustache',
    isPattern: true,
    fileName : 'foo.mustache',
    patternPartial: 'hidden-foo'
  });

  //act
  var result = ui.isPatternExcluded(pattern, patternlab);

  //assert
  test.equals(result, true);
  test.end();
});

tap.test('isPatternExcluded - returns true when pattern within underscored directory - subtype level', function (test) {
  //arrange
  var patternlab = createFakePatternLab({});
  var pattern = Pattern.createEmpty({
    relPath: 'shown/_patternsubtype/foo.mustache',
    isPattern: true,
    fileName : 'foo.mustache',
    patternPartial: 'shown-foo'
  });

  //act
  var result = ui.isPatternExcluded(pattern, patternlab);

  //assert
  test.equals(result, true);
  test.end();
});

tap.test('groupPatterns - creates pattern groups correctly', function (test) {
  //arrange
  var patternlab = createFakePatternLab({
    patterns: [],
    patternGroups: {},
    subtypePatterns: {}
  });

  patternlab.patterns.push(
    new Pattern('00-test/foo.mustache'),
    new Pattern('00-test/bar.mustache'),
    new Pattern('patternType1/patternSubType1/blue.mustache'),
    new Pattern('patternType1/patternSubType1/red.mustache'),
    new Pattern('patternType1/patternSubType1/yellow.mustache'),
    new Pattern('patternType1/patternSubType2/black.mustache'),
    new Pattern('patternType1/patternSubType2/grey.mustache'),
    new Pattern('patternType1/patternSubType2/white.mustache')
  );
  ui.resetUIBuilderState(patternlab);

  //act
  var result = ui.groupPatterns(patternlab);

  //assert
  test.equals(result.patternGroups.patternType1.patternSubType1.blue.patternPartial, 'patternType1-blue');
  test.equals(result.patternGroups.patternType1.patternSubType1.red.patternPartial, 'patternType1-red');
  test.equals(result.patternGroups.patternType1.patternSubType1.yellow.patternPartial, 'patternType1-yellow');
  test.equals(result.patternGroups.patternType1.patternSubType2.black.patternPartial, 'patternType1-black');
  test.equals(result.patternGroups.patternType1.patternSubType2.grey.patternPartial, 'patternType1-grey');
  test.equals(result.patternGroups.patternType1.patternSubType2.white.patternPartial, 'patternType1-white');

  test.equals(patternlab.patternTypes[0].patternItems[0].patternPartial, 'test-bar');
  test.equals(patternlab.patternTypes[0].patternItems[1].patternPartial, 'test-foo');

  //todo: patternlab.patternTypes[0].patternItems[1] looks malformed

  test.end();
});

tap.test('groupPatterns - creates documentation patterns for each type and subtype if not exists', function (test) {
  //arrange
  var patternlab = createFakePatternLab({
    patterns: [],
    patternGroups: {},
    subtypePatterns: {}
  });

  patternlab.patterns.push(
    new Pattern('00-test/foo.mustache'),
    new Pattern('00-test/bar.mustache'),
    new Pattern('patternType1/patternSubType1/blue.mustache'),
    new Pattern('patternType1/patternSubType1/red.mustache'),
    new Pattern('patternType1/patternSubType1/yellow.mustache'),
    new Pattern('patternType1/patternSubType2/black.mustache'),
    new Pattern('patternType1/patternSubType2/grey.mustache'),
    new Pattern('patternType1/patternSubType2/white.mustache')
  );
  ui.resetUIBuilderState(patternlab);

  //act
  var result = ui.groupPatterns(patternlab);

  //assert
  test.equals(result.patternGroups.patternType1.patternSubType1['viewall-patternType1-patternSubType1'].patternPartial, 'viewall-patternType1-patternSubType1');
  test.equals(result.patternGroups.patternType1.patternSubType2['viewall-patternType1-patternSubType2'].patternPartial, 'viewall-patternType1-patternSubType2');

  test.end();
});

tap.test('groupPatterns - adds each pattern to the patternPaths object', function (test) {
  //arrange
  var patternlab = createFakePatternLab({
    patterns: [],
    patternGroups: {},
    subtypePatterns: {}
  });

  patternlab.patterns.push(
    new Pattern('00-test/foo.mustache'),
    new Pattern('00-test/bar.mustache'),
    new Pattern('patternType1/patternSubType1/blue.mustache'),
    new Pattern('patternType1/patternSubType1/red.mustache'),
    new Pattern('patternType1/patternSubType1/yellow.mustache'),
    new Pattern('patternType1/patternSubType2/black.mustache'),
    new Pattern('patternType1/patternSubType2/grey.mustache'),
    new Pattern('patternType1/patternSubType2/white.mustache')
  );
  ui.resetUIBuilderState(patternlab);

  //act
  var result = ui.groupPatterns(patternlab);

  //assert
  test.equals(patternlab.patternPaths['test']['foo'], '00-test-foo');
  test.equals(patternlab.patternPaths['test']['bar'], '00-test-bar');
  test.equals(patternlab.patternPaths['patternType1']['blue'], 'patternType1-patternSubType1-blue');
  test.equals(patternlab.patternPaths['patternType1']['red'], 'patternType1-patternSubType1-red');
  test.equals(patternlab.patternPaths['patternType1']['yellow'], 'patternType1-patternSubType1-yellow');
  test.equals(patternlab.patternPaths['patternType1']['black'], 'patternType1-patternSubType2-black');
  test.equals(patternlab.patternPaths['patternType1']['grey'], 'patternType1-patternSubType2-grey');
  test.equals(patternlab.patternPaths['patternType1']['white'], 'patternType1-patternSubType2-white');

  test.end();
});

tap.test('groupPatterns - adds each pattern to the view all paths object', function (test) {
  //arrange
  var patternlab = createFakePatternLab({
    patterns: [],
    patternGroups: {},
    subtypePatterns: {}
  });

  patternlab.patterns.push(
    new Pattern('00-test/foo.mustache'),
    new Pattern('00-test/bar.mustache'),
    new Pattern('patternType1/patternSubType1/blue.mustache'),
    new Pattern('patternType1/patternSubType1/red.mustache'),
    new Pattern('patternType1/patternSubType1/yellow.mustache'),
    new Pattern('patternType1/patternSubType2/black.mustache'),
    new Pattern('patternType1/patternSubType2/grey.mustache'),
    new Pattern('patternType1/patternSubType2/white.mustache')
  );
  ui.resetUIBuilderState(patternlab);

  //act
  var result = ui.groupPatterns(patternlab);

  //assert
  test.equals('todo', 'todo');

  test.end();
});

tap.test('resetUIBuilderState - reset global objects', function (test) {
  //arrange
  var patternlab = createFakePatternLab({
    patternPaths: { foo: 1},
    viewAllPaths: { bar: 2},
    patternTypes: ['baz']
  });

  //act
  ui.resetUIBuilderState(patternlab);

  //assert
  test.equals(patternlab.patternPaths.foo, undefined);
  test.equals(patternlab.viewAllPaths.bar, undefined);
  test.equals(patternlab.patternTypes.length, 0);

  test.end();
});
<|endoftext|>


<commit_before>var expect = require('expect.js'),
    fixtures = require('../fixtures'),
    Cookie = require('../../lib/index.js').Cookie;

/* global describe, it */
describe('Cookie', function () {
    describe('json representation', function () {
        it('must match what it was initialized with', function () {
            var rawCookie = fixtures.collectionV2.item[0].response[0].cookie[0],
                cookie = new Cookie(rawCookie),
                jsonified = cookie.toJSON();
            expect(jsonified.domain).to.eql(rawCookie.domain);
            expect(jsonified.httpOnly).to.eql(rawCookie.httpOnly);
            expect(jsonified.hostOnly).to.eql(rawCookie.hostOnly);
            expect(jsonified.key).to.eql(rawCookie.key);
            expect(jsonified.path).to.eql(rawCookie.path);
            expect(jsonified.expires).to.eql(rawCookie.expires.toString());
            expect(jsonified.secure).to.eql(rawCookie.secure);
            expect(jsonified.session).to.eql(rawCookie.session);
            expect(jsonified.value).to.eql(rawCookie.value);
        });
    });

    describe('parsing', function () {
        var rawCookie = fixtures.rawCookie;
        it('should be parsed properly', function () {
            var parsed = Cookie.parse(rawCookie),
                ext;
            expect(parsed).to.have.property('key', 'GAPS');
            expect(parsed).to.have.property('value', 'lol');
            expect(parsed).to.have.property('expires', 'Sun, 04-Feb-2018 14:18:27 GMT');
            expect(parsed.secure).to.be(true);
            expect(parsed.httpOnly).to.be(true);
            expect(parsed.extensions).to.be.an(Array);
            expect(parsed.extensions.length).to.be(1);

            ext = parsed.extensions[0];
            expect(ext.key).to.be('Priority');
            expect(ext.value).to.be('HIGH');
        });
    });

    describe('isCookie', function () {
        var rawCookie = {
            domain: '.httpbin.org',
            expires: 1502442248,
            hostOnly: false,
            httpOnly: false,
            key: '_ga',
            path: '/',
            secure: false,
            session: false,
            _postman_storeId: '0',
            value: 'GA1.2.113558537.1435817423'
        };

        it('should return true for a cookie instance', function () {
            expect(Cookie.isCookie(new Cookie(rawCookie))).to.be(true);
        });

        it('should return false for a raw cookie object', function () {
            expect(Cookie.isCookie(rawCookie)).to.be(false);
        });

        it('should return false when called without arguments', function () {
            expect(Cookie.isCookie()).to.be(false);
        });
    });
});
<commit_msg>Updated cookie tests to match the changes<commit_after>var expect = require('expect.js'),
    fixtures = require('../fixtures'),
    Cookie = require('../../lib/index.js').Cookie;

/* global describe, it */
describe('Cookie', function () {
    describe('json representation', function () {
        it('must match what it was initialized with', function () {
            var rawCookie = fixtures.collectionV2.item[0].response[0].cookie[0],
                cookie = new Cookie(rawCookie),
                jsonified = cookie.toJSON();
            expect(jsonified.domain).to.eql(rawCookie.domain);
            expect(jsonified.httpOnly).to.eql(rawCookie.httpOnly);
            expect(jsonified.hostOnly).to.eql(rawCookie.hostOnly);
            expect(jsonified.name).to.eql(rawCookie.key);
            expect(jsonified.path).to.eql(rawCookie.path);
            expect(jsonified.expires).to.eql(rawCookie.expires.toString());
            expect(jsonified.secure).to.eql(rawCookie.secure);
            expect(jsonified.session).to.eql(rawCookie.session);
            expect(jsonified.value).to.eql(rawCookie.value);
        });
    });

    describe('parsing', function () {
        var rawCookie = fixtures.rawCookie;
        it('should be parsed properly', function () {
            var parsed = Cookie.parse(rawCookie),
                ext;
            expect(parsed).to.have.property('key', 'GAPS');
            expect(parsed).to.have.property('value', 'lol');
            expect(parsed).to.have.property('expires', 'Sun, 04-Feb-2018 14:18:27 GMT');
            expect(parsed.secure).to.be(true);
            expect(parsed.httpOnly).to.be(true);
            expect(parsed.extensions).to.be.an(Array);
            expect(parsed.extensions.length).to.be(1);

            ext = parsed.extensions[0];
            expect(ext.key).to.be('Priority');
            expect(ext.value).to.be('HIGH');
        });
    });

    describe('isCookie', function () {
        var rawCookie = {
            domain: '.httpbin.org',
            expires: 1502442248,
            hostOnly: false,
            httpOnly: false,
            key: '_ga',
            path: '/',
            secure: false,
            session: false,
            _postman_storeId: '0',
            value: 'GA1.2.113558537.1435817423'
        };

        it('should return true for a cookie instance', function () {
            expect(Cookie.isCookie(new Cookie(rawCookie))).to.be(true);
        });

        it('should return false for a raw cookie object', function () {
            expect(Cookie.isCookie(rawCookie)).to.be(false);
        });

        it('should return false when called without arguments', function () {
            expect(Cookie.isCookie()).to.be(false);
        });
    });
});
<|endoftext|>


<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'YouTube',
    prepareImgLinks:function (callback) {
        var res = [],
            repl = 'http://i1.ytimg.com/vi/$1/0.jpg';

        function decodeQueryString(queryString) {
            var keyValPairs = queryString.split("&"), params = {};
            for (var i = 0; i < keyValPairs.length; i++) {
                var key = decodeURIComponent(keyValPairs[i].split("=")[0]);
                params[key] = decodeURIComponent(keyValPairs[i].split("=")[1] || "");
            }
            return params;
        }

        function decodeStreamMap(url_encoded_fmt_stream_map) {
            var streams = url_encoded_fmt_stream_map.split(","), sources = {};
            for (var i = 0; i < streams.length; i++) {
                var stream = decodeQueryString(streams[i]);
                var type = stream.type.split(";")[0];
                var quality = stream.quality.split(",")[0];
                stream.original_url = stream.url;
                stream.url = "" + stream.url + "&signature=" + stream.sig;
                sources["" + type + " " + quality] = stream;
            }
            return sources;
        }

        function getSource(sources, type, quality) {
            var lowest = null, exact = null;
            for (var key in sources) {
                var source = sources[key];
                if (source.type.match(type)) {
                    if (source.quality.match(quality)) {
                        exact = source;
                    } else {
                        lowest = source;
                    }
                }
            }
            return exact || lowest;
        }

        function prepareVideoPreview(link, id) {
            if (link.hasClass('hoverZoomLoading') || link.hasClass('hoverZoomLink')) return;
            link.addClass('hoverZoomLoading');

            var match = link.attr('href').match(/[\?&]t=([\dhm]+)/);
            var start = match && match.length >= 2 ? match[1] : null;
            if (start && start.indexOf('m') !== -1) {
                var parts = start.split('m');
                if (parts.length == 2) {
                    var parts2 = start.split('h');
                    if (parts2.length == 2)
                        parts[0] = parseInt(parts2[0]) * 60 + parseInt(parts2[1]);
                    start = parseInt(parts[0]) * 60 + parseInt(parts[1] || 0);
                }
            }

            chrome.runtime.sendMessage({action: 'ajaxGet', url: location.protocol + "//www.youtube.com/get_video_info?video_id=" + id}, function (video_info) {
                link.removeClass('hoverZoomLoading');
                var video = decodeQueryString(video_info);
                if (video.status === "fail") {
                    console.log(video.reason);
                    return;
                }
                var sources = decodeStreamMap(video.url_encoded_fmt_stream_map);
                var src = getSource(sources, "webm", "hd720") || getSource(sources, "mp4", "hd720");
                if (src) {
                    link.data().hoverZoomSrc = [start ? src.url + '#t=' + start : src.url];
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        }

        $('a[href*="youtu.be/"]').one('mouseenter', function () {
            var link = $(this), match = this.href.match(/^.*youtu.be\/([\w-]+).*$/);
            if (!match || match.length < 2) return;
            prepareVideoPreview(link, match[1]);
        });

        $('a[href*="youtube.com/watch"]').one('mouseenter', function () {
            var link = $(this), match = this.href.match(/^.*v=([\w-]+).*$/);
            if (!match || match.length < 2) return;
            prepareVideoPreview(link, match[1]);
        });

        // $('a[href*="youtu.be/"] img').each(function () {
        //     var link = $(parentNodeName(this, 'a')),
        //         img = $(this);
        //     img.data().hoverZoomSrc = [link.attr('href').replace(/^.*youtu.be\/([\w-]+).*$/, repl)];
        //     res.push(img);
        // });

        // $('a[href*="youtube.com/watch"] img').each(function () {
        //     var link = $(parentNodeName(this, 'a')),
        //         img = $(this);
        //     img.data().hoverZoomSrc = [link.attr('href').replace(/^.*v=([\w-]+).*$/, repl)];
        //     res.push(img);
        // });

        hoverZoom.urlReplace(res,
            'img[src*="ytimg.com/vi/"], img[src*="ytimg.com/vi_webp/"]',
            /\/([1-9]|default|hqdefault|mqdefault)\.(jpg|webp)/,
            '/0.$2'
        );

        $('a img[data-thumb*="ytimg.com/vi/"]').each(function () {
            var img = $(this);
            img.data().hoverZoomSrc = [this.getAttribute('data-thumb').replace(/\/([1-9]|default|hqdefault|mqdefault)\.jpg/, '/0.jpg')];
            res.push(img);
        });

        callback($(res));
    }
});
<commit_msg>Disabled youtube video preview in embeded iframe<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'YouTube',
    prepareImgLinks:function (callback) {
        var res = [],
            repl = 'http://i1.ytimg.com/vi/$1/0.jpg';

        function decodeQueryString(queryString) {
            var keyValPairs = queryString.split("&"), params = {};
            for (var i = 0; i < keyValPairs.length; i++) {
                var key = decodeURIComponent(keyValPairs[i].split("=")[0]);
                params[key] = decodeURIComponent(keyValPairs[i].split("=")[1] || "");
            }
            return params;
        }

        function decodeStreamMap(url_encoded_fmt_stream_map) {
            var streams = url_encoded_fmt_stream_map.split(","), sources = {};
            for (var i = 0; i < streams.length; i++) {
                var stream = decodeQueryString(streams[i]);
                var type = stream.type.split(";")[0];
                var quality = stream.quality.split(",")[0];
                stream.original_url = stream.url;
                stream.url = "" + stream.url + "&signature=" + stream.sig;
                sources["" + type + " " + quality] = stream;
            }
            return sources;
        }

        function getSource(sources, type, quality) {
            var lowest = null, exact = null;
            for (var key in sources) {
                var source = sources[key];
                if (source.type.match(type)) {
                    if (source.quality.match(quality)) {
                        exact = source;
                    } else {
                        lowest = source;
                    }
                }
            }
            return exact || lowest;
        }

        function prepareVideoPreview(link, id) {
            if (link.hasClass('hoverZoomLoading') || link.hasClass('hoverZoomLink') || link.hasClass('ytp-title-link')) return;
            link.addClass('hoverZoomLoading');

            var match = link.attr('href').match(/[\?&]t=([\dhm]+)/);
            var start = match && match.length >= 2 ? match[1] : null;
            if (start && start.indexOf('m') !== -1) {
                var parts = start.split('m');
                if (parts.length == 2) {
                    var parts2 = start.split('h');
                    if (parts2.length == 2)
                        parts[0] = parseInt(parts2[0]) * 60 + parseInt(parts2[1]);
                    start = parseInt(parts[0]) * 60 + parseInt(parts[1] || 0);
                }
            }

            chrome.runtime.sendMessage({action: 'ajaxGet', url: location.protocol + "//www.youtube.com/get_video_info?video_id=" + id}, function (video_info) {
                link.removeClass('hoverZoomLoading');
                var video = decodeQueryString(video_info);
                if (video.status === "fail") {
                    console.log(video.reason);
                    return;
                }
                var sources = decodeStreamMap(video.url_encoded_fmt_stream_map);
                var src = getSource(sources, "webm", "hd720") || getSource(sources, "mp4", "hd720");
                if (src) {
                    link.data().hoverZoomSrc = [start ? src.url + '#t=' + start : src.url];
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        }

        $('a[href*="youtu.be/"]').one('mouseenter', function () {
            var link = $(this), match = this.href.match(/^.*youtu.be\/([\w-]+).*$/);
            if (!match || match.length < 2) return;
            prepareVideoPreview(link, match[1]);
        });

        $('a[href*="youtube.com/watch"]').one('mouseenter', function () {
            var link = $(this), match = this.href.match(/^.*v=([\w-]+).*$/);
            if (!match || match.length < 2) return;
            prepareVideoPreview(link, match[1]);
        });

        // $('a[href*="youtu.be/"] img').each(function () {
        //     var link = $(parentNodeName(this, 'a')),
        //         img = $(this);
        //     img.data().hoverZoomSrc = [link.attr('href').replace(/^.*youtu.be\/([\w-]+).*$/, repl)];
        //     res.push(img);
        // });

        // $('a[href*="youtube.com/watch"] img').each(function () {
        //     var link = $(parentNodeName(this, 'a')),
        //         img = $(this);
        //     img.data().hoverZoomSrc = [link.attr('href').replace(/^.*v=([\w-]+).*$/, repl)];
        //     res.push(img);
        // });

        hoverZoom.urlReplace(res,
            'img[src*="ytimg.com/vi/"], img[src*="ytimg.com/vi_webp/"]',
            /\/([1-9]|default|hqdefault|mqdefault)\.(jpg|webp)/,
            '/0.$2'
        );

        $('a img[data-thumb*="ytimg.com/vi/"]').each(function () {
            var img = $(this);
            img.data().hoverZoomSrc = [this.getAttribute('data-thumb').replace(/\/([1-9]|default|hqdefault|mqdefault)\.jpg/, '/0.jpg')];
            res.push(img);
        });

        callback($(res));
    }
});
<|endoftext|>