<commit_before>const chalk = require('chalk');
const path = require('path');
const http = require('http');
const url = require('url');
const fs = require('fs');

const TESTPAGE_URL_BASE = 'file://' + path.resolve(__dirname, 'testpage.html').replace('\\', '/');

const createFetchTargetServer = () => {
  const server = http.createServer((req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    const queryParams = url.parse(req.url, true).query;
    const sleepMillis = queryParams.sleepMillis;
    setTimeout(() => {
      res.writeHead(200);
      res.end();
    }, sleepMillis);
  }).listen(0);
  const boundListenPort = server.address().port;
  return { server, port: boundListenPort, baseUrl: `http://127.0.0.1:${boundListenPort}` };
};

const runBasicTests = (testSuiteTitle, TESTPAGE_URL) => {
  describe(testSuiteTitle, () => {

    it('check version', () => {
      browser.url(TESTPAGE_URL);
      const browserData = browser.executeAsync(async (done) => {
        done(window.DetectedBrowserData);
      });
      console.log('Tests running on: ' + JSON.stringify(browserData, null, 2));
    });

    it('Request object has .signal', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        const controller = new AbortController();
        const signal = controller.signal;
        const request = new Request('/', {signal});
        if (!request.signal) {
          done('FAIL: missing request.signal');
        }
        if (!Request.prototype.isPrototypeOf(request)) {
          done('FAIL: wrong prototype');
        }
        done('PASS');
      });
      expect(result).toBe('PASS');
    });

    it('abort during fetch', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        const signal = controller.signal;
        setTimeout(() => {
          controller.abort();
        }, 500);
        try {
          await fetch(`${baseUrl}?sleepMillis=1000`, {signal});
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('abort during fetch when Request has signal', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        const signal = controller.signal;
        setTimeout(() => {
          controller.abort();
        }, 500);
        try {
          let request = new Request(`${baseUrl}?sleepMillis=1000`, {signal});
          await fetch(request);
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('abort before fetch started', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        controller.abort();
        const signal = controller.signal;
        try {
          await fetch(`${baseUrl}?sleepMillis=1000`, {signal});
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('abort before fetch started, verify no HTTP request is made', () => {
      const server = http.createServer((req, res) => {
        fail('fetch() made an HTTP request despite pre-aborted signal');
      }).listen(0);
      const boundListenPort = server.address().port;
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (boundListenPort, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        controller.abort();
        const signal = controller.signal;
        try {
          await fetch(`http://127.0.0.1:${boundListenPort}`, {signal});
          done({name: 'fail'});
        } catch (err) {
          done(err);
        }
      }, boundListenPort);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('fetch without aborting', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        const signal = controller.signal;
        try {
          await fetch(`${baseUrl}?sleepMillis=50`, {signal});
          done('PASS');
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(result).toBe('PASS');
      server.close();
    });

    it('fetch without signal set', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        try {
          await fetch(`${baseUrl}?sleepMillis=50`);
          done('PASS');
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(result).toBe('PASS');
      server.close();
    });

    it('event listener fires "abort" event', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        controller.signal.addEventListener('abort', () => {
          done('PASS');
        });
        controller.abort();
      });
      expect(result).toBe('PASS');
    });

    it('signal.aborted is true after abort', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('FAIL');
        }, 2000);
        const controller = new AbortController();
        controller.signal.addEventListener('abort', () => {
          if (controller.signal.aborted === true) {
            done('PASS');
          } else {
            done('FAIL');
          }
        });
        controller.abort();
        if (controller.signal.aborted !== true) {
          done('FAIL');
        }
      });
      expect(result).toBe('PASS');
    });

    it('event listener doesn\'t fire "abort" event after removeEventListener', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('PASS');
        }, 200);
        const controller = new AbortController();
        const handlerFunc = () => {
          done('FAIL');
        };
        controller.signal.addEventListener('abort', handlerFunc);
        controller.signal.removeEventListener('abort', handlerFunc);
        controller.abort();
      });
      expect(result).toBe('PASS');
    });

    it('signal.onabort called on abort', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('FAIL');
        }, 200);
        const controller = new AbortController();
        controller.signal.onabort = () => {
          done('PASS');
        };
        controller.abort();
      });
      expect(result).toBe('PASS');
    });

    it('fetch from web worker works', () => {
      // Need to load from webserver because worker because security policy
      // prevents file:// pages from "loading arbitrary .js files" as workers.
      const server = http.createServer((req, res) => {
        if (req.url === '/') {
          // No need to load polyfill in main JS context, we're only gonna run it
          // inside the worker only
          res.end('');
        } else if (req.url === '/umd-polyfill.js') {
          res.setHeader('Content-Type', 'text/javascript');
          res.end(fs.readFileSync(path.join(__dirname, '../dist/umd-polyfill.js')));
        } else if (req.url === '/web-worker.js') {
          res.setHeader('Content-Type', 'text/javascript');
          res.end(fs.readFileSync(path.join(__dirname, 'web-worker.js')));
        }
      }).listen(0);
      const boundListenPort = server.address().port;

      browser.url(`http://127.0.0.1:${boundListenPort}`);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('FAIL');
        }, 2000);
        const worker = new Worker('web-worker.js');
        worker.postMessage('run-test');
        worker.onmessage = (ev) => {
          done(ev.data);
        };
      });
      expect(result).toBe('PASS');
      server.close();
    });

    it('toString() output', () => {
      browser.url(TESTPAGE_URL);

      let result;

      result = browser.executeAsync((done) => {
        done(new AbortController().toString());
      });
      expect(result).toBe('[object AbortController]');

      result = browser.executeAsync((done) => {
        done(Object.prototype.toString.call(new AbortController()));
      });
      expect(result).toBe('[object AbortController]');

      result = browser.executeAsync((done) => {
        done(new AbortController().signal.toString());
      });
      expect(result).toBe('[object AbortSignal]');
    });
  });
};

// Run all testcases with abortcontroller-polyfill force installed (even browser has native AbortController)
runBasicTests(
  'basic tests with abortcontroller-polyfill force installed',
  `${TESTPAGE_URL_BASE}?__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=1`
);

// Run all testcases again with normal installation logic for abortcontroller-polyfill (on modern browsers
// this will run the testcases against the native AbortController implementation, and on older browsers
// this will verify that the polyfill chooses to install itself when it is needed)
runBasicTests(
  'basic tests again with normal installation logic for abortcontroller-polyfill',
  TESTPAGE_URL_BASE
);

afterEach(() => {
  checkJSErrors();
});

let hasPrintErrorOnceAlready = false;
function checkJSErrors() {
  let browserLog = [];
  if (browser.capabilities.browserName === 'firefox') {
    if (!hasPrintErrorOnceAlready) {
      console.log('NOTE: cannot get browser log in firefox so cannot verify that "no JS errors" fired during testing');
      hasPrintErrorOnceAlready = true;
    }
  } else {
    browser.call(() => browser.getLogs('browser').then(log => {
      browserLog = log;
      browserLog.forEach(error => {
        if (error.level === 'SEVERE') {
          console.log(chalk.red(`[${error.level}] ${error.message}`));
        } else {
          console.log(`[${error.level}] ${error.message}`);
        }
      });
    }));
  }
  return browserLog;
}
<commit_msg>Add testcase where two fetches are using the same abort signal<commit_after>const chalk = require('chalk');
const path = require('path');
const http = require('http');
const url = require('url');
const fs = require('fs');

const TESTPAGE_URL_BASE = 'file://' + path.resolve(__dirname, 'testpage.html').replace('\\', '/');

const createFetchTargetServer = () => {
  const server = http.createServer((req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    const queryParams = url.parse(req.url, true).query;
    const sleepMillis = queryParams.sleepMillis;
    setTimeout(() => {
      res.writeHead(200);
      res.end();
    }, sleepMillis);
  }).listen(0);
  const boundListenPort = server.address().port;
  return { server, port: boundListenPort, baseUrl: `http://127.0.0.1:${boundListenPort}` };
};

