<commit_before>(function(){
    if(window.IPython !== undefined){
        var comm_global = null;

        var callback = function(uuid, ranges){
            comm_global.send({
                type: "selected",
                stage_uuid: uuid,
                range: ranges.x
            });
        };

        window.Nyaplot.sheet_manager.register_sheet(
            "interactive_layer",
            ["parent", "scalex", "scaley", "stage_uuid"],
            {
                opacity: 0.125,
                color: 'gray'
            },
            function(parent, scalex, scaley, stage_uuid, options){
                var brushed = function(){
                    var ranges = {
                        x: (brush.empty() ? scalex.domain() : brush.extent()),
                        y: scaley.domain()
                    };
                    callback(stage_uuid, ranges);
                };

                var brush = d3.svg.brush()
                        .x(scalex)
                        .on("brushend", brushed);

                var model = parent.append("g");
                console.log(scaley);
                var height = d3.max(scaley.range()) - d3.min(scaley.range());
                var y = d3.min(scaley.range());

                parent.call(brush)
                    .selectAll("rect")
                    .attr("y", y)
                    .attr("height", height)
                    .style({
                        "fill-opacity": options.opacity,
                        "fill": options.color,
                        "shape-rendering": "crispEdges"
                    });
            }
        );

        window.IPython.notebook.kernel.comm_manager.register_target("nyaplot_interactive", function(comm, msg){
            comm.on_msg(function(msg_){
                console.log("msg has come. ", msg_);
                var msg = msg_.content.data;

                switch(msg.type){
                case "hello":
                    comm_global = comm;
                    break;
                case "update":
                    /*
                     msg: {
                     type: "update",
                     model: model
                     }
                     */
                    console.log("update");
                    var model = JSON.parse(msg.model);
                    window.Nyaplot.core.parse(model);
                    break;
                default:
                    console.log("error", msg);
                    break;
                }
            });
        });
    }
})();
<commit_msg>Change space<commit_after>(function(){
    if(window.IPython !== undefined){
        var comm_global = null;

        var callback = function(uuid, ranges){
            comm_global.send({
                type: "selected",
                stage_uuid: uuid,
                range: ranges.x
            });
        };

        window.Nyaplot.sheet_manager.register_sheet(
            "interactive_layer",
            ["parent", "scalex", "scaley", "stage_uuid"],
            {
                opacity: 0.125,
                color: 'gray'
            },
            function(parent, scalex, scaley, stage_uuid, options){
                var brushed = function(){
                    var ranges = {
                        x: (brush.empty() ? scalex.domain() : brush.extent()),
                        y: scaley.domain()
                    };
                    callback(stage_uuid, ranges);
                };

                var brush = d3.svg.brush()
                        .x(scalex)
                        .on("brushend", brushed);

                var model = parent.append("g");
                console.log(scaley);
                var height = d3.max(scaley.range()) - d3.min(scaley.range());
                var y = d3.min(scaley.range());

                parent.call(brush)
                    .selectAll("rect")
                    .attr("y", y)
                    .attr("height", height)
                    .style({
                        "fill-opacity": options.opacity,
                        "fill": options.color,
                        "shape-rendering": "crispEdges"
                    });
            }
        );

        window.IPython.notebook.kernel.comm_manager.register_target("nyaplot_interactive", function(comm, msg){
            comm.on_msg(function(msg_){
                console.log("msg has come.", msg_);
                var msg = msg_.content.data;

                switch(msg.type){
                case "hello":
                    comm_global = comm;
                    break;
                case "update":
                    /*
                     msg: {
                     type: "update",
                     model: model
                     }
                     */
                    console.log("update");
                    var model = JSON.parse(msg.model);
                    window.Nyaplot.core.parse(model);
                    break;
                default:
                    console.log("error", msg);
                    break;
                }
            });
        });
    }
})();
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
import { h } from 'preact';
import { define, props } from 'skatejs';
import { BaseComponent } from '../base-component.js';
import { store } from '../../store.js'; // connect to redux

import { Tooltip } from '../pl-tooltip/pl-tooltip';
import VisuallyHidden from '@reach/visually-hidden';

import PhoneIcon from '../../../icons/phone.svg';
import TabletIcon from '../../../icons/tablet.svg';
import LaptopIcon from '../../../icons/laptop.svg';
import DesktopIcon from '../../../icons/desktop.svg';
import DiscoIcon from '../../../icons/disco-ball.svg';
import RandomIcon from '../../../icons/random.svg';

import { minViewportWidth, maxViewportWidth, getRandom } from '../../utils';

// @todo: re-add keyboard shortcuts to these
@define
class ViewportSizes extends BaseComponent {
  static is = 'pl-viewport-sizes';

  _stateChanged(state) {
    this.triggerUpdate();
  }

  constructor(self) {
    self = super(self);
    self.resizeViewport = self.resizeViewport.bind(self);
    self.useShadow = false;
    return self;
  }

  connecting() {
    const state = store.getState();
    const { ishControlsHide } = window.ishControls;
    this.ishControlsHide = ishControlsHide;
  }

  shouldUpdate(prevProps, prevState) {
    return true;
  }

  resizeViewport(size) {
    if (this.iframe) {
      switch (size) {
        case 'small':
          this.iframe.fullMode = false;
          this.iframe.sizeiframe(
            getRandom(
              minViewportWidth,
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.s[1], 10)
                : 500
            ),
            true
          );
          break;
        case 'medium':
          this.iframe.fullMode = false;
          this.iframe.sizeiframe(
            getRandom(
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.m[0], 10)
                : 500,
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.m[1], 10)
                : 800
            ),
            true
          );
          break;
        case 'large':
          this.iframe.fullMode = false;
          this.iframe.sizeiframe(
            getRandom(
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.l[0], 10)
                : 800,
              maxViewportWidth
            ),
            true
          );
          break;
        case 'full':
          this.iframe.fullMode = true;
          this.iframe.sizeiframe(maxViewportWidth, true);
          break;
      }
    }
  }

  rendered() {
    this.iframe = document.querySelector('pl-iframe');
  }

  render() {
    return (

        {!this.ishControlsHide.s && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Small"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-s',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('small')}
                >
                  <VisuallyHidden>Resize viewport to small</VisuallyHidden>
                  <PhoneIcon
                    width={14}
                    height={20}
                    fill="currentColor"
                    viewBox="0 0 24 12"
                  />
                </button>
              )}
            </Tooltip>

        )}
        {!this.ishControlsHide.m && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Medium"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-m',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('medium')}
                >
                  <VisuallyHidden>Resize viewport to medium</VisuallyHidden>
                  <TabletIcon
                    width={16}
                    height={24}
                    fill="currentColor"
                    viewBox="0 0 24 16"
                  />
                </button>
              )}
            </Tooltip>

        )}
        {!this.ishControlsHide.l && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Large"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-l',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('large')}
                >
                  <VisuallyHidden>Resize viewport to large</VisuallyHidden>
                  <LaptopIcon
                    width={24}
                    height={22}
                    fill="currentColor"
                    viewBox="0 0 24 20"
                  />
                </button>
              )}
            </Tooltip>

        )}
        {!this.ishControlsHide.full && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Full"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-full',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('full')}
                >
                  <VisuallyHidden>Resize viewport to full</VisuallyHidden>
                  <DesktopIcon
                    width={24}
                    height={22}
                    fill="currentColor"
                    viewBox="0 0 24 20"
                  />
                </button>
              )}
            </Tooltip>

        )}
        {/* {!this.ishControlsHide.random && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Random"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-random',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('random')}
                >
                  <VisuallyHidden>Resize viewport to random</VisuallyHidden>
                  <RandomIcon
                    width={24}
                    height={24}
                    fill="currentColor"
                    stroke="currentColor"
                    viewBox="0 0 28 28"
                  />
                </button>
              )}
            </Tooltip>

        )} */}
        {/* {!this.ishControlsHide.disco && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Disco"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-disco',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('disco')}
                >
                  <VisuallyHidden>
                    Resize viewport using disco mode!
                  </VisuallyHidden>
                  <DiscoIcon
                    width={24}
                    height={24}
                    fill="currentColor"
                    viewBox="0 0 24 24"
                  />
                </button>
              )}
            </Tooltip>

        )} */}
        {!this.ishControlsHide.hay && (

            <button class="pl-c-size-list__action mode-link" id="pl-size-hay">
              Hay!
            </button>

        )}

    );
  }
}
<commit_msg>refactor: switch over to using new <pl-icon> component<commit_after>/* eslint-disable no-unused-vars */
import { h } from 'preact';
import { define, props } from 'skatejs';
import { BaseComponent } from '../base-component.js';
import { store } from '../../store.js'; // connect to redux

import { Tooltip } from '../pl-tooltip/pl-tooltip';
import VisuallyHidden from '@reach/visually-hidden';

import { minViewportWidth, maxViewportWidth, getRandom } from '../../utils';

// @todo: re-add keyboard shortcuts to these
@define
class ViewportSizes extends BaseComponent {
  static is = 'pl-viewport-sizes';

  _stateChanged(state) {
    this.triggerUpdate();
  }

  constructor(self) {
    self = super(self);
    self.resizeViewport = self.resizeViewport.bind(self);
    self.useShadow = false;
    return self;
  }

  connecting() {
    const state = store.getState();
    const { ishControlsHide } = window.ishControls;
    this.ishControlsHide = ishControlsHide;
  }

  shouldUpdate(prevProps, prevState) {
    return true;
  }

  resizeViewport(size) {
    if (this.iframe) {
      switch (size) {
        case 'small':
          this.iframe.fullMode = false;
          this.iframe.sizeiframe(
            getRandom(
              minViewportWidth,
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.s[1], 10)
                : 500
            ),
            true
          );
          break;
        case 'medium':
          this.iframe.fullMode = false;
          this.iframe.sizeiframe(
            getRandom(
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.m[0], 10)
                : 500,
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.m[1], 10)
                : 800
            ),
            true
          );
          break;
        case 'large':
          this.iframe.fullMode = false;
          this.iframe.sizeiframe(
            getRandom(
              window.config.ishViewportRange !== undefined
                ? parseInt(window.config.ishViewportRange.l[0], 10)
                : 800,
              maxViewportWidth
            ),
            true
          );
          break;
        case 'full':
          this.iframe.fullMode = true;
          this.iframe.sizeiframe(maxViewportWidth, true);
          break;
      }
    }
  }

  rendered() {
    this.iframe = document.querySelector('pl-iframe');
  }

  render() {
    return (

        {!this.ishControlsHide.s && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Small"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-s',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('small')}
                >
                  <VisuallyHidden>Resize viewport to small</VisuallyHidden>
                  <span
                    dangerouslySetInnerHTML={{
                      __html: '<pl-icon name="phone"></pl-icon>',
                    }}
                  />
                </button>
              )}
            </Tooltip>

        )}
        {!this.ishControlsHide.m && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Medium"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-m',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('medium')}
                >
                  <VisuallyHidden>Resize viewport to medium</VisuallyHidden>
                  <span
                    dangerouslySetInnerHTML={{
                      __html: '<pl-icon name="tablet"></pl-icon>',
                    }}
                  />
                </button>
              )}
            </Tooltip>

        )}
        {!this.ishControlsHide.l && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Large"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-l',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('large')}
                >
                  <VisuallyHidden>Resize viewport to large</VisuallyHidden>
                  <span
                    dangerouslySetInnerHTML={{
                      __html: '<pl-icon name="laptop"></pl-icon>',
                    }}
                  />
                </button>
              )}
            </Tooltip>

        )}
        {!this.ishControlsHide.full && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Full"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-full',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('full')}
                >
                  <VisuallyHidden>Resize viewport to full</VisuallyHidden>
                  <span
                    dangerouslySetInnerHTML={{
                      __html: '<pl-icon name="desktop"></pl-icon>',
                    }}
                  />
                </button>
              )}
            </Tooltip>

        )}
        {/* {!this.ishControlsHide.random && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Random"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-random',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('random')}
                >
                  <VisuallyHidden>Resize viewport to random</VisuallyHidden>
                  <RandomIcon
                    width={24}
                    height={24}
                    fill="currentColor"
                    stroke="currentColor"
                    viewBox="0 0 28 28"
                  />
                </button>
              )}
            </Tooltip>

        )} */}
        {/* {!this.ishControlsHide.disco && (

            <Tooltip
              placement="top"
              trigger="hover"
              tooltip="Disco"
              usePortal={false}
            >
              {({ getTriggerProps, triggerRef }) => (
                <button
                  {...getTriggerProps({
                    className: 'pl-c-size-list__action',
                    id: 'pl-size-disco',
                    ref: triggerRef,
                  })}
                  onClick={e => this.resizeViewport('disco')}
                >
                  <VisuallyHidden>
                    Resize viewport using disco mode!
                  </VisuallyHidden>
                  <DiscoIcon
                    width={24}
                    height={24}
                    fill="currentColor"
                    viewBox="0 0 24 24"
                  />
                </button>
              )}
            </Tooltip>

        )} */}
        {!this.ishControlsHide.hay && (

            <button class="pl-c-size-list__action mode-link" id="pl-size-hay">
              Hay!
            </button>

        )}

    );
  }
}
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path'),
	wrench = require('wrench'),
	colors = require('colors'),
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	platforms = require('../../platforms/index');

var TIMEOUT_COMPILE = 10000;
var GEN_FOLDER = '_generated';

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	// Iterate through each test app and make sure it compiles for all platforms
	_.each(wrench.readdirSyncRecursive(paths.apps), function(file) {
		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs)) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1');
			});

			_.each(platforms, function(platform,k) {
				describe('for ' + platform.platform.cyan, function () {
					it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									expect(this.output.error).toBeFalsy();
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness,'Resources');
					var files = wrench.readdirSyncRecursive(genFolder);

					_.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }

						it('matches known good generated code for ' + gFile.yellow, function () {
							var newFile = path.join(hrFolder,gFile);
							expect(fs.existsSync(newFile)).toBeTruthy();

							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
							expect(goodFileContents === newFileContents).toBeTruthy();
						});
					});
				});
			});
		});
	});
});
<commit_msg>don't try to run compile tests on generated code<commit_after>var fs = require('fs'),
	path = require('path'),
	wrench = require('wrench'),
	colors = require('colors'),
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	platforms = require('../../platforms/index');