const runBasicTests = (testSuiteTitle, TESTPAGE_URL) => {
  describe(testSuiteTitle, () => {

    it('check version', () => {
      browser.url(TESTPAGE_URL);
      const browserData = browser.executeAsync(async (done) => {
        done(window.DetectedBrowserData);
      });
      console.log('Tests running on: ' + JSON.stringify(browserData, null, 2));
    });

    it('Request object has .signal', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        const controller = new AbortController();
        const signal = controller.signal;
        const request = new Request('/', {signal});
        if (!request.signal) {
          done('FAIL: missing request.signal');
        }
        if (!Request.prototype.isPrototypeOf(request)) {
          done('FAIL: wrong prototype');
        }
        done('PASS');
      });
      expect(result).toBe('PASS');
    });

    it('abort during fetch', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        const signal = controller.signal;
        setTimeout(() => {
          controller.abort();
        }, 500);
        try {
          await fetch(`${baseUrl}?sleepMillis=1000`, {signal});
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('abort when multiple fetches are using the same signal', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const errors = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        const signal = controller.signal;
        setTimeout(() => {
          controller.abort();
        }, 500);
        const requests = [
          fetch(`${baseUrl}?sleepMillis=900`, {signal}),
          fetch(`${baseUrl}?sleepMillis=1100`, {signal})
        ];
        const errors = [];
        for (let req of requests) {
          try {
            await req;
            errors.push({name: 'fail'});
          } catch (err) {
            errors.push(err);
          }
        }
        done(errors);
      }, baseUrl);
      expect(errors[0].name).toBe('AbortError');
      expect(errors[1].name).toBe('AbortError');
      server.close();
    });

    it('abort during fetch when Request has signal', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        const signal = controller.signal;
        setTimeout(() => {
          controller.abort();
        }, 500);
        try {
          let request = new Request(`${baseUrl}?sleepMillis=1000`, {signal});
          await fetch(request);
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('abort before fetch started', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        controller.abort();
        const signal = controller.signal;
        try {
          await fetch(`${baseUrl}?sleepMillis=1000`, {signal});
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('abort before fetch started, verify no HTTP request is made', () => {
      const server = http.createServer((req, res) => {
        fail('fetch() made an HTTP request despite pre-aborted signal');
      }).listen(0);
      const boundListenPort = server.address().port;
      browser.url(TESTPAGE_URL);
      const err = browser.executeAsync(async (boundListenPort, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        controller.abort();
        const signal = controller.signal;
        try {
          await fetch(`http://127.0.0.1:${boundListenPort}`, {signal});
          done({name: 'fail'});
        } catch (err) {
          done(err);
        }
      }, boundListenPort);
      expect(err.name).toBe('AbortError');
      server.close();
    });

    it('fetch without aborting', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        const signal = controller.signal;
        try {
          await fetch(`${baseUrl}?sleepMillis=50`, {signal});
          done('PASS');
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(result).toBe('PASS');
      server.close();
    });

    it('fetch without signal set', () => {
      const { server, baseUrl } = createFetchTargetServer();
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (baseUrl, done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        try {
          await fetch(`${baseUrl}?sleepMillis=50`);
          done('PASS');
        } catch (err) {
          done(err);
        }
      }, baseUrl);
      expect(result).toBe('PASS');
      server.close();
    });

    it('event listener fires "abort" event', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done({name: 'fail'});
        }, 2000);
        const controller = new AbortController();
        controller.signal.addEventListener('abort', () => {
          done('PASS');
        });
        controller.abort();
      });
      expect(result).toBe('PASS');
    });

    it('signal.aborted is true after abort', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('FAIL');
        }, 2000);
        const controller = new AbortController();
        controller.signal.addEventListener('abort', () => {
          if (controller.signal.aborted === true) {
            done('PASS');
          } else {
            done('FAIL');
          }
        });
        controller.abort();
        if (controller.signal.aborted !== true) {
          done('FAIL');
        }
      });
      expect(result).toBe('PASS');
    });

    it('event listener doesn\'t fire "abort" event after removeEventListener', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('PASS');
        }, 200);
        const controller = new AbortController();
        const handlerFunc = () => {
          done('FAIL');
        };
        controller.signal.addEventListener('abort', handlerFunc);
        controller.signal.removeEventListener('abort', handlerFunc);
        controller.abort();
      });
      expect(result).toBe('PASS');
    });

    it('signal.onabort called on abort', () => {
      browser.url(TESTPAGE_URL);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('FAIL');
        }, 200);
        const controller = new AbortController();
        controller.signal.onabort = () => {
          done('PASS');
        };
        controller.abort();
      });
      expect(result).toBe('PASS');
    });

    it('fetch from web worker works', () => {
      // Need to load from webserver because worker because security policy
      // prevents file:// pages from "loading arbitrary .js files" as workers.
      const server = http.createServer((req, res) => {
        if (req.url === '/') {
          // No need to load polyfill in main JS context, we're only gonna run it
          // inside the worker only
          res.end('');
        } else if (req.url === '/umd-polyfill.js') {
          res.setHeader('Content-Type', 'text/javascript');
          res.end(fs.readFileSync(path.join(__dirname, '../dist/umd-polyfill.js')));
        } else if (req.url === '/web-worker.js') {
          res.setHeader('Content-Type', 'text/javascript');
          res.end(fs.readFileSync(path.join(__dirname, 'web-worker.js')));
        }
      }).listen(0);
      const boundListenPort = server.address().port;

      browser.url(`http://127.0.0.1:${boundListenPort}`);
      const result = browser.executeAsync(async (done) => {
        setTimeout(() => {
          done('FAIL');
        }, 2000);
        const worker = new Worker('web-worker.js');
        worker.postMessage('run-test');
        worker.onmessage = (ev) => {
          done(ev.data);
        };
      });
      expect(result).toBe('PASS');
      server.close();
    });

    it('toString() output', () => {
      browser.url(TESTPAGE_URL);

      let result;

      result = browser.executeAsync((done) => {
        done(new AbortController().toString());
      });
      expect(result).toBe('[object AbortController]');

      result = browser.executeAsync((done) => {
        done(Object.prototype.toString.call(new AbortController()));
      });
      expect(result).toBe('[object AbortController]');

      result = browser.executeAsync((done) => {
        done(new AbortController().signal.toString());
      });
      expect(result).toBe('[object AbortSignal]');
    });
  });
};

// Run all testcases with abortcontroller-polyfill force installed (even browser has native AbortController)
runBasicTests(
  'basic tests with abortcontroller-polyfill force installed',
  `${TESTPAGE_URL_BASE}?__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=1`
);

// Run all testcases again with normal installation logic for abortcontroller-polyfill (on modern browsers
// this will run the testcases against the native AbortController implementation, and on older browsers
// this will verify that the polyfill chooses to install itself when it is needed)
runBasicTests(
  'basic tests again with normal installation logic for abortcontroller-polyfill',
  TESTPAGE_URL_BASE
);

afterEach(() => {
  checkJSErrors();
});

let hasPrintErrorOnceAlready = false;
function checkJSErrors() {
  let browserLog = [];
  if (browser.capabilities.browserName === 'firefox') {
    if (!hasPrintErrorOnceAlready) {
      console.log('NOTE: cannot get browser log in firefox so cannot verify that "no JS errors" fired during testing');
      hasPrintErrorOnceAlready = true;
    }
  } else {
    browser.call(() => browser.getLogs('browser').then(log => {
      browserLog = log;
      browserLog.forEach(error => {
        if (error.level === 'SEVERE') {
          console.log(chalk.red(`[${error.level}] ${error.message}`));
        } else {
          console.log(`[${error.level}] ${error.message}`);
        }
      });
    }));
  }
  return browserLog;
}
<|endoftext|>


<commit_before><commit_msg>Create new Sonic object in Game engine.<commit_after><|endoftext|>


<commit_before>/**
 * @fileoverview Tests for the eslint.js executable.
 * @author Teddy Katz
 */

"use strict";

const childProcess = require("child_process");
const assert = require("chai").assert;
const EXECUTABLE_PATH = require("path").resolve(`${__dirname}/../../bin/eslint.js`);

/**
* Asserts that the exit code of a given child process will equal the given value.
* @param {ChildProcess} exitingProcess The child process
* @param {number} expectedExitCode The expected exit code of the child process
* @returns {Promise} A Promise that fufills if the exit code ends up matching, and rejects otherwise.
*/
function assertExitCode(exitingProcess, expectedExitCode) {
    return new Promise((resolve, reject) => {
        exitingProcess.once("exit", exitCode => {
            if (exitCode === expectedExitCode) {
                resolve();
            } else {
                reject(new Error(`Expected an exit code of ${expectedExitCode} but got ${exitCode}.`));
            }
        });
    });
}

/**
* Returns a Promise for the stdout of a process.
* @param {ChildProcess} runningProcess The child process
* @returns {Promise<string>} A Promise that fulfills with all of the stdout output produced by the process when it exits.
*/
function getStdout(runningProcess) {
    let stdout = "";

    runningProcess.stdout.on("data", data => {
        stdout += data;
    });

    return new Promise(resolve => {
        runningProcess.once("exit", () => resolve(stdout));
    });
}