var TIMEOUT_COMPILE = 10000;
var GEN_FOLDER = '_generated';

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	// Iterate through each test app and make sure it compiles for all platforms
	_.each(wrench.readdirSyncRecursive(paths.apps), function(file) {
		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs) || indexJs.indexOf(GEN_FOLDER) !== -1) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1');
			});

			_.each(platforms, function(platform,k) {
				describe('for ' + platform.platform.cyan, function () {
					it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									expect(this.output.error).toBeFalsy();
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness,'Resources');
					var files = wrench.readdirSyncRecursive(genFolder);

					_.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }

						it('matches known good generated code for ' + gFile.yellow, function () {
							var newFile = path.join(hrFolder,gFile);
							expect(fs.existsSync(newFile)).toBeTruthy();

							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
							expect(goodFileContents === newFileContents).toBeTruthy();
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>var Strategy = require('../lib/strategy')
  , chai = require('chai')
  , qs = require('querystring');

describe('strategy', function() {

  describe('configured to work with a specific OpenID provider', function() {

    describe('issuing authorization request', function() {

      describe('that redirects to service provider without redirect URI', function() {
        var strategy = new Strategy({
          authorizationURL: 'https://www.example.com/oauth2/authorize',
          tokenURL: 'https://www.example.com/oauth2/token',
          clientID: 'ABC123',
          clientSecret: 'secret'
        },
        function(accessToken, refreshToken, profile, done) {});

        var state, url;

        before(function(done) {
          chai.passport.use(strategy)
            .redirect(function(u) {
              state = encodeURIComponent(qs.parse(u).state);
              url = u;
              done();
            })
            .req(function(req) {
              req.session = {};
            })
            .authenticate();
        });

        it('should be redirected', function() {
          expect(url).to.equal('https://www.example.com/oauth2/authorize?response_type=code&client_id=ABC123&scope=openid&state=' + state);
        });
      }); // that redirects to service provider without redirect URI

    }); // issuing authorization request

  }); // configured to work with a known OpenID provider

}); // Strategy
<commit_msg>Update test case.<commit_after>var Strategy = require('../lib/strategy')
  , chai = require('chai')
  , uri = require('url')
  , qs = require('querystring');

describe('strategy', function() {

  describe('configured to work with a specific OpenID provider', function() {

    describe('issuing authorization request', function() {

      describe('that redirects to service provider without redirect URI', function() {
        var strategy = new Strategy({
          issuer: 'https://www.example.com',
          authorizationURL: 'https://www.example.com/oauth2/authorize',
          tokenURL: 'https://www.example.com/oauth2/token',
          clientID: 'ABC123',
          clientSecret: 'secret'
        }, function() {});

        var request, url, state;

        before(function(done) {
          chai.passport.use(strategy)
            .redirect(function(u) {
              var pu = uri.parse(u, true);

              state = pu.query.state;
              url = u;
              done();
            })
            .req(function(req) {
              request = req;
              req.session = {};
            })
            .authenticate();
        });

        it('should be redirected', function() {
          expect(url).to.equal('https://www.example.com/oauth2/authorize?response_type=code&client_id=ABC123&scope=openid&state=' + encodeURIComponent(state));
        });

        it('should save state in session', function() {
          expect(request.session['openidconnect:www.example.com'].state).to.have.length(24);
          expect(request.session['openidconnect:www.example.com'].state).to.equal(state);
        });
      }); // that redirects to service provider without redirect URI

    }); // issuing authorization request

  }); // configured to work with a known OpenID provider

}); // Strategy
<|endoftext|>


<commit_before>"use strict";
var expect = require('expect.js');
var qacServices = require('../lib/qac-services.js');
var qacCommon = require('../lib/qcs-common.js');
var helper=require('../test/test-helper.js');
var html = require('js-to-html').html;
var sinon = require('sinon');
var Promises = require('best-promise');
var fs = require('fs-promise');
var Path = require('path');
var _ = require('lodash');

describe('qac-services coverage', function(){
    describe('common', function() {
        var expHeads = [
                        html.link({href:'/markdown.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/markdown2.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/github.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/qcs.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/favicon.ico', rel:'shortcut icon'})
                          ];
        it('simpleHead', function(done) {
            var sh = qacCommon.simpleHead(null, qacServices);
            expect(sh).to.eql(html.head(expHeads));
            done();
        });
        it('simpleHead with params', function(done) {
            var sh = qacCommon.simpleHead('optional.css', qacServices);
            expHeads.splice(4, 0, html.link({href:'/optional.css', media:'all', rel:'stylesheet'}));
            expect(sh).to.eql(html.head(expHeads));
            done();
        });
        var title = "un titulo", content="el contenido";
        var css = 'extra.css';
        var exCSS = "<link href='/"+css+"' media=all rel=stylesheet>";
        function expHT(title, content, css) {
            return "<!doctype html>\n"+
                  "<title>"+title+"</title><link href='/markdown.css' media=all rel=stylesheet>"+
                  "<link href='/markdown2.css' media=all rel=stylesheet><link href='/github.css' media=all rel=stylesheet>"+
                  "<link href='/qcs.css' media=all rel=stylesheet>"+
                  css+"<link rel='shortcut icon' href='/favicon.ico'>"+
                  ""+content+""
        }
        it('simpleHtml', function(done) {
            var sh = qacCommon.simpleHtml(title, content, null, qacServices);
            expect(sh).to.eql(expHT(title, content, ""));
            done();
        });
        it('simpleHtml with params', function(done) {
            var sh = qacCommon.simpleHtml(title, content, css, qacServices);
            expect(sh).to.eql(expHT(title, content, exCSS));
            done();
        });
        it('simpleHtml without title', function(done) {
            var sh = qacCommon.simpleHtml(null, content, css, qacServices);
            expect(sh).to.eql(expHT('qa-control', content, exCSS));
            done();
        });
    });
    describe('button generation', function() {
        var org='una-organization', proj='un-proyecto';
        it('project actions unlogged', function(done) {
            expect(qacServices.projectActionButtons(org, proj)).to.eql([]);
            done();
        });
        it('organization/project add actions unlogged', function(done) {
            expect(qacServices.orgAddButton()).to.eql([]);
            expect(qacServices.projectAddButton()).to.eql([]);
            done();
        });
    });
    describe('config', function() {
        it('wrong params', function(done) {
            expect(qacServices.config).withArgs(null).to.throwException(/must set 'production' in config/);
            expect(qacServices.config).withArgs(true, false).to.not.throwException();
            expect(qacServices.production).to.not.be.ok();
            done();
        });
        it('initialization', function(done) {
            var miConfig = _.cloneDeep(helper.testConfig);
            miConfig['root-url'] = '/something';
            miConfig.repository.path = 'a-path';
            miConfig.repository.request_secret = 'a-secret';
            qacServices.config(miConfig, true);
            expect(qacServices.repository.path).to.eql('a-path');
            expect(qacServices.repository.request_secret).to.eql('a-secret');
            expect(qacServices.rootUrl).to.eql('/something');
            expect(qacServices.production).to.eql(true);
            helper.setup(qacServices); // restauro
            done();
        });
    });
    describe('getProject', function() {
        it('wrong error', function(done) {
            var orga='la-org', proj='el-proj';
            sinon.stub(fs, 'readFile', function(nameCucardas){
                //console.log("nameCucardas", nameCucardas);
                switch(nameCucardas){
                    case Path.normalize('la-org-path/projects/'+proj+'/result/cucardas.md'): return Promises.reject({code:'not-ENOENT'});
                    default: throw new Error('unexpected params in readFile of cucardas');
                }
            });
            qacServices.getProject(helper.session, {organization:{name:orga, path:'la-org-path'}}, {projectName:proj}).catch(function(err) {
                fs.readFile.restore();
                expect(err.code).to.eql('not-ENOENT');
                done();
            }).catch(function(que) {
                done('should not happen');
            })
        });
    });
    describe('functions', function() {
        it('md5Prefixed', function(done) {
            expect(qacServices.md5Prefixed('guest')).to.eql('md5.084e0343a0486ff05530df6c705c8bb4');
            done();
        });
        it('noCacheHeaders', function(done) {
            function Req() {
                this.v1 = '';
                this.v2 = '';
                var yo =this;
                this.header=function(p1, p2) {
                    yo.v1 = p1;
                    yo.v2 = p2;
                };
            }
            var req = new Req();
            qacServices.noCacheHeaders(req);
            expect(req.v1).to.eql('Cache-Control');
            expect(req.v2).to.eql('no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
            done();
        });
        it('sortProjects', function(done) {
            var p1={content:[{content:[{attributes:{href:'Alerta'}}]}]};
            var p2={content:[{content:[{attributes:{href:'Roja'}}]}]};
            expect(qacServices.sortProjects(p1, p2)).to.eql(-1);
            expect(qacServices.sortProjects(p2, p1)).to.eql(1);
            expect(qacServices.sortProjects(p1, p1)).to.eql(0);
            done();
        });
        it('invalidSVG', function(done) {
            qacServices.invalidSVG().then(function(svg) {
               var msv = '<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20">'+
                                  '<linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/>'+
                                  '<stop offset="1" stop-opacity=".1"/></linearGradient><mask id="a">'+
                                  '<rect width="115" height="20" rx="3" fill="#fff"/></mask><g mask="url(#a)">'+
                                  '<path fill="#555" d="M0 0h68v20H0z"/><path fill="#9f9f9f" d="M68 0h47v20H68z"/>'+
                                  '<path fill="url(#b)" d="M0 0h115v20H0z"/></g>'+
                                  '<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">'+
                                  '<text x="34" y="15" fill="#010101" fill-opacity=".3">qa-control</text>'+
                                  '<text x="34" y="14">qa-control</text><text x="90.5" y="15" fill="#010101" fill-opacity=".3">invalid</text>'+
                                  '<text x="90.5" y="14">invalid</text></g></svg>';
               expect(svg).to.eql(msv);
               done();
            });
        }, function(err) {
            console.log("err", err);
            done(err);
        });
        it('gitHubUrl', function(done) {
            var url = {uri: 'https://api.github.com/uno/dos/repos', headers: { 'User-Agent': 'Request-Promise' } };
            expect(qacServices.gitHubUrl('uno', 'dos')).to.eql(url);
            url.uri = 'https://api.github.com/tres/cuatro/repos';
            expect(qacServices.gitHubUrl('tres', 'cuatro')).to.eql(url);
            done();
        });
        it('uriIsHandled', function(done) {
            expect(qacServices.uriIsHandled({params:{organization: 'login'}})).to.be.ok();
            expect(qacServices.uriIsHandled({params:{organization: 'manual-delete'}})).to.be.ok();
            expect(qacServices.uriIsHandled({params:{organization: 'anual-delete'}})).to.not.be.ok();
            done();
        });
        it('enableLoginPlus', function(done) {
            expect(qacServices.enableLoginPlus).withArgs(null).to.throwException(/must provide path to users database/);
            expect(qacServices.enableLoginPlus).withArgs('non_existent_path').to.throwException(/users database not found/);
            done();
        });
    });
    describe('session', function() {
        it('setSession', function(done) {
            var ses = {};
            expect(qacServices.setSession(null)).to.eql(ses);
            var req = {};
            expect(qacServices.setSession(req)).to.eql(ses);
            req['cookies'] = null;
            expect(qacServices.setSession(req)).to.eql(ses);
            req['cookies'] = {};
            expect(qacServices.setSession(req)).to.eql(ses);
            var cKey = 'connect.sid';
            req['cookies'][cKey] = null;
            expect(qacServices.setSession(req)).to.eql(ses);
            var cVal = 'un-sid';
            req['cookies'][cKey] = cVal;
            expect(qacServices.setSession(req)).to.eql(ses);
            req['session'] = {};
            expect(qacServices.setSession(req)).to.eql(ses);
            req['session']['passport'] = {}
            expect(qacServices.setSession(req)).to.eql(ses);
            req['session']['passport']['user'] = null;
            expect(qacServices.setSession(req)).to.eql(ses);
            var cUser = 'un-user';
            req['session']['passport']['user'] = cUser;
            ses[cVal] = cUser;
            expect(qacServices.setSession(req)).to.eql(ses);

            qacServices.users = qacServices.setSession(req);
            expect(qacServices.users).to.eql(ses);
            cVal = 'otro-sid';
            cUser = 'otro-user';
            ses[cVal] = cUser;
            req['session']['passport']['user'] = cUser;
            req['cookies'][cKey] = cVal;
            qacServices.users = qacServices.setSession(req);
            expect(qacServices.users).to.eql(ses);

            qacServices.users = null; // reseteo
            done();
        });
        it('test (fake session)', function(done) {
            expect(qacServices.setSession(helper.session.req)).to.eql(helper.session.users);
            done();
        });
        it('validSession', function(done) {
            qacServices.users = qacServices.setSession(helper.session.req);
            expect(qacServices.users).to.eql(helper.session.users);
            expect(qacServices.validSession(null)).to.eql(null);
            var req = {};
            expect(qacServices.validSession(req)).to.eql(null);
            req['cookies']={'connect.sid':''};
            expect(qacServices.validSession(req)).to.not.be.ok();
            req['cookies']={'connect.sid':'wrong-user'};
            expect(qacServices.validSession(req)).to.not.be.ok();
            req['cookies']={'connect.sid':'fake-sid'};
            expect(qacServices.validSession(req)).to.be.ok();
            qacServices.users = null; // reseteo
            done();
        });
    });
});
<commit_msg>Coverage: getProjectLogs()<commit_after>"use strict";
var expect = require('expect.js');
var qacServices = require('../lib/qac-services.js');
var qacCommon = require('../lib/qcs-common.js');
var helper=require('../test/test-helper.js');
var html = require('js-to-html').html;
var sinon = require('sinon');
var Promises = require('best-promise');
var fs = require('fs-promise');
var Path = require('path');
var _ = require('lodash');

describe('qac-services coverage', function(){
    describe('common', function() {
        var expHeads = [
                        html.link({href:'/markdown.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/markdown2.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/github.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/qcs.css', media:'all', rel:'stylesheet'}),
                        html.link({href:'/favicon.ico', rel:'shortcut icon'})
                          ];
        it('simpleHead', function(done) {
            var sh = qacCommon.simpleHead(null, qacServices);
            expect(sh).to.eql(html.head(expHeads));
            done();
        });
        it('simpleHead with params', function(done) {
            var sh = qacCommon.simpleHead('optional.css', qacServices);
            expHeads.splice(4, 0, html.link({href:'/optional.css', media:'all', rel:'stylesheet'}));
            expect(sh).to.eql(html.head(expHeads));
            done();
        });
        var title = "un titulo", content="el contenido";
        var css = 'extra.css';
        var exCSS = "<link href='/"+css+"' media=all rel=stylesheet>";
        function expHT(title, content, css) {
            return "<!doctype html>\n"+
                  "<title>"+title+"</title><link href='/markdown.css' media=all rel=stylesheet>"+
                  "<link href='/markdown2.css' media=all rel=stylesheet><link href='/github.css' media=all rel=stylesheet>"+
                  "<link href='/qcs.css' media=all rel=stylesheet>"+
                  css+"<link rel='shortcut icon' href='/favicon.ico'>"+
                  ""+content+""
        }
        it('simpleHtml', function(done) {
            var sh = qacCommon.simpleHtml(title, content, null, qacServices);
            expect(sh).to.eql(expHT(title, content, ""));
            done();
        });
        it('simpleHtml with params', function(done) {
            var sh = qacCommon.simpleHtml(title, content, css, qacServices);
            expect(sh).to.eql(expHT(title, content, exCSS));
            done();
        });
        it('simpleHtml without title', function(done) {
            var sh = qacCommon.simpleHtml(null, content, css, qacServices);
            expect(sh).to.eql(expHT('qa-control', content, exCSS));
            done();
        });
    });
    describe('button generation', function() {
        var org='una-organization', proj='un-proyecto';
        it('project actions unlogged', function(done) {
            expect(qacServices.projectActionButtons(org, proj)).to.eql([]);
            done();
        });
        it('organization/project add actions unlogged', function(done) {
            expect(qacServices.orgAddButton()).to.eql([]);
            expect(qacServices.projectAddButton()).to.eql([]);
            done();
        });
    });
    describe('config', function() {
        it('wrong params', function(done) {
            expect(qacServices.config).withArgs(null).to.throwException(/must set 'production' in config/);
            expect(qacServices.config).withArgs(true, false).to.not.throwException();
            expect(qacServices.production).to.not.be.ok();
            done();
        });
        it('initialization', function(done) {
            var miConfig = _.cloneDeep(helper.testConfig);
            miConfig['root-url'] = '/something';
            miConfig.repository.path = 'a-path';
            miConfig.repository.request_secret = 'a-secret';
            qacServices.config(miConfig, true);
            expect(qacServices.repository.path).to.eql('a-path');
            expect(qacServices.repository.request_secret).to.eql('a-secret');
            expect(qacServices.rootUrl).to.eql('/something');
            expect(qacServices.production).to.eql(true);
            helper.setup(qacServices); // restauro
            done();
        });
    });
    describe('project', function() {
        it('getProject() wrong error', function(done) {
            var orga='la-org', proj='el-proj';
            sinon.stub(fs, 'readFile', function(nameCucardas){
                //console.log("nameCucardas", nameCucardas);
                switch(nameCucardas){
                    case Path.normalize('la-org-path/projects/'+proj+'/result/cucardas.md'): return Promises.reject({code:'not-ENOENT'});
                    default: throw new Error('unexpected params in readFile of cucardas');
                }
            });
            qacServices.getProject(helper.session, {organization:{name:orga, path:'la-org-path'}}, {projectName:proj}).catch(function(err) {
                fs.readFile.restore();
                expect(err.code).to.eql('not-ENOENT');
                done();
            }).catch(function(que) {
                done('should not happen');
            })
        });
        it('getProjectLogs()', function(done) {
            var projPath = 'path-del-proyecto';
            sinon.stub(fs, 'readJSON', function(jsonPath){
                // console.log("jsonPath", jsonPath);
                switch(jsonPath){
                    case Path.normalize(projPath+'/result/qa-control-result.json'):
                        return Promises.resolve([
                            {"warning": "elwarning","params": ["index.js"],"scoring": {"customs": 1}},
                            {"warning": "elwarning2", "scoring": {"customs": 1}}
                        ]);
                    case Path.normalize(projPath+'/result/bitacora.json'):
                        return Promises.resolve([
                            {"date": "fecha1", "origin": "command", "text": "git clone"},
                            {"date": "fecha2","origin": "exit","text": "0"},
                            {"date": "fecha3","origin": "shell","text": "el-shell"},
                            {"date": "fecha4","origin": "internal","text": "\"cucardas.md\" generated"}
                        ]);
                    default:
                        return Promises.reject('unexpected params in readJSON ['+jsonPath+']');
                }
            });
            qacServices.getProjectLogs(projPath).then(function(logs) {
                //console.log("logs", logs)
                var result=[
                    html.hr(),
                    html.table([
                        html.tr([
                            html.th({colspan:3}, 'QA Control result')
                        ]),
                        html.tr([ html.td('warning'), html.td('file'), html.td('scoring') ]),
                        html.tr([ html.td('elwarning'), html.td('index.js'), html.td('1') ]),
                        html.tr([ html.td('elwarning2'), html.td(''), html.td('1') ])
                        ]),
                    html.hr(),
                    html.table([
                        html.tr([ html.th('Actions log') ]),
                        html.tr([ html.td([ html.div({class:'stdout'}, 'git clone') ]) ]),
                        html.tr([ html.td([ html.div({class:'stdout'}, '0') ]) ]),
                        html.tr([ html.td([ html.div({class:'shell'}, 'el-shell') ]) ]),
                        html.tr([ html.td([ html.div({class:'internal'}, '\"cucardas.md\" generated') ]) ])
                        ])
                   ];
                expect(logs).to.eql(result);
                fs.readJSON.restore();
                done();
            }).catch(function(err) {
                console.log("ERR", err);
                done(err);
            });
        });
    });
    describe('functions', function() {
        it('md5Prefixed', function(done) {
            expect(qacServices.md5Prefixed('guest')).to.eql('md5.084e0343a0486ff05530df6c705c8bb4');
            done();
        });
        it('noCacheHeaders', function(done) {
            function Req() {
                this.v1 = '';
                this.v2 = '';
                var yo =this;
                this.header=function(p1, p2) {
                    yo.v1 = p1;
                    yo.v2 = p2;
                };
            }
            var req = new Req();
            qacServices.noCacheHeaders(req);
            expect(req.v1).to.eql('Cache-Control');
            expect(req.v2).to.eql('no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
            done();
        });
        it('sortProjects', function(done) {
            var p1={content:[{content:[{attributes:{href:'Alerta'}}]}]};
            var p2={content:[{content:[{attributes:{href:'Roja'}}]}]};
            expect(qacServices.sortProjects(p1, p2)).to.eql(-1);
            expect(qacServices.sortProjects(p2, p1)).to.eql(1);
            expect(qacServices.sortProjects(p1, p1)).to.eql(0);
            done();
        });
        it('invalidSVG', function(done) {
            qacServices.invalidSVG().then(function(svg) {
               var msv = '<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20">'+
                                  '<linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/>'+
                                  '<stop offset="1" stop-opacity=".1"/></linearGradient><mask id="a">'+
                                  '<rect width="115" height="20" rx="3" fill="#fff"/></mask><g mask="url(#a)">'+
                                  '<path fill="#555" d="M0 0h68v20H0z"/><path fill="#9f9f9f" d="M68 0h47v20H68z"/>'+
                                  '<path fill="url(#b)" d="M0 0h115v20H0z"/></g>'+
                                  '<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">'+
                                  '<text x="34" y="15" fill="#010101" fill-opacity=".3">qa-control</text>'+
                                  '<text x="34" y="14">qa-control</text><text x="90.5" y="15" fill="#010101" fill-opacity=".3">invalid</text>'+
                                  '<text x="90.5" y="14">invalid</text></g></svg>';
               expect(svg).to.eql(msv);
               done();
            });
        }, function(err) {
            console.log("err", err);
            done(err);
        });
        it('gitHubUrl', function(done) {
            var url = {uri: 'https://api.github.com/uno/dos/repos', headers: { 'User-Agent': 'Request-Promise' } };
            expect(qacServices.gitHubUrl('uno', 'dos')).to.eql(url);
            url.uri = 'https://api.github.com/tres/cuatro/repos';
            expect(qacServices.gitHubUrl('tres', 'cuatro')).to.eql(url);
            done();
        });
        it('uriIsHandled', function(done) {
            expect(qacServices.uriIsHandled({params:{organization: 'login'}})).to.be.ok();
            expect(qacServices.uriIsHandled({params:{organization: 'manual-delete'}})).to.be.ok();
            expect(qacServices.uriIsHandled({params:{organization: 'anual-delete'}})).to.not.be.ok();
            done();
        });
        it('enableLoginPlus', function(done) {
            expect(qacServices.enableLoginPlus).withArgs(null).to.throwException(/must provide path to users database/);
            expect(qacServices.enableLoginPlus).withArgs('non_existent_path').to.throwException(/users database not found/);
            done();
        });
    });
    describe('session', function() {
        it('setSession', function(done) {
            var ses = {};
            expect(qacServices.setSession(null)).to.eql(ses);
            var req = {};
            expect(qacServices.setSession(req)).to.eql(ses);
            req['cookies'] = null;
            expect(qacServices.setSession(req)).to.eql(ses);
            req['cookies'] = {};
            expect(qacServices.setSession(req)).to.eql(ses);
            var cKey = 'connect.sid';
            req['cookies'][cKey] = null;
            expect(qacServices.setSession(req)).to.eql(ses);
            var cVal = 'un-sid';
            req['cookies'][cKey] = cVal;
            expect(qacServices.setSession(req)).to.eql(ses);
            req['session'] = {};
            expect(qacServices.setSession(req)).to.eql(ses);
            req['session']['passport'] = {}
            expect(qacServices.setSession(req)).to.eql(ses);
            req['session']['passport']['user'] = null;
            expect(qacServices.setSession(req)).to.eql(ses);
            var cUser = 'un-user';
            req['session']['passport']['user'] = cUser;
            ses[cVal] = cUser;
            expect(qacServices.setSession(req)).to.eql(ses);

            qacServices.users = qacServices.setSession(req);
            expect(qacServices.users).to.eql(ses);
            cVal = 'otro-sid';
            cUser = 'otro-user';
            ses[cVal] = cUser;
            req['session']['passport']['user'] = cUser;
            req['cookies'][cKey] = cVal;
            qacServices.users = qacServices.setSession(req);
            expect(qacServices.users).to.eql(ses);

            qacServices.users = null; // reseteo
            done();
        });
        it('test (fake session)', function(done) {
            expect(qacServices.setSession(helper.session.req)).to.eql(helper.session.users);
            done();
        });
        it('validSession', function(done) {
            qacServices.users = qacServices.setSession(helper.session.req);
            expect(qacServices.users).to.eql(helper.session.users);
            expect(qacServices.validSession(null)).to.eql(null);
            var req = {};
            expect(qacServices.validSession(req)).to.eql(null);
            req['cookies']={'connect.sid':''};
            expect(qacServices.validSession(req)).to.not.be.ok();
            req['cookies']={'connect.sid':'wrong-user'};
            expect(qacServices.validSession(req)).to.not.be.ok();
            req['cookies']={'connect.sid':'fake-sid'};
            expect(qacServices.validSession(req)).to.be.ok();
            qacServices.users = null; // reseteo
            done();
        });
    });
});
<|endoftext|>


<commit_before>/**
 * Interact with local and remote project repos using Git.
 */

"use strict";

var git = require("nodegit");
var path = require("path");
var url = require("url");
var _ = require('underscore');
var Q = require('q');
var fs = require("q-io/fs"); // https://github.com/kriskowal/q-io

var appConfig = require('../../configuration').get();

// Mac OSX certificate issue http://www.nodegit.org/guides/cloning/
var copingWithMacCertBug = {
  certificateCheck: function () {
    return 1;
  }
};

/**
 * Parse the tag and branch names out of the refs list
 * and generate an object of data to return.
 */
function parseTagsAndBranches(refs, projectRef) {
  return refs
    .map(function (ref) {
      var shortName = ref.shorthand();
      var safeName = encodeURIComponent(ref.name());
      return {
        name: shortName,
        tag: ref.isTag(),
        branch: ref.isBranch(),
        urlEncodedName: safeName,
        current: ref.name() === projectRef.name()
      }
    });
}

// Wrap up the supplied repository metadata in an object.
// TODO: this model should not be generated here.
function generateRepoMetaData(projectData, sha, tagsAndBranches, currentBranchName, files, remoteUrl) {
  var updatedData = {
    // Copied
    repoName: projectData.repoName,
    localPath: projectData.localPath,
    projectLink: projectData.projectLink,
    // New
    commit: sha,
    shortCommit: sha.substring(0, 7),
    tagsAndBranches: tagsAndBranches,
    currentBranchName: currentBranchName,
    currentBranchNameShort: currentBranchName,
    featureFilePaths: files,
    repoUrl: remoteUrl,
  };

  // Filter falsey values and empty arrays.
  function findFalsey(data) {
    return function (key) {
      var value = data[key];
      return !data[key] || (value.length !== undefined ? value.length === 0 : false);
    }
  }

  var missingValues = Object.keys(updatedData).filter(findFalsey(updatedData));
  if (missingValues.length) {
    console.warn("Missing values:");
    console.warn(missingValues);
  }

  return updatedData;
}

/**
 * Clone the project.
 *
 * @return a promise for the repo metadata.
 */
function clone(projectData, cloneOptions) {
  var repository;
  if (!projectData.repoUrl) {
    throw new TypeError('Clone called without a repo URL.');
  }

  return git.Clone(projectData.repoUrl, projectData.localPath, cloneOptions)
    .then(function (repo) {
      repository = repo;
      return repository.getCurrentBranch();
    })
    .then(function (branch) {
      return getProjectData(projectData, branch.shorthand());
    });
}

/**
 * Perform a fetch on the project.
 *
 * @return a promise for the repo metadata.
 */
function update(projectData) {
  var repository;

  return git.Repository.openBare(projectData.localPath)
    .then(function (repo) {
      repository = repo;
      return repository.fetchAll(copingWithMacCertBug, true);
    })
    .then(function () {
      return getProjectData(projectData, projectData.currentBranchName);
    });
}

/**
 * Get or update the project repo using Git.
 *
 * @return a promise for the repo metadata.
 */
function getProject(projectData) {
  return fs.exists(projectData.localPath)
    .then(function (pathExists) {

      // Need to define this here as the Clone function modifies the passed object (face palm).
      var cloneOptions = {};
      cloneOptions.bare = 1;
      cloneOptions.remoteCallbacks = copingWithMacCertBug;

      if(appConfig.allowInsecureSSL) {
        console.log("Will ignore SSL errors!");
        cloneOptions.fetchOpts = {
          callbacks: copingWithMacCertBug
        };
      }

      /**
       * If there is no matching directory then clone the repo
       * else perform a pull on it.
       */
      if (!pathExists) {
        return clone(projectData, cloneOptions);
      } else {
        return update(projectData);
      }
    });
};

function getBranch(projectData, branchName) {
  return git.Repository.open(projectData.localPath)
    .then(function (repo) {
      if (branchName) {
        return repo.getBranch(branchName);
      }
      return repo.getCurrentBranch();
    });
}

function getProjectData(projectData, targetBranchName) {
  // The targetBranchName is the full remote branch ref.
  // The shortBranchName is what the local branch would be called.
  var currentRef;
  var shortBranchName;

  var repository;
  var remoteUrl;
  var headCommit;
  var listOfFiles;

  return getBranch(projectData, targetBranchName)
    .then(function (ref) {
      currentRef = ref;
      shortBranchName = currentRef.shorthand()
      return git.Repository.open(projectData.localPath)
    })
    .then(function (repo) {
      repository = repo;
      return repository.getRemote('origin');
    }).then(function (remote) {
      remoteUrl = remote.url();
      return repository.getReferenceCommit(currentRef.name());
    })
    .then(function (commit) {
      headCommit = commit.sha();
      return commit.getTree();
    })
    .then(getAllFiles)
    .then(function (files) {
      listOfFiles = files.map(function (fileOfInterestName) {
        return {
          ref: currentRef.name(),
          featureName: fileOfInterestName,
          featureNameShort: fileOfInterestName.replace(/\.feature$/, '')
        }
      });
      return repository.getReferences(git.Reference.TYPE.OID);
    })
    .then(function (refs) {
      var tagsAndBranches = parseTagsAndBranches(refs, currentRef);
      return generateRepoMetaData(projectData, headCommit, tagsAndBranches, currentRef.name(), listOfFiles, remoteUrl);
    });
}

function getFileContents(projectData, filePath) {
  var repository;

  return git.Repository.open(projectData.localPath)
    .then(function (repo) {
      repository = repo;
      return repository.getReferenceCommit(projectData.currentBranchName);
    })
    .then(function (commit) {
      return commit.getTree()
    })
    .then(function (tree) {
      return tree.getEntry(filePath)
    })
    .then(function (entry) {
      return entry.getBlob();
    })
    .then(function (blob) {
      return blob.toString();
    });
}

function _getAllFiles(tree) {
  var files = [];

  tree.entries().forEach(function (e) {
    if (e.isFile())
      files.push(e.path());

    if (e.isTree())
      files.push(e.getTree().then(function (t) {
        return _getAllFiles(t);
      }));
  });

  return Q.all(files)
    .then(function (files) {
      return _.flatten(files);
    });
}

function getAllFiles(tree) {
  return _getAllFiles(tree)
    .then(function (files) {
      return files.filter(function (f) {
        return /\.(feature|md)/.test(f);
      });
    });
}

module.exports = {
  getProject: getProject,
  getProjectData: getProjectData,
  getFileContents: getFileContents
};
<commit_msg>Rename copingWithMacBug to ignoreSSLErrors as it can now be used generally. Add notes on Mac specific SSL hack.<commit_after>/**
 * Interact with local and remote project repos using Git.
 */

"use strict";

var git = require("nodegit");
var path = require("path");
var url = require("url");
var _ = require('underscore');
var Q = require('q');
var fs = require("q-io/fs"); // https://github.com/kriskowal/q-io

var appConfig = require('../../configuration').get();

var ignoreSSLErrors = {
  certificateCheck: function () {
    return 1;
  }
};

/**
 * Parse the tag and branch names out of the refs list
 * and generate an object of data to return.
 */
function parseTagsAndBranches(refs, projectRef) {
  return refs
    .map(function (ref) {
      var shortName = ref.shorthand();
      var safeName = encodeURIComponent(ref.name());
      return {
        name: shortName,
        tag: ref.isTag(),
        branch: ref.isBranch(),
        urlEncodedName: safeName,
        current: ref.name() === projectRef.name()
      }
    });
}

// Wrap up the supplied repository metadata in an object.
// TODO: this model should not be generated here.
function generateRepoMetaData(projectData, sha, tagsAndBranches, currentBranchName, files, remoteUrl) {
  var updatedData = {
    // Copied
    repoName: projectData.repoName,
    localPath: projectData.localPath,
    projectLink: projectData.projectLink,
    // New
    commit: sha,
    shortCommit: sha.substring(0, 7),
    tagsAndBranches: tagsAndBranches,
    currentBranchName: currentBranchName,
    currentBranchNameShort: currentBranchName,
    featureFilePaths: files,
    repoUrl: remoteUrl,
  };

  // Filter falsey values and empty arrays.
  function findFalsey(data) {
    return function (key) {
      var value = data[key];
      return !data[key] || (value.length !== undefined ? value.length === 0 : false);
    }
  }

  var missingValues = Object.keys(updatedData).filter(findFalsey(updatedData));
  if (missingValues.length) {
    console.warn("Missing values:");
    console.warn(missingValues);
  }

  return updatedData;
}

/**
 * Clone the project.
 *
 * @return a promise for the repo metadata.
 */
function clone(projectData, cloneOptions) {
  var repository;
  if (!projectData.repoUrl) {
    throw new TypeError('Clone called without a repo URL.');
  }

  return git.Clone(projectData.repoUrl, projectData.localPath, cloneOptions)
    .then(function (repo) {
      repository = repo;
      return repository.getCurrentBranch();
    })
    .then(function (branch) {
      return getProjectData(projectData, branch.shorthand());
    });
}

/**
 * Perform a fetch on the project.
 *
 * @return a promise for the repo metadata.
 */
function update(projectData) {
  var repository;

  return git.Repository.openBare(projectData.localPath)
    .then(function (repo) {
      repository = repo;
      return repository.fetchAll(ignoreSSLErrors, true);
    })
    .then(function () {
      return getProjectData(projectData, projectData.currentBranchName);
    });
}

/**
 * Get or update the project repo using Git.
 *
 * @return a promise for the repo metadata.
 */
function getProject(projectData) {
  return fs.exists(projectData.localPath)
    .then(function (pathExists) {

      // Need to define this here as the Clone function modifies the passed object (face palm).
      var cloneOptions = {};
      cloneOptions.bare = 1;

      // Mac OSX certificate issue http://www.nodegit.org/guides/cloning/
      // This is now an undocumented Mac only part of the API.
      cloneOptions.remoteCallbacks = ignoreSSLErrors;

      // General option to ingore SSL errors.
      if(appConfig.allowInsecureSSL) {
        console.log("Will ignore SSL errors!");
        cloneOptions.fetchOpts = {
          callbacks: ignoreSSLErrors
        };
      }

      /**
       * If there is no matching directory then clone the repo
       * else perform a pull on it.
       */
      if (!pathExists) {
        return clone(projectData, cloneOptions);
      } else {
        return update(projectData);
      }
    });
};

function getBranch(projectData, branchName) {
  return git.Repository.open(projectData.localPath)
    .then(function (repo) {
      if (branchName) {
        return repo.getBranch(branchName);
      }
      return repo.getCurrentBranch();
    });
}

function getProjectData(projectData, targetBranchName) {
  // The targetBranchName is the full remote branch ref.
  // The shortBranchName is what the local branch would be called.
  var currentRef;
  var shortBranchName;

  var repository;
  var remoteUrl;
  var headCommit;
  var listOfFiles;

  return getBranch(projectData, targetBranchName)
    .then(function (ref) {
      currentRef = ref;
      shortBranchName = currentRef.shorthand()
      return git.Repository.open(projectData.localPath)
    })
    .then(function (repo) {
      repository = repo;
      return repository.getRemote('origin');
    }).then(function (remote) {
      remoteUrl = remote.url();
      return repository.getReferenceCommit(currentRef.name());
    })
    .then(function (commit) {
      headCommit = commit.sha();
      return commit.getTree();
    })
    .then(getAllFiles)
    .then(function (files) {
      listOfFiles = files.map(function (fileOfInterestName) {
        return {
          ref: currentRef.name(),
          featureName: fileOfInterestName,
          featureNameShort: fileOfInterestName.replace(/\.feature$/, '')
        }
      });
      return repository.getReferences(git.Reference.TYPE.OID);
    })
    .then(function (refs) {
      var tagsAndBranches = parseTagsAndBranches(refs, currentRef);
      return generateRepoMetaData(projectData, headCommit, tagsAndBranches, currentRef.name(), listOfFiles, remoteUrl);
    });
}

function getFileContents(projectData, filePath) {
  var repository;

  return git.Repository.open(projectData.localPath)
    .then(function (repo) {
      repository = repo;
      return repository.getReferenceCommit(projectData.currentBranchName);
    })
    .then(function (commit) {
      return commit.getTree()
    })
    .then(function (tree) {
      return tree.getEntry(filePath)
    })
    .then(function (entry) {
      return entry.getBlob();
    })
    .then(function (blob) {
      return blob.toString();
    });
}

function _getAllFiles(tree) {
  var files = [];

  tree.entries().forEach(function (e) {
    if (e.isFile())
      files.push(e.path());

    if (e.isTree())
      files.push(e.getTree().then(function (t) {
        return _getAllFiles(t);
      }));
  });

  return Q.all(files)
    .then(function (files) {
      return _.flatten(files);
    });
}

function getAllFiles(tree) {
  return _getAllFiles(tree)
    .then(function (files) {
      return files.filter(function (f) {
        return /\.(feature|md)/.test(f);
      });
    });
}

module.exports = {
  getProject: getProject,
  getProjectData: getProjectData,
  getFileContents: getFileContents
};
<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;

describe('node generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('node-gulp:app', [
        '../../app'
      ]);
      this.app.options['skip-install'] = true;
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['lib/mymodule.js', /https:\/\/github.com\/octocat\/mymodule/],
      ['package.json', /"name": "mymodule"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('creates expected files', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['lib/mymodule.js', /http:\/\/example.com/],
      ['package.json', /"name": "mymodule"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'homepage': 'http://example.com',
      'modules': [],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with releaseModule', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['package.json', /"gulp-bump"/],
      ['package.json', /"name": "mymodule"/],
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['releaseModule'],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with jscsModule', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.jscs.json',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['package.json', /"name": "mymodule"/],
      ['package.json', /"gulp-jscs"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['jscsModule'],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with package lodash', function (done) {
    var expectedContent = [
      ['package.json', /"lodash"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': ['lodash']
    });

    this.app.run({}, function () {
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with package q', function (done) {
    var expectedContent = [
      ['package.json', /"q"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': ['q']
    });

    this.app.run({}, function () {
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with package lodash and q', function (done) {
    var expectedContent = [
      ['package.json', /"lodash"/],
      ['package.json', /"q"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': ['lodash', 'q']
    });

    this.app.run({}, function () {
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with istanbul', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['.gitignore', /^(?!coverage\/)/],
      ['gulpfile.js', /var istanbul = require\('gulp-istanbul'\)/],
      ['gulpfile.js', /gulp.task\('istanbul'/],
      ['gulpfile.js', /gulp.task\('test', \['lint', 'istanbul'\]\);/],
      ['package.json', /"name": "mymodule"/, /"istanbul"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['istanbulModule'],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with istanbul and coveralls', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'README.md',
      'package.json'
    ];
    var expectedContent = [
      ['.travis.yml', /npm run coveralls/],
      ['.gitignore', /coverage\//],
      ['gulpfile.js', /var istanbul = require\('gulp-istanbul'\)/],
      ['gulpfile.js', /gulp.task\('istanbul'/],
      ['gulpfile.js', /gulp.task\('test', \['lint', 'istanbul'\]\);/],
      ['package.json', /"name": "mymodule"/],
      ['package.json', /"gulp-istanbul"/],
      ['package.json', /"coveralls": "gulp test/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['istanbulModule'],
      'coverallsModule': true,
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

});
<commit_msg>fix tests<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;

describe('node generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('node-gulp:app', [
        '../../app'
      ]);
      this.app.options['skip-install'] = true;
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['lib/mymodule.js', /https:\/\/github.com\/octocat\/mymodule/],
      ['package.json', /"name": "mymodule"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('creates expected files', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['lib/mymodule.js', /http:\/\/example.com/],
      ['package.json', /"name": "mymodule"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'homepage': 'http://example.com',
      'modules': [],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with releaseModule', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['package.json', /"gulp-bump"/],
      ['package.json', /"name": "mymodule"/],
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['releaseModule'],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with jscsModule', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.jscs.json',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['package.json', /"name": "mymodule"/],
      ['package.json', /"gulp-jscs"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['jscsModule'],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with package lodash', function (done) {
    var expectedContent = [
      ['package.json', /"lodash"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': ['lodash']
    });

    this.app.run({}, function () {
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with package q', function (done) {
    var expectedContent = [
      ['package.json', /"q"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': ['q']
    });

    this.app.run({}, function () {
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with package lodash and q', function (done) {
    var expectedContent = [
      ['package.json', /"lodash"/],
      ['package.json', /"q"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': [],
      'dependencies': ['lodash', 'q']
    });

    this.app.run({}, function () {
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with istanbul', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'package.json',
      'README.md'
    ];

    var expectedContent = [
      ['.gitignore', /^(?!coverage\/)/],
      ['gulpfile.js', /gulp.task\('istanbul'/],
      ['gulpfile.js', /gulp.task\('test', \['lint', 'istanbul'\]\);/],
      ['package.json', /"name": "mymodule"/, /"istanbul"/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['istanbulModule'],
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('generator with istanbul and coveralls', function (done) {
    var expectedFiles = [
      'lib/mymodule.js',
      'test/mymodule_test.js',
      'example/simple.js',
      '.gitignore',
      '.jshintrc',
      '.travis.yml',
      '.editorconfig',
      'gulpfile.js',
      'README.md',
      'package.json'
    ];
    var expectedContent = [
      ['.travis.yml', /npm run coveralls/],
      ['.gitignore', /coverage\//],
      ['gulpfile.js', /gulp.task\('istanbul'/],
      ['gulpfile.js', /gulp.task\('test', \['lint', 'istanbul'\]\);/],
      ['package.json', /"name": "mymodule"/],
      ['package.json', /"gulp-istanbul"/],
      ['package.json', /"coveralls": "gulp test/]
    ];

    helpers.mockPrompt(this.app, {
      'name': 'mymodule',
      'description': 'awesome module',
      'license': 'MIT',
      'githubUsername': 'octocat',
      'authorName': 'Octo Cat',
      'authorEmail': 'octo@example.com',
      'modules': ['istanbulModule'],
      'coverallsModule': true,
      'dependencies': []
    });

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

});
<|endoftext|>


<commit_before>var run = require('./run.js');
var bodec = require('bodec');

var repo = {};
require('../mixins/mem-db.js')(repo);

var pack = require('./sample-pack.js');
var hashes;

run([
  function setup() {
    require('../mixins/pack-ops.js')(repo);
  },
  function testUnpack(end) {
    repo.unpack(singleStream(pack), {
      onProgress: onProgress
    }, function (err, result) {
      if (err) return end(err);
      hashes = result;
      end();
    });
    function onProgress(progress) {
      // console.log(progress);
    }
  },
  function testPack(end) {
    var stream;
    var parts = [];
    repo.pack(hashes, {}, function (err, result) {
      if (err) return end(err);
      stream = result;
      stream.read(onRead);
    });
    function onRead(err, chunk) {
      if (err) return end(err);
      // console.log(chunk);
      if (chunk) {
        parts.push(chunk);
        return stream.read(onRead);
      }

      end();
    }

  }
]);

function singleStream(item) {
  var done = false;
  return { read: function (callback) {
    if (done) return callback();
    done = true;
    callback(null, item);
  }};

}<commit_msg>Clean up packops test<commit_after>var run = require('./run.js');

var repo = {};
require('../mixins/mem-db.js')(repo);

var pack = require('./sample-pack.js');
var hashes;

run([
  function setup() {
    require('../mixins/pack-ops.js')(repo);
  },
  function testUnpack(end) {
    repo.unpack(singleStream(pack), {
      onProgress: onProgress
    }, function (err, result) {
      if (err) return end(err);
      hashes = result;
      if (hashes.length !== 16) {
        return end(new Error("Wrong number of objects unpacked"));
      }
      end();
    });
    function onProgress(progress) {
      // console.log(progress);
    }
  },
  function testPack(end) {
    var stream;
    var parts = [];
    repo.pack(hashes, {}, function (err, result) {
      if (err) return end(err);
      stream = result;
      stream.read(onRead);
    });
    function onRead(err, chunk) {
      if (err) return end(err);
      // console.log(chunk);
      if (chunk) {
        parts.push(chunk);
        return stream.read(onRead);
      }
      end();
    }
  }
]);

function singleStream(item) {
  var done = false;
  return { read: function (callback) {
    if (done) return callback();
    done = true;
    callback(null, item);
  }};
}<|endoftext|>