describe("bin/eslint.js", () => {
    const forkedProcesses = new Set();

    /**
    * Forks the process to run an instance of ESLint.
    * @param {string[]} [args] An array of arguments
    * @param {Object} [options] An object containing options for the resulting child process
    * @returns {ChildProcess} The resulting child process
    */
    function runESLint(args, options) {
        const newProcess = childProcess.fork(EXECUTABLE_PATH, args, Object.assign({silent: true}, options));

        forkedProcesses.add(newProcess);
        return newProcess;
    }

    describe("reading from stdin", () => {
        it("has exit code 0 if no linting errors are reported", () => {
            const child = runESLint(["--stdin", "--no-eslintrc"]);

            child.stdin.write("var foo = bar;\n");
            child.stdin.end();
            return assertExitCode(child, 0);
        });

        it("has exit code 1 if a syntax error is thrown", () => {
            const child = runESLint(["--stdin", "--no-eslintrc"]);

            child.stdin.write("This is not valid JS syntax.\n");
            child.stdin.end();
            return assertExitCode(child, 1);
        });

        it("has exit code 1 if a linting error occurs", () => {
            const child = runESLint(["--stdin", "--no-eslintrc", "--rule", "semi:2"]);

            child.stdin.write("var foo = bar // <-- no semicolon\n");
            child.stdin.end();
            return assertExitCode(child, 1);
        });

        it("gives a detailed error message if no config file is found", () => {
            const child = runESLint(["--stdin"], {cwd: "/"}); // Assumes the root directory has no .eslintrc file

            const exitCodePromise = assertExitCode(child, 1);
            const stdoutPromise = getStdout(child).then(stdout => {
                assert.match(stdout, /ESLint couldn't find a configuration file/);
            });

            child.stdin.write("var foo = bar\n");
            child.stdin.end();

            return Promise.all([exitCodePromise, stdoutPromise]);
        });

    });

    afterEach(() => {

        // Clean up all the processes after every test.
        forkedProcesses.forEach(child => child.kill());
        forkedProcesses.clear();
    });

    // TODO (not-an-aardvark): Add tests for non-stdin functionality
});
<commit_msg>Chore: Add additional tests for bin/eslint.js (#7290)<commit_after>/**
 * @fileoverview Tests for the eslint.js executable.
 * @author Teddy Katz
 */

"use strict";

const childProcess = require("child_process");
const assert = require("chai").assert;
const EXECUTABLE_PATH = require("path").resolve(`${__dirname}/../../bin/eslint.js`);

/**
* Asserts that the exit code of a given child process will equal the given value.
* @param {ChildProcess} exitingProcess The child process
* @param {number} expectedExitCode The expected exit code of the child process
* @returns {Promise} A Promise that fufills if the exit code ends up matching, and rejects otherwise.
*/
function assertExitCode(exitingProcess, expectedExitCode) {
    return new Promise((resolve, reject) => {
        exitingProcess.once("exit", exitCode => {
            if (exitCode === expectedExitCode) {
                resolve();
            } else {
                reject(new Error(`Expected an exit code of ${expectedExitCode} but got ${exitCode}.`));
            }
        });
    });
}

/**
* Returns a Promise for the stdout of a process.
* @param {ChildProcess} runningProcess The child process
* @returns {Promise<string>} A Promise that fulfills with all of the stdout output produced by the process when it exits.
*/
function getStdout(runningProcess) {
    let stdout = "";

    runningProcess.stdout.on("data", data => {
        stdout += data;
    });

    return new Promise(resolve => {
        runningProcess.once("exit", () => resolve(stdout));
    });
}

describe("bin/eslint.js", () => {
    const forkedProcesses = new Set();

    /**
    * Forks the process to run an instance of ESLint.
    * @param {string[]} [args] An array of arguments
    * @param {Object} [options] An object containing options for the resulting child process
    * @returns {ChildProcess} The resulting child process
    */
    function runESLint(args, options) {
        const newProcess = childProcess.fork(EXECUTABLE_PATH, args, Object.assign({silent: true}, options));

        forkedProcesses.add(newProcess);
        return newProcess;
    }

    describe("reading from stdin", () => {
        it("has exit code 0 if no linting errors are reported", () => {
            const child = runESLint(["--stdin", "--no-eslintrc"]);

            child.stdin.write("var foo = bar;\n");
            child.stdin.end();
            return assertExitCode(child, 0);
        });

        it("has exit code 1 if a syntax error is thrown", () => {
            const child = runESLint(["--stdin", "--no-eslintrc"]);

            child.stdin.write("This is not valid JS syntax.\n");
            child.stdin.end();
            return assertExitCode(child, 1);
        });

        it("has exit code 1 if a linting error occurs", () => {
            const child = runESLint(["--stdin", "--no-eslintrc", "--rule", "semi:2"]);

            child.stdin.write("var foo = bar // <-- no semicolon\n");
            child.stdin.end();
            return assertExitCode(child, 1);
        });

        it("gives a detailed error message if no config file is found", () => {
            const child = runESLint(["--stdin"], {cwd: "/"}); // Assumes the root directory has no .eslintrc file

            const exitCodePromise = assertExitCode(child, 1);
            const stdoutPromise = getStdout(child).then(stdout => {
                assert.match(stdout, /ESLint couldn't find a configuration file/);
            });

            child.stdin.write("var foo = bar\n");
            child.stdin.end();

            return Promise.all([exitCodePromise, stdoutPromise]);
        });

    });

    describe("running on files", () => {
        it("has exit code 0 if no linting errors occur", () => assertExitCode(runESLint(["bin/eslint.js"]), 0));
        it("has exit code 0 if a linting warning is reported", () => assertExitCode(runESLint(["bin/eslint.js", "--env", "es6", "--no-eslintrc", "--rule", "semi: [1, never]"]), 0));
        it("has exit code 1 if a linting error is reported", () => assertExitCode(runESLint(["bin/eslint.js", "--env", "es6", "--no-eslintrc", "--rule", "semi: [2, never]"]), 1));
        it("has exit code 1 if a syntax error is thrown", () => assertExitCode(runESLint(["README.md"]), 1));
    });

    afterEach(() => {

        // Clean up all the processes after every test.
        forkedProcesses.forEach(child => child.kill());
        forkedProcesses.clear();
    });
});
<|endoftext|>


<commit_before>/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
import { observer } from "mobx-react";

import button from "mdlean/lib/button";
import wizard from "mdlean/lib/wizard";

import {
  providerSelection,
  providerSelectionCreateStore,
} from "./providerSelection";
import { awsFormCreate, createStoreAws } from "./awsConfig";
import { gcpFormCreate, createStoreGoogle } from "./gcpConfig";
import { azureFormCreate, createStoreAzure } from "./azureConfig";
import { ovhFormCreate, createStoreOvh } from "./ovhConfig";

import { repositoryConfig, repositoryCreateStore } from "./gitRepositoryConfig";
import {
  gitCredentialConfig,
  gitCredentialCreateStore,
} from "./gitCredentialConfig";
import { infraSettings, infraSettingsCreateStore } from "./infraSettings";

import {
  importProjectForm,
  importProjectCreateStore,
} from "./importProjectForm";

export const buttonWizardBack = (context) => {
  const Button = button(context);
  return () => (
    <Button onClick={() => context.emitter.emit("step.previous")}>
      {"\u25c0"} Back
    </Button>
  );
};

export const buttonHistoryBack = (context) => {
  const Button = button(context);
  return () => (
    <Button onClick={() => context.emitter.emit("step.previous")}>
      {"\u25c0"} Back
    </Button>
  );
};

export const wizardStoreCreate = (context) => {
  const providerSelectionStore = providerSelectionCreateStore({ context });

  const importProjectStore = importProjectCreateStore(context);

  const infraSettingsStore = infraSettingsCreateStore({
    context,
    providerSelectionStore,
    importProjectStore,
  });

  const gitCredentialStore = gitCredentialCreateStore({
    context,
    infraSettingsStore,
  });

  const gitRepositoryStore = repositoryCreateStore({
    context,
    infraSettingsStore,
    gitCredentialStore,
  });

  const aws = createStoreAws(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  const google = createStoreGoogle(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  const azure = createStoreAzure(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  const ovh = createStoreOvh(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  return {
    providerSelectionStore,
    importProjectStore,
    infraSettingsStore,
    gitCredentialStore,
    gitRepositoryStore,
    aws,
    azure,
    google,
    ovh,
  };
};

export const wizardCreate = ({ context, stores }) => {
  const { tr, emitter } = context;
  const ProviderSelection = providerSelection(context);
  const InfraSettings = infraSettings(context);
  const RepositoryConfig = repositoryConfig(context);
  const GitCredentialConfig = gitCredentialConfig(context);
  const ImportProjectForm = importProjectForm(context);

  const AwsFormCreate = awsFormCreate(context);
  const GcpFormCreate = gcpFormCreate(context);
  const AzureFormCreate = azureFormCreate(context);
  const OvhFormCreate = ovhFormCreate(context);

  const {
    providerSelectionStore,
    importProjectStore,
    infraSettingsStore,
    gitCredentialStore,
    gitRepositoryStore,
    aws,
    google,
    azure,
    ovh,
  } = stores.wizard;

  const configViewFromProvider = (providerName) => {
    switch (providerName) {
      case "aws":
        return <AwsFormCreate store={aws} />;
      case "google":
        return <GcpFormCreate store={google} />;
      case "azure":
        return <AzureFormCreate store={azure} />;
      case "ovh":
        return <OvhFormCreate store={ovh} />;
      default:
        throw Error(`invalid provider type`);
    }
  };
  const wizardDefs = [
    {
      name: "ProviderSelection",
      header: () => {tr.t("Select Provider")},
      content: () => <ProviderSelection store={providerSelectionStore} />,
      enter: async () => {
        stores.providerSelectionStore.setProvider("");
      },
    },
    {
      name: "Import",
      header: observer(() => Import),
      content: ({}) => (
        <ImportProjectForm
          store={importProjectStore}
          storeProvider={providerSelectionStore}
        />
      ),
      enter: async () => {
        importProjectStore.project = {};
      },
    },
    {
      name: "Settings",
      header: observer(() => Settings),
      content: ({}) => (
        <InfraSettings
          store={infraSettingsStore}
          storeProvider={providerSelectionStore}
        />
      ),
      enter: async () => {
        infraSettingsStore.data.name = importProjectStore.project.title;
      },
    },
    {
      name: "GitCredential",
      header: observer(() => Git Credential),
      content: ({}) => <GitCredentialConfig store={gitCredentialStore} />,
    },
    {
      name: "GitRepository",
      header: observer(() => Git Repository),
      content: ({}) => <RepositoryConfig store={gitRepositoryStore} />,
    },
    {
      name: "Configuration",
      header: observer(() => Configuration),
      content: ({}) =>
        configViewFromProvider(providerSelectionStore.data.providerName),
    },
  ];

  const Wizard = wizard(context, { wizardDefs });

  // TODO only for testing
  // providerSelectionStore.selectProvider({ providerName: "aws" });
  // importProjectStore.onSelectProject({
  //   title: "EKS",
  //   description: "Deploy a kubernetes cluster with EKS",
  //   url: "https://github.com/grucloud/grucloud/",
  //   branch: "main",
  //   directory: "packages/modules/aws/eks/example",
  // });

  // infraSettingsStore.save({ data: { name: "EKS infra", stage: "dev" } });
  // gitCredentialStore.save({
  //   data: {
  //     username: "",
  //     password: "",
  //   },
  // });
  // gitRepositoryStore.setData({
  //   url: "https://github.com/grucloud/xxxxxxx",
  //   branch: "master",
  // });
  // gitRepositoryStore.save();

  return observer(function WizardView() {
    return (

        <Wizard.View />

    );
  });
};
<commit_msg>fix ProviderSelection onEnter<commit_after>/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
import { observer } from "mobx-react";

import button from "mdlean/lib/button";
import wizard from "mdlean/lib/wizard";

import {
  providerSelection,
  providerSelectionCreateStore,
} from "./providerSelection";
import { awsFormCreate, createStoreAws } from "./awsConfig";
import { gcpFormCreate, createStoreGoogle } from "./gcpConfig";
import { azureFormCreate, createStoreAzure } from "./azureConfig";
import { ovhFormCreate, createStoreOvh } from "./ovhConfig";

import { repositoryConfig, repositoryCreateStore } from "./gitRepositoryConfig";
import {
  gitCredentialConfig,
  gitCredentialCreateStore,
} from "./gitCredentialConfig";
import { infraSettings, infraSettingsCreateStore } from "./infraSettings";

import {
  importProjectForm,
  importProjectCreateStore,
} from "./importProjectForm";

export const buttonWizardBack = (context) => {
  const Button = button(context);
  return () => (
    <Button onClick={() => context.emitter.emit("step.previous")}>
      {"\u25c0"} Back
    </Button>
  );
};

export const buttonHistoryBack = (context) => {
  const Button = button(context);
  return () => (
    <Button onClick={() => context.emitter.emit("step.previous")}>
      {"\u25c0"} Back
    </Button>
  );
};

export const wizardStoreCreate = (context) => {
  const providerSelectionStore = providerSelectionCreateStore({ context });

  const importProjectStore = importProjectCreateStore(context);

  const infraSettingsStore = infraSettingsCreateStore({
    context,
    providerSelectionStore,
    importProjectStore,
  });

  const gitCredentialStore = gitCredentialCreateStore({
    context,
    infraSettingsStore,
  });

  const gitRepositoryStore = repositoryCreateStore({
    context,
    infraSettingsStore,
    gitCredentialStore,
  });

  const aws = createStoreAws(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  const google = createStoreGoogle(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  const azure = createStoreAzure(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  const ovh = createStoreOvh(context, {
    importProjectStore,
    gitCredentialStore,
    gitRepositoryStore,
    infraSettingsStore,
  });

  return {
    providerSelectionStore,
    importProjectStore,
    infraSettingsStore,
    gitCredentialStore,
    gitRepositoryStore,
    aws,
    azure,
    google,
    ovh,
  };
};

export const wizardCreate = ({ context, stores }) => {
  const { tr, emitter } = context;
  const ProviderSelection = providerSelection(context);
  const InfraSettings = infraSettings(context);
  const RepositoryConfig = repositoryConfig(context);
  const GitCredentialConfig = gitCredentialConfig(context);
  const ImportProjectForm = importProjectForm(context);

  const AwsFormCreate = awsFormCreate(context);
  const GcpFormCreate = gcpFormCreate(context);
  const AzureFormCreate = azureFormCreate(context);
  const OvhFormCreate = ovhFormCreate(context);

  const {
    providerSelectionStore,
    importProjectStore,
    infraSettingsStore,
    gitCredentialStore,
    gitRepositoryStore,
    aws,
    google,
    azure,
    ovh,
  } = stores.wizard;

  const configViewFromProvider = (providerName) => {
    switch (providerName) {
      case "aws":
        return <AwsFormCreate store={aws} />;
      case "google":
        return <GcpFormCreate store={google} />;
      case "azure":
        return <AzureFormCreate store={azure} />;
      case "ovh":
        return <OvhFormCreate store={ovh} />;
      default:
        throw Error(`invalid provider type`);
    }
  };
  const wizardDefs = [
    {
      name: "ProviderSelection",
      header: () => {tr.t("Select Provider")},
      content: () => <ProviderSelection store={providerSelectionStore} />,
      enter: async () => {
        providerSelectionStore.setProvider("");
      },
    },
    {
      name: "Import",
      header: observer(() => Import),
      content: ({}) => (
        <ImportProjectForm
          store={importProjectStore}
          storeProvider={providerSelectionStore}
        />
      ),
      enter: async () => {
        importProjectStore.project = {};
      },
    },
    {
      name: "Settings",
      header: observer(() => Settings),
      content: ({}) => (
        <InfraSettings
          store={infraSettingsStore}
          storeProvider={providerSelectionStore}
        />
      ),
      enter: async () => {
        infraSettingsStore.data.name = importProjectStore.project.title;
      },
    },
    {
      name: "GitCredential",
      header: observer(() => Git Credential),
      content: ({}) => <GitCredentialConfig store={gitCredentialStore} />,
      enter: async () => {
        gitCredentialStore.getAll();
      },
    },
    {
      name: "GitRepository",
      header: observer(() => Git Repository),
      content: ({}) => <RepositoryConfig store={gitRepositoryStore} />,
    },
    {
      name: "Configuration",
      header: observer(() => Configuration),
      content: ({}) =>
        configViewFromProvider(providerSelectionStore.data.providerName),
    },
  ];

  const Wizard = wizard(context, { wizardDefs });

  // TODO only for testing
  // providerSelectionStore.selectProvider({ providerName: "aws" });
  // importProjectStore.showNewProjectFromTemplate(true);
  // importProjectStore.onSelectProject({
  //   title: "EKS",
  //   description: "Deploy a kubernetes cluster with EKS",
  //   url: "https://github.com/grucloud/grucloud/",
  //   branch: "main",
  //   directory: "packages/modules/aws/eks/example",
  // });

  // infraSettingsStore.save({ data: { name: "EKS infra", stage: "dev" } });
  // gitCredentialStore.save({
  //   data: {
  //     username: "",
  //     password: "",
  //   },
  // });
  // gitRepositoryStore.setData({
  //   url: "https://github.com/grucloud/xxxxxxx",
  //   branch: "master",
  // });
  // gitRepositoryStore.save();

  return observer(function WizardView() {
    return (

        <Wizard.View />

    );
  });
};
<|endoftext|>


<commit_before><commit_msg>fix status<commit_after><|endoftext|>


<commit_before>export default {
  meta: "DART mockup",
//  photoBasePath: "https://opendirective.github.io/brianMedia/DARTMockup/",
  photoBasePath: "file:///C:/projects/brianMedia/DARTMockup/",
  albums: [
    {name: "start",
     cards: [{label: "Familjen", image: "Familjen", album: 'Familjen'},
             {label: "Resor", image: "Resor", album: "Resor"},
             {label: "Huset", image: "Huset", album: "Huset"},
             {label: "Intressen", image: "Intressen", album: "Intressen"}
            ]
    },
    {name: "Familjen",
     cards: [{label: "Barnen", image: "Barnen", album: 'Barnen'},
             {label: "Barnbarnen", image: "Barnbarnen", album: "Barnbarnen"},
             {label: "Mor & far", image: "Mor & far", album: "Mor & far"},
             {label: "Missan", image: "Missan", album: "Missan"}
            ]
    },
    {name: "Barnbarnen",
     cards: [{label: "Einer", image: "Einer", album: 'Einer'},
             {label: "Amon", image: "Amon", album: "Amon"},
             {label: "Isidor", image: "Isidor", album: "Isidor"},
             {label: "Tyr", image: "Tyr", album: "Tyr"}
            ]
    },
    {name: "Resor",
      cards: [{label: "Gotland", image: "Gotland", album: 'Visby'},
              {label: "Vadstena", image: "Vadstena", album: "Vadstena"},
              {label: "Skärg ården", image: "Skärg ården", album: "Skärg ården"},
              {label: "Paris", image: "Paris", album: "Paris"}
            ]
    },
    {name: "Visby",
      cards: [{label: "Ruin", image: "Ruin", album: 'Ruin'},
              {label: "Botaniska", image: "Botaniska", album: "Botaniska"},
              {label: "Fåro", image: "Fåro", album: "Fåro"},
              {label: "Promenad", image: "Promenad", album: "Promenad"}
            ]
    },
    {name: "Huset",
      cards: [{label: "Vinter", image: "Vinter", album: 'Vinter'},
              {label: "Sommar", image: "Sommar", album: "Sommar"},
              {label: "Solnedgång", image: "Solnedgång", album: "Solnedgång"},
              {label: "Skogen", image: "Skogen", album: "Skogen"}
            ]
    },
    {name: "Tradgården",
      cards: [{label: "Stora rabatten", image: "Stora rabatten", album: 'Stora rabatten'},
              {label: "Vallmo", image: "Vallmo", album: "Vallmo"},
              {label: "Vårrabatt", image: "Vårrabatt", album: "Vårrabatt"},
              {label: "Tradpion", image: "Tradpion", album: "Tradpion"}
            ]
    },
    {name: "Intressen",
      cards: [{label: "Handarbete", image: "Handarbete", album: 'Tradgården'},
              {label: "Bakning", image: "Bakning", album: "Bakning"},
              {label: "Odling", image: "Odling", album: "Odling"},
              {label: "Båten", image: "Båten", album: "Båten"}
            ]
    },
    {name: "Odling",
      cards: [{label: "Squash", image: "Squash", album: 'Squash'},
              {label: "Rabarber", image: "Rabarber", album: "Rabarber"},
              {label: "Landet", image: "Landet", album: "Landet"},
              {label: "Vårodling", image: "Vårodling", album: "Vårodling"}
            ]
    }
  ]
}
<commit_msg>remove extra default config<commit_after><|endoftext|>


<commit_before><commit_msg>removed obsolete BXE flowscript<commit_after><|endoftext|>


<commit_before>/* jshint browser: true */
/* global define: false, expect: false, equal: false, ok: false, test: false*/

define(["../browserbox.js"], function(browserbox){

    "use strict";

    module("check special use");

    test("SPECIAL-USE extension", function(err){
        var br = browserbox();
        br.capability = ["SPECIAL-USE"];

        equal(false, br._checkSpecialUse({}));
        equal(false, br._checkSpecialUse({flags: ["test"]}));
        equal("\\All", br._checkSpecialUse({flags: ["test", "\\All"]}));
    });

    test("No extension", function(err){
        var br = browserbox();

        equal(false, br._checkSpecialUse({name: "test"}));
        equal("\\Trash", br._checkSpecialUse({name: "Praht"}));
    });

    module("namespace");

    test("No namespace response", function(err){
        var br = browserbox();
        ok(!br._parseNAMESPACE({payload:{NAMESPACE:[]}}));
    });

    test("Single personal namespace", function(err){
        var br = browserbox();
        deepEqual(

            {
                personal: [{prefix: "INBOX.", delimiter: "."}],
                users: null,
                shared: null
            },

            br._parseNAMESPACE({payload:{
                NAMESPACE:[{attributes: [[[{type: "STRING", value: "INBOX."}, {type: "STRING", value: "."}]], null, null]}]
            }}));
    });

    test("Single personal, single users, multiple shared", function(err){
        var br = browserbox();
        deepEqual(

            {
                personal: [{prefix: "", delimiter: "/"}],
                users: [{prefix: "~", delimiter: "/"}],
                shared: [{prefix: "#shared/", delimiter: "/"},{prefix: "#public/", delimiter: "/"}]
            },

            br._parseNAMESPACE({payload:{
                NAMESPACE:[
                    {
                        attributes: [
                            // personal
                            [[{type: "STRING", value: ""}, {type: "STRING", value: "/"}]],
                            // users
                            [[{type: "STRING", value: "~"}, {type: "STRING", value: "/"}]],
                            // shared
                            [
                                [{type: "STRING", value: "#shared/"}, {type: "STRING", value: "/"}],
                                [{type: "STRING", value: "#public/"}, {type: "STRING", value: "/"}]
                            ]
                        ]
                    }
                ]
            }}));
    });

    module("select response");

    test("Complete response", function(err){
        var br = browserbox();
        deepEqual(

            {
                exists: 123,
                flags: ["\\Answered", "\\Flagged"],
                highestModseq: 3682918,
                permanentFlags: ["\\Answered", "\\Flagged"],
                readOnly: false,
                uidNext: 38361,
                uidValidity: 2
            },

            br._parseSELECT({
                code: "READ-WRITE",
                payload: {
                    EXISTS: [{nr: 123}],
                    FLAGS: [{attributes: [[{type: "ATOM", value: "\\Answered"}, {type: "ATOM", value: "\\Flagged"}]]}],
                    OK: [
                        {code: "PERMANENTFLAGS", permanentflags: ["\\Answered", "\\Flagged"]},
                        {code: "UIDVALIDITY", uidvalidity: "2"},
                        {code: "UIDNEXT", uidnext: "38361"},
                        {code: "HIGHESTMODSEQ", highestmodseq: "3682918"}
                    ]
                }
            }));
    });

    test("No modseq", function(err){
        var br = browserbox();
        deepEqual(

            {
                exists: 123,
                flags: ["\\Answered", "\\Flagged"],
                permanentFlags: ["\\Answered", "\\Flagged"],
                readOnly: false,
                uidNext: 38361,
                uidValidity: 2
            },

            br._parseSELECT({
                code: "READ-WRITE",
                payload: {
                    EXISTS: [{nr: 123}],
                    FLAGS: [{attributes: [[{type: "ATOM", value: "\\Answered"}, {type: "ATOM", value: "\\Flagged"}]]}],
                    OK: [
                        {code: "PERMANENTFLAGS", permanentflags: ["\\Answered", "\\Flagged"]},
                        {code: "UIDVALIDITY", uidvalidity: "2"},
                        {code: "UIDNEXT", uidnext: "38361"}
                    ]
                }
            }));
    });

    test("Read only", function(err){
        var br = browserbox();
        deepEqual(

            {
                exists: 123,
                flags: ["\\Answered", "\\Flagged"],
                permanentFlags: ["\\Answered", "\\Flagged"],
                readOnly: true,
                uidNext: 38361,
                uidValidity: 2
            },

            br._parseSELECT({
                code: "READ-ONLY",
                payload: {
                    EXISTS: [{nr: 123}],
                    FLAGS: [{attributes: [[{type: "ATOM", value: "\\Answered"}, {type: "ATOM", value: "\\Flagged"}]]}],
                    OK: [
                        {code: "PERMANENTFLAGS", permanentflags: ["\\Answered", "\\Flagged"]},
                        {code: "UIDVALIDITY", uidvalidity: "2"},
                        {code: "UIDNEXT", uidnext: "38361"}
                    ]
                }
            }));
    });

});
<commit_msg>Fixed namespace tests<commit_after>/* jshint browser: true */
/* global define: false, expect: false, equal: false, ok: false, test: false*/

define(["../browserbox.js"], function(browserbox){

    "use strict";

    module("check special use");

    test("SPECIAL-USE extension", function(err){
        var br = browserbox();
        br.capability = ["SPECIAL-USE"];

        equal(false, br._checkSpecialUse({}));
        equal(false, br._checkSpecialUse({flags: ["test"]}));
        equal("\\All", br._checkSpecialUse({flags: ["test", "\\All"]}));
    });

    test("No extension", function(err){
        var br = browserbox();

        equal(false, br._checkSpecialUse({name: "test"}));
        equal("\\Trash", br._checkSpecialUse({name: "Praht"}));
    });

    module("namespace");

    test("No namespace response", function(err){
        var br = browserbox();
        ok(!br._parseNAMESPACE({payload:{NAMESPACE:[]}}));
    });

    test("Single personal namespace", function(err){
        var br = browserbox();
        deepEqual(

            {
                personal: [{prefix: "INBOX.", delimiter: "."}],
                users: false,
                shared: false
            },

            br._parseNAMESPACE({payload:{
                NAMESPACE:[{attributes: [[[{type: "STRING", value: "INBOX."}, {type: "STRING", value: "."}]], null, null]}]
            }}));
    });

    test("Single personal, single users, multiple shared", function(err){
        var br = browserbox();
        deepEqual(

            {
                personal: [{prefix: "", delimiter: "/"}],
                users: [{prefix: "~", delimiter: "/"}],
                shared: [{prefix: "#shared/", delimiter: "/"},{prefix: "#public/", delimiter: "/"}]
            },

            br._parseNAMESPACE({payload:{
                NAMESPACE:[
                    {
                        attributes: [
                            // personal
                            [[{type: "STRING", value: ""}, {type: "STRING", value: "/"}]],
                            // users
                            [[{type: "STRING", value: "~"}, {type: "STRING", value: "/"}]],
                            // shared
                            [
                                [{type: "STRING", value: "#shared/"}, {type: "STRING", value: "/"}],
                                [{type: "STRING", value: "#public/"}, {type: "STRING", value: "/"}]
                            ]
                        ]
                    }
                ]
            }}));
    });

    module("select response");

    test("Complete response", function(err){
        var br = browserbox();
        deepEqual(

            {
                exists: 123,
                flags: ["\\Answered", "\\Flagged"],
                highestModseq: 3682918,
                permanentFlags: ["\\Answered", "\\Flagged"],
                readOnly: false,
                uidNext: 38361,
                uidValidity: 2
            },

            br._parseSELECT({
                code: "READ-WRITE",
                payload: {
                    EXISTS: [{nr: 123}],
                    FLAGS: [{attributes: [[{type: "ATOM", value: "\\Answered"}, {type: "ATOM", value: "\\Flagged"}]]}],
                    OK: [
                        {code: "PERMANENTFLAGS", permanentflags: ["\\Answered", "\\Flagged"]},
                        {code: "UIDVALIDITY", uidvalidity: "2"},
                        {code: "UIDNEXT", uidnext: "38361"},
                        {code: "HIGHESTMODSEQ", highestmodseq: "3682918"}
                    ]
                }
            }));
    });

    test("No modseq", function(err){
        var br = browserbox();
        deepEqual(

            {
                exists: 123,
                flags: ["\\Answered", "\\Flagged"],
                permanentFlags: ["\\Answered", "\\Flagged"],
                readOnly: false,
                uidNext: 38361,
                uidValidity: 2
            },

            br._parseSELECT({
                code: "READ-WRITE",
                payload: {
                    EXISTS: [{nr: 123}],
                    FLAGS: [{attributes: [[{type: "ATOM", value: "\\Answered"}, {type: "ATOM", value: "\\Flagged"}]]}],
                    OK: [
                        {code: "PERMANENTFLAGS", permanentflags: ["\\Answered", "\\Flagged"]},
                        {code: "UIDVALIDITY", uidvalidity: "2"},
                        {code: "UIDNEXT", uidnext: "38361"}
                    ]
                }
            }));
    });

    test("Read only", function(err){
        var br = browserbox();
        deepEqual(

            {
                exists: 123,
                flags: ["\\Answered", "\\Flagged"],
                permanentFlags: ["\\Answered", "\\Flagged"],
                readOnly: true,
                uidNext: 38361,
                uidValidity: 2
            },

            br._parseSELECT({
                code: "READ-ONLY",
                payload: {
                    EXISTS: [{nr: 123}],
                    FLAGS: [{attributes: [[{type: "ATOM", value: "\\Answered"}, {type: "ATOM", value: "\\Flagged"}]]}],
                    OK: [
                        {code: "PERMANENTFLAGS", permanentflags: ["\\Answered", "\\Flagged"]},
                        {code: "UIDVALIDITY", uidvalidity: "2"},
                        {code: "UIDNEXT", uidnext: "38361"}
                    ]
                }
            }));
    });

});
<|endoftext|>


<commit_before><commit_msg>Clarify tests.<commit_after><|endoftext|>


<commit_before><commit_msg>replace clearRegisteredEpics with reset<commit_after><|endoftext|>


<commit_before><commit_msg>Extend constructor inlining test case.<commit_after><|endoftext|>


<commit_before><commit_msg>tests: fix smooth tests by cloning the media files each time they are requested<commit_after><|endoftext|>


<commit_before>/*global requirejs*/
requirejs(['../../src/js/paths', '../utils'], function (paths, Utils) {

    'use strict';

    var FENIX_CDN = "//fenixapps.fao.org/repository",
        baseUrl = '../../src/js/';

    // replace placeholders and baseUrl
    paths = Utils.replacePlaceholders(paths, FENIX_CDN);
    paths.baseUrl = baseUrl;

    requirejs.config(paths);

    requirejs(['fx-c-c/start', 'jquery', 'amplify'], function (ChartCreator, $) {

        // Chart with scattered data
        $.getJSON("data/afo/scattered_data.json", function (model) {

            // Timeserie Chart
            var c = new ChartCreator();
            $.when( c.init({
                model: model,
                adapter: {
                    type: "timeserie",
                    filters: {
                        xAxis: 'time',
                        yAxis: 'Element',
                        value: 'value',
                        series: []
                    }
                },
                template: {},
                creator: {}
            })).then(function( creator ) {
                    creator.render({
                            container: Utils.createDiv(),
                            creator: {
                                chartObj: {
                                    chart:{
                                        type: "line"
                                    },
                                    tooltip: {
                                        crosshairs: "mixed",
                                        shared: true
                                    }
                                }
                            }
                        }
                    );
                }
            );

            // Line chart
            c = new ChartCreator();
            $.when( c.init({
                model: model,
                adapter: {
                    type: "line",
                    filters: {
                        xAxis: 'time',
                        yAxis: 'Element',
                        value: 'value',
                        series: []
                    }
                },
                template: {},
                creator: {}
            })).then(function( creator ) {
                    creator.render({
                            container: Utils.createDiv(),
                            creator: {
                                chartObj: {
                                    chart:{
                                        type: "line"
                                    },
                                    tooltip: {
                                        crosshairs: "mixed",
                                        shared: true
                                    }
                                }
                            }
                        }
                    );
                }
            );

            // Bar Chart with the same data
            c = new ChartCreator();
            $.when( c.init({
                model: model,
                adapter: {
                    lang: 'EN',
                    type: "",
                    filters: {
                        xAxis: 'time',
                        yAxis: 'Element',
                        value: 'value',
                        series: []
                    }
                },
                template: {},
                creator: {},
            })).then(function( creator ) {
                    creator.render( {
                            container: Utils.createDiv(),
                            creator: {
                                chartObj: {
                                    chart:{
                                        type: "column"
                                    }
                                }
                            }
                        }
                    );
                }
            );

        });
    });
});<commit_msg>added tests<commit_after>/*global requirejs, $*/
requirejs(['../../src/js/paths', '../utils'], function (paths, Utils) {

    'use strict';

    var FENIX_CDN = "//fenixapps.fao.org/repository",
        baseUrl = '../../src/js/';

    // replace placeholders and baseUrl
    paths = Utils.replacePlaceholders(paths, FENIX_CDN);
    paths.baseUrl = baseUrl;

    requirejs.config(paths);

    function lineChartOptions(options, container) {
        return $.extend({}, options || {}, {
            container: container || Utils.createDiv(),
            creator: {
                chartObj: {
                    chart:{
                        type: "line"
                    },
                    tooltip: {
                        crosshairs: "mixed",
                        shared: true
                    }
                }
            }
        });
    }

    function columnChartOptions(options, container) {
        return $.extend({}, options || {}, {
            container: container || Utils.createDiv(),
            creator: {
                chartObj: {
                    chart:{
                        type: "column"
                    }
                }
            }
        });
    }

    function barChartOptions(options, container) {
        return $.extend({}, options || {}, {
            container: container || Utils.createDiv(),
            creator: {
                chartObj: {
                    chart:{
                        type: "bar"
                    }
                }
            }
        });
    }

    requirejs(['fx-c-c/start', 'jquery', 'amplify'], function (ChartCreator, $) {

        // Chart with scattered data
        $.getJSON("data/afo/scattered_data.json", function (model) {

            // Consistant Timeserie Chart
            var c = new ChartCreator();
            $.when( c.init({
                model: model,
                adapter: {
                    type: "timeserie",
                    filters: {
                        xAxis: 'time',
                        yAxis: 'Element',
                        value: 'value',
                        series: []
                    }
                },
                template: {},
                creator: {}
            })).then(function( creator ) {
                var o = {
                    template: {
                        title: "Chart with Timeserie",
                    }
                };
                creator.render(lineChartOptions(o));
                creator.render(columnChartOptions(o));
                creator.render(barChartOptions(o));
            });

            // Scattered Data Chart
            var c2 = new ChartCreator();
            $.when( c2.init({
                model: model,
                adapter: {
                    type: "line",
                    filters: {
                        xAxis: 'time',
                        yAxis: 'Element',
                        value: 'value',
                        series: []
                    }
                },
                template: {},
                creator: {}
            })).then(function( creator ) {
                var o = {
                    template: {
                        title: "Chart with scattered data",
                    }
                };
                creator.render(lineChartOptions(o));
                creator.render(columnChartOptions(o));
                creator.render(barChartOptions(o));
            });
        });
    });

});<|endoftext|>


<commit_before>import React from 'react';
import ComponentTypeIcons from '../../components/ListView/ComponentTypeIcons';
import ComponentSummaryList from '../../components/ListView/ComponentSummaryList';
import MetadataApi from '../../data/MetadataApi';
import constants from '../../core/constants';

class ListItemComponents extends React.Component {

  state = { expanded: false, dependencies: [], showAllDeps: false }

  componentWillReceiveProps(newProps) {
    // compare old value to new value, and if this component is getting new data,
    // then get the current expand state of the new value as it is in the old dom
    // and apply that expand state to this component
    const olditem = this.props.listItem;
    const newitem = newProps.listItem;
    const parent = this.props.listItemParent;
    if (olditem !== newitem) {
      if ($(`#${parent} [data-name='${newitem.name}']`).hasClass('list-view-pf-expand-active')) {
        this.setState({ expanded: true });
      } else {
        this.setState({ expanded: false });
      }
    }
  }

  getDependencies(component) {
    const p = new Promise((resolve, reject) => {
      Promise.all([
        MetadataApi.getData(constants.get_modules_info + component.name),
      ]).then((data) => {
        const dependencies = data[0].modules[0].dependencies;
        this.setState({ dependencies });
        resolve();
      }).catch(e => {
        console.log(`getDependencies: Error getting dependencies: ${e}`);
        reject();
      });
    });
    return p;
  }

  handleExpandComponent = (event) => {
    // the user clicked a list item in the recipe contents area to expand or collapse
    if (!$(event.target).is('button, a, input, .fa-ellipsis-v')) {
      const expandState = !this.state.expanded;
      this.setState({ expanded: expandState });
      if (expandState === true && this.state.dependencies.length === 0) {
        this.getDependencies(this.props.listItem);
      }
    }
  }

  render() {
    const { listItem } = this.props;
    return (
      <div data-name={listItem.name} className={`list-group-item ${this.state.expanded ? 'list-view-pf-expand-active' : ''}`}>

 this.handleExpandComponent(e)}>

            <span className={`fa fa-angle-right ${this.state.expanded ? 'fa-angle-down' : 'fa-angle-right'}`}>

            <input type="checkbox" />

          {this.props.noEditComponent !== true &&

                <button
                  className="btn btn-link dropdown-toggle"
                  type="button"
                  id="dropdownKebabRight9"
                  data-toggle="dropdown"
                  aria-haspopup="true"
                  aria-expanded="true"
                ></button>

                     this.props.handleComponentDetails(
                        e, listItem, this.props.componentDetailsParent)}
                    >View

Edit

                     this.props.handleRemoveComponent(e, listItem)}
                    >Remove

          }

              <ComponentTypeIcons componentType={listItem.ui_type} />

                   this.props.handleComponentDetails(
                    e, listItem, this.props.componentDetailsParent)}
                  >{listItem.name}

                  {listItem.summary}

                  Version {listItem.version}

                  Release {listItem.release}

                  Dependencies
                  {`${(this.state.dependencies.length > 0) ? this.state.dependencies.length : '---'}`}

        <div className={`list-group-item-container container-fluid ${this.state.expanded ? '' : 'hidden'}`}>

Version

{listItem.version ? listItem.version :  }

Release

{listItem.release ? listItem.release :  }

Architecture

---

Install Size

2 MB (5 MB with Dependencies)

URL

                {listItem.homepage != null &&

{listItem.homepage}

                  ||

                }

Packager

Red Hat

Product Family

---

Lifecycle

01/15/2017

Support Level

Standard

              Errata

RHBA-2016:1641 RHEL Atomic OSTree Update 7.2.6-1

RHBA-2016:1641 RHEL Atomic OSTree Update 7.2.6-1

              {listItem.ui_type !== 'RPM' &&

Child Components (4)

                          fm-group:rpm-development-tools

                          fm-group:hardware-support

                          View More

}
              {this.props.isDependency &&

Required By (1)

                        <ComponentTypeIcons componentType={listItem.ui_type} />

                          {listItem.requiredBy}---

}
              {this.state.dependencies.length > 0 &&
                <ComponentSummaryList listItems={this.state.dependencies} />
              }

    );
  }

}

ListItemComponents.propTypes = {
  listItem: React.PropTypes.object,
  listItemParent: React.PropTypes.string,
  componentDetailsParent: React.PropTypes.object,
  handleComponentDetails: React.PropTypes.func,
  handleRemoveComponent: React.PropTypes.func,
  noEditComponent: React.PropTypes.bool,
  isDependency: React.PropTypes.bool,
};

export default ListItemComponents;
<commit_msg>Making update based on review<commit_after>import React from 'react';
import ComponentTypeIcons from '../../components/ListView/ComponentTypeIcons';
import ComponentSummaryList from '../../components/ListView/ComponentSummaryList';
import MetadataApi from '../../data/MetadataApi';
import constants from '../../core/constants';

class ListItemComponents extends React.Component {

  state = { expanded: false, dependencies: [], showAllDeps: false }

  componentWillReceiveProps(newProps) {
    // compare old value to new value, and if this component is getting new data,
    // then get the current expand state of the new value as it is in the old dom
    // and apply that expand state to this component
    const olditem = this.props.listItem;
    const newitem = newProps.listItem;
    const parent = this.props.listItemParent;
    if (olditem !== newitem) {
      if ($(`#${parent} [data-name='${newitem.name}']`).hasClass('list-view-pf-expand-active')) {
        this.setState({ expanded: true });
      } else {
        this.setState({ expanded: false });
      }
    }
  }

  getDependencies(component) {
    const p = new Promise((resolve, reject) => {
      Promise.all([
        MetadataApi.getData(constants.get_modules_info + component.name),
      ]).then((data) => {
        const dependencies = data[0].modules[0].dependencies;
        this.setState({ dependencies });
        resolve();
      }).catch(e => {
        console.log(`getDependencies: Error getting dependencies: ${e}`);
        reject();
      });
    });
    return p;
  }

  handleExpandComponent = (event) => {
    // the user clicked a list item in the recipe contents area to expand or collapse
    if (!$(event.target).is('button, a, input, .fa-ellipsis-v')) {
      const expandState = !this.state.expanded;
      this.setState({ expanded: expandState });
      if (expandState === true && this.state.dependencies.length === 0) {
        this.getDependencies(this.props.listItem);
      }
    }
  }

  render() {
    const { listItem } = this.props;
    return (
      <div data-name={listItem.name} className={`list-group-item ${this.state.expanded ? 'list-view-pf-expand-active' : ''}`}>

 this.handleExpandComponent(e)}>

            <span className={`fa fa-angle-right ${this.state.expanded ? 'fa-angle-down' : 'fa-angle-right'}`}>

            <input type="checkbox" />

          {this.props.noEditComponent !== true &&

                <button
                  className="btn btn-link dropdown-toggle"
                  type="button"
                  id="dropdownKebabRight9"
                  data-toggle="dropdown"
                  aria-haspopup="true"
                  aria-expanded="true"
                ></button>

                     this.props.handleComponentDetails(
                        e, listItem, this.props.componentDetailsParent)}
                    >View

Edit

                     this.props.handleRemoveComponent(e, listItem)}
                    >Remove

          }

              <ComponentTypeIcons componentType={listItem.ui_type} />

                   this.props.handleComponentDetails(
                    e, listItem, this.props.componentDetailsParent)}
                  >{listItem.name}

                  {listItem.summary}

                  Version {listItem.version}

                  Release {listItem.release}

                  Dependencies
                  {`${(this.state.dependencies.length > 0) ? this.state.dependencies.length : '---'}`}

        <div className={`list-group-item-container container-fluid ${this.state.expanded ? '' : 'hidden'}`}>

Version

{listItem.version ? listItem.version :  }

Release

{listItem.release ? listItem.release :  }

Architecture

---

Install Size

2 MB (5 MB with Dependencies)

URL

                {listItem.homepage != null &&

{listItem.homepage}

                  ||

                }

Packager

Red Hat

Product Family

---

Lifecycle

01/15/2017

Support Level

Standard

              Errata

RHBA-2016:1641 RHEL Atomic OSTree Update 7.2.6-1

RHBA-2016:1641 RHEL Atomic OSTree Update 7.2.6-1

              {listItem.ui_type !== 'RPM' &&

Child Components (4)

                          fm-group:rpm-development-tools

                          fm-group:hardware-support

                          View More

}
              {this.props.isDependency &&

Required By (1)

                          ---

}
              {this.state.dependencies.length > 0 &&
                <ComponentSummaryList listItems={this.state.dependencies} />
              }

    );
  }

}

ListItemComponents.propTypes = {
  listItem: React.PropTypes.object,
  listItemParent: React.PropTypes.string,
  componentDetailsParent: React.PropTypes.object,
  handleComponentDetails: React.PropTypes.func,
  handleRemoveComponent: React.PropTypes.func,
  noEditComponent: React.PropTypes.bool,
  isDependency: React.PropTypes.bool,
};

export default ListItemComponents;
<|endoftext|>


<commit_before>var x = require('casper').selectXPath;
var mouse = require('mouse').create(casper);

casper.test.begin('basic tooltip is functional', 7, function(test) {
    casper.start("tests/functional.html", function() {
        test.assertExists(x('/html/body/div'));
        test.assertSelectorHasText(x('/html/body/div'), 'Hover over me!');
        test.assertSelectorHasText(x('/html/body/div/div[2]'), 'Not tooltip content!');
        test.assertSelectorHasText(x('/html/body/div/div[1]'), 'Tooltip content!');
        this.mouse.move(500, 500);
        test.assertNotVisible(x('/html/body/div/div[1]'));
        this.mouse.move(50, 10);
        test.assertVisible(x('/html/body/div/div[1]'));
        this.mouse.move(500, 100);
        test.assertNotVisible(x('/html/body/div/div[1]'));
    }).run(function() {
        test.done();
    });
});
<commit_msg>fixing order of tests to better reflect dom<commit_after>var x = require('casper').selectXPath;
var mouse = require('mouse').create(casper);

casper.test.begin('basic tooltip is functional', 7, function(test) {
    casper.start("tests/functional.html", function() {
        test.assertExists(x('/html/body/div'));
        test.assertSelectorHasText(x('/html/body/div'), 'Hover over me!');
        test.assertSelectorHasText(x('/html/body/div/div[1]'), 'Tooltip content!');
        test.assertSelectorHasText(x('/html/body/div/div[2]'), 'Not tooltip content!');
        this.mouse.move(500, 500);
        test.assertNotVisible(x('/html/body/div/div[1]'));
        this.mouse.move(50, 10);
        test.assertVisible(x('/html/body/div/div[1]'));
        this.mouse.move(500, 100);
        test.assertNotVisible(x('/html/body/div/div[1]'));
    }).run(function() {
        test.done();
    });
});
<|endoftext|>


<commit_before>if (typeof chai === 'undefined') {
  if (window.lively4url) {
    // workaround for lively4
    System.import('node_modules/chai/chai.js').then(module => {
      window.chai = module
    });
  } else {
    const _require = require; // workaround for lively modules
    if (typeof global !== 'undefined') {
      global.chai = _require('chai');
    }
  }
}
<commit_msg>fix: now the travis tests were broken<commit_after>if (typeof chai === 'undefined') {
  if (window && window.lively4url) {
    // workaround for lively4
    System.import('node_modules/chai/chai.js').then(module => {
      window.chai = module
    });
  } else {
    const _require = require; // workaround for lively modules
    if (typeof global !== 'undefined') {
      global.chai = _require('chai');
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

describe('The support for bluebird promises', function () {

    var Promise = require('bluebird');
    var nightShift = require('nightshift-core');
    var bluebird = require('../src');

    beforeEach(function () {
        nightShift.plugin(bluebird);
    });

    it('should create a bluebird promise', function () {
        var executor = jasmine.createSpy('executor');
        var promise = nightShift.promises.newPromise(executor);
        expect(executor).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Function));
        expect(promise).toEqual(jasmine.any(Promise));
    });

    it('should create a deferred object with a bluebird promise', function () {
        var deferred = nightShift.promises.defer();
        expect(deferred).toEqual({
            promise: jasmine.any(Promise),
            resolve: jasmine.any(Function),
            reject: jasmine.any(Function)
        });
    });

    it('should fulfill the bluebird promise when resolving a deferred object', function (done) {
        var deferred = nightShift.promises.defer();
        var fulfillment = 'fulfillment';
        deferred.resolve(fulfillment);

        var onFulfill = jasmine.createSpy('onFulfill');
        deferred.promise
            .then(onFulfill)
            .then(function () {
                expect(onFulfill).toHaveBeenCalledWith(fulfillment);
            })
            .then(done);
    });

    it('should reject the bluebird promise when rejecting a deferred object', function (done) {
        var deferred = nightShift.promises.defer();
        var error = 'error';
        deferred.reject(error);

        var onReject = jasmine.createSpy('onReject');
        deferred.promise
            .then(null, onReject)
            .then(function () {
                expect(onReject).toHaveBeenCalledWith(error);
            })
            .then(done);
    });

    it('should give access to the bluebird romise constructor', function () {
        expect(nightShift.promises.Promise).toBe(Promise);
    });
});<commit_msg>Changed test description<commit_after>'use strict';

describe('The promise utilities', function () {

    var Promise = require('bluebird');
    var nightShift = require('nightshift-core');
    var bluebird = require('../src');

    beforeEach(function () {
        nightShift.plugin(bluebird);
    });

    it('should create a bluebird promise', function () {
        var executor = jasmine.createSpy('executor');
        var promise = nightShift.promises.newPromise(executor);
        expect(executor).toHaveBeenCalledWith(jasmine.any(Function), jasmine.any(Function));
        expect(promise).toEqual(jasmine.any(Promise));
    });

    it('should create a deferred object with a bluebird promise', function () {
        var deferred = nightShift.promises.defer();
        expect(deferred).toEqual({
            promise: jasmine.any(Promise),
            resolve: jasmine.any(Function),
            reject: jasmine.any(Function)
        });
    });

    it('should fulfill the bluebird promise when resolving a deferred object', function (done) {
        var deferred = nightShift.promises.defer();
        var fulfillment = 'fulfillment';
        deferred.resolve(fulfillment);

        var onFulfill = jasmine.createSpy('onFulfill');
        deferred.promise
            .then(onFulfill)
            .then(function () {
                expect(onFulfill).toHaveBeenCalledWith(fulfillment);
            })
            .then(done);
    });

    it('should reject the bluebird promise when rejecting a deferred object', function (done) {
        var deferred = nightShift.promises.defer();
        var error = 'error';
        deferred.reject(error);

        var onReject = jasmine.createSpy('onReject');
        deferred.promise
            .then(null, onReject)
            .then(function () {
                expect(onReject).toHaveBeenCalledWith(error);
            })
            .then(done);
    });

    it('should give access to the bluebird romise constructor', function () {
        expect(nightShift.promises.Promise).toBe(Promise);
    });
});<|endoftext|>


<commit_before>module.exports = function (config) {
  const cfg = {
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      { pattern: './main.js', watched: false }
    ],
    exclude: [
    ],
    preprocessors: {
      './main.js': ['webpack', 'sourcemap']
    },
    webpack: require('./webpack-spec.config')({ env: 'test' }),
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: ['Chrome'],
    customLaunchers: {
      ChromeTravisCi: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    singleRun: true,
    concurrency: Infinity
  };

  if (process.env.TRAVIS) {
    cfg.browsers = ['Chrome_travis_ci'];
  }

  config.set(cfg);
}
<commit_msg>Build tweak to launch chrome for tests<commit_after>module.exports = function (config) {
  const cfg = {
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      { pattern: './main.js', watched: false }
    ],
    exclude: [
    ],
    preprocessors: {
      './main.js': ['webpack', 'sourcemap']
    },
    webpack: require('./webpack-spec.config')({ env: 'test' }),
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: ['Chrome'],
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
    singleRun: true,
    concurrency: Infinity
  };

  if (process.env.TRAVIS) {
    cfg.browsers = ['Chrome_travis_ci'];
  }

  config.set(cfg);
}
<|endoftext|>


<commit_before>var matrix = require('../src/matrix').matrix;
var assert = require('assert');

describe('matrix.add', function() {
    it('should perform matrix addition when given two matrices with the same dimensions', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        var expected = [[10, 10, 10], [10, 10, 10], [10, 10, 10]];
        var actual = matrix.add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given two matrices with different dimensions', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[1, 2], [3, 4], [5, 6]];
        assert.throws(function() {
            matrix.add(a, b);
        }, matrix.MatrixError, 'Matrices do not have the same dimensions.');
    });

    it('should perform scalar addition when given a matrix and a scalar value', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = 2;
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = matrix.add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should perform scalar addition when given a scalar value and a matrix', function() {
        var a = 2;
        var b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = matrix.add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given an invalid matrix', function() {
        var a = [[1, 2, 3], [4, 5], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        assert.throws(function() {
            matrix.add(a, b);
        }, matrix.MatrixError, 'A given matrix is invalid.');
    });

    it('should throw MatrixError when not given any matrices', function() {
        var a = 2;
        var b = 3;
        assert.throws(function() {
            matrix.add(a, b);
        }, matrix.MatrixError, 'No matrices given.');
    });

    it('should be integrated to Array.prototype', function() {
        var expected = true;
        var actual = Array.prototype.hasOwnProperty('add');
        assert.equal(expected, actual);
    });
});<commit_msg>added a test spec for matrix.add<commit_after>var matrix = require('../src/matrix').matrix;
var assert = require('assert');

describe('matrix.add', function() {
    it('should perform matrix addition when given two matrices with the same dimensions', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        var expected = [[10, 10, 10], [10, 10, 10], [10, 10, 10]];
        var actual = matrix.add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given two matrices with different dimensions', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[1, 2], [3, 4], [5, 6]];
        assert.throws(function() {
            matrix.add(a, b);
        }, matrix.MatrixError, 'Matrices do not have the same dimensions.');
    });

    it('should perform scalar addition when given a matrix and a scalar value', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = 2;
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = matrix.add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should perform scalar addition when given a scalar value and a matrix', function() {
        var a = 2;
        var b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var expected = [[3, 4, 5], [6, 7, 8], [9, 10, 11]];
        var actual = matrix.add(a, b);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given an invalid matrix', function() {
        var a = [[1, 2, 3], [4, 5], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        assert.throws(function() {
            matrix.add(a, b);
        }, matrix.MatrixError, 'A given matrix is invalid.');
    });

    it('should throw MatrixError when not given any matrices', function() {
        var a = 2;
        var b = 3;
        assert.throws(function() {
            matrix.add(a, b);
        }, matrix.MatrixError, 'No matrices given.');
    });

    it('should be integrated to Array.prototype', function() {
        var expected = true;
        var actual = Array.prototype.hasOwnProperty('add');
        assert.equal(expected, actual);
    });

    it('should add valid matrices through the Array.prototype property', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]];
        var expected = [[10, 10, 10], [10, 10, 10], [10, 10, 10]];
        var actual = a.add(b);
        assert.deepEqual(expected, actual);
    });
});<|endoftext|>


<commit_before>import {P2PImageServer} from "../src/P2PImageServer.js"
import {P2PImageClient} from "../src/P2PImageClient.js"

//
// make a very simple server that capitalizes the object coming in.
//
window.server = new P2PImageServer({id:'plumkin capitiliztion server' + Math.floor(10000*Math.random())})
server.on('connect', function(args){
  sendToDiv('server', 'client connected to the server')
})
server.on('data', function(args){
  sendToDiv('server', 'server recieved data:' + args.data)
  //capitalize the response
  args.peer.send(args.data.toUpperCase())
})

// connect to a server twice
//
//    the first peer
window.client1 = new P2PImageClient()
client1.connectToPeerID(server.id, function(err, connection) {
  connection.on('connect', function () {
    sendToDiv('client1', "CONNECTED")
    connection.send("hello world")
    sendToDiv('client1', "client 1 sent data: hello world")
  })
  connection.on('data', function (data) {
    sendToDiv('client1', 'client 1 recieved data:' + data)
  })
})
// the second peer
window.client2 = new P2PImageClient()
client2.connectToPeerID(server.id, function(err, connection) {
  connection.on('connect', function () {
    sendToDiv('client2', "CONNECTED")
    connection.send("hello mars")
    sendToDiv('client2', "client 2 sent data: hello mars")
  })
  connection.on('data', function (data) {
    sendToDiv('client2', 'client 2 recieved data:' + data)
  })
})

//
//  Just test if there are more peers
//
client1.getPeerList(function(err,val){
  var count = 0
  for(var i in val) {
    var server = val[i]
    count ++
  }
  console.assert(!err, err)
  console.assert(count > 0, "No servers. That shouldn't happen")
})

//helper function
function sendToDiv(id, text) {
  var el = document.getElementById(id)
  el.innerHTML += "...." + text + "
"
}

//
// test if blob support is in yet
//
function testBlobSupport(){
  var client = new P2PImageClient()
  client.connectToPeerID(server.id, function(err, connection) {
    connection.on('connect',function(){
        try{
          connection.send( new Blob(new Uint8Array(1234), {type: 'image/png'}))
          alert('blobs are now supported. This warrents a re-write of some stuff')
          sendToDiv('server','Blobs are now suported')
        } catch(err2) {
          console.error(err2)
          sendToDiv('server','Blobs are still not supported')
        }
    })
  })
}
testBlobSupport()
<commit_msg>for debugging<commit_after>import {P2PImageServer} from "../src/P2PImageServer.js"
import {P2PImageClient} from "../src/P2PImageClient.js"

window.P2PImageClient = P2PImageClient
window.P2PImageServer = P2PImageServer
//
// make a very simple server that capitalizes the object coming in.
//
window.server = new P2PImageServer({id:'plumkin capitiliztion server' + Math.floor(10000*Math.random())})
server.on('connect', function(args){
  sendToDiv('server', 'client connected to the server')
})
server.on('data', function(args){
  sendToDiv('server', 'server recieved data:' + args.data)
  //capitalize the response
  args.peer.send(args.data.toUpperCase())
})

// connect to a server twice
//
//    the first peer
window.client1 = new P2PImageClient()
client1.connectToPeerID(server.id, function(err, connection) {
  connection.on('connect', function () {
    sendToDiv('client1', "CONNECTED")
    connection.send("hello world")
    sendToDiv('client1', "client 1 sent data: hello world")
  })
  connection.on('data', function (data) {
    sendToDiv('client1', 'client 1 recieved data:' + data)
  })
})
// the second peer
window.client2 = new P2PImageClient()
client2.connectToPeerID(server.id, function(err, connection) {
  connection.on('connect', function () {
    sendToDiv('client2', "CONNECTED")
    connection.send("hello mars")
    sendToDiv('client2', "client 2 sent data: hello mars")
  })
  connection.on('data', function (data) {
    sendToDiv('client2', 'client 2 recieved data:' + data)
  })
})

//
//  Just test if there are more peers
//
client1.getPeerList(function(err,val){
  var count = 0
  for(var i in val) {
    var server = val[i]
    count ++
  }
  console.assert(!err, err)
  console.assert(count > 0, "No servers. That shouldn't happen")
})

//helper function
function sendToDiv(id, text) {
  var el = document.getElementById(id)
  el.innerHTML += "...." + text + "
"
}

//
// test if blob support is in yet
//
function testBlobSupport(){
  var client = new P2PImageClient()
  client.connectToPeerID(server.id, function(err, connection) {
    connection.on('connect',function(){
        try{
          connection.send( new Blob(new Uint8Array(1234), {type: 'image/png'}))
          alert('blobs are now supported. This warrents a re-write of some stuff')
          sendToDiv('server','Blobs are now suported')
        } catch(err2) {
          console.error(err2)
          sendToDiv('server','Blobs are still not supported')
        }
    })
  })
}
testBlobSupport()
<|endoftext|>