<commit_before>module.exports = function(grunt) {
  var _ = require('lodash'),
    request = require('request'),
    SauceTunnel = require('sauce-tunnel'),
    Q = require('q'),
    rqst = request.defaults({
      jar: false
    });

  //these result parsers return true if the tests all passed
  var resultParsers = {
    jasmine: function(result){
      return result.passed;
    },
    qunit: function(result){
      if (result.passed === undefined){ return undefined; }
      return result.passed == result.total;
    },
    mocha: function(result){
      if (result.passes === undefined){ return undefined; }
      return result.failures === 0;
    },
    'YUI Test': function(result){
      if (result.passed === undefined){ return undefined; }
      return result.passed == result.total;
    },
    custom: function(result){
      if (result.passed === undefined){ return undefined; }
      return result.failed === 0;
    }
  };

  var TestResult = function(jobId, user, key, framework, testInterval){
    var url = 'https://saucelabs.com/rest/v1/' + user + '/js-tests/status';
    var deferred = Q.defer();

    var requestParams = {
      method: 'post',
      url: url,
      auth: {
        user: user,
        pass: key
      },
      json: true,
      body: {
        "js tests": [jobId]
      }
    };

    var checkStatus = function(){

      rqst(requestParams, function(error, response, body){

        if (error){
          deferred.resolve({
            passed: undefined,
            result: {
              message: "Error connecting to api to get test status: " + error.toString()
            }
          });
          return;
        }

        var testInfo = body['js tests'][0];

        if (testInfo.status == "test error"){
          deferred.resolve({
            passed: undefined,
            result: {
              message: "Test Error"
            }
          });
          return;
        }

        if (!body.completed){
          setTimeout(checkStatus ,testInterval);
        } else {
          testInfo.passed = testInfo.result ? resultParsers[framework](testInfo.result) : false;
          deferred.resolve(testInfo);
        }

      });
    };

    checkStatus();

    return deferred.promise;
  };

  var TestRunner = function(user, key, testInterval) {
    this.user = user;
    this.key = key;
    this.url = 'https://saucelabs.com/rest/v1/' + this.user + '/js-tests';
    this.testInterval = testInterval;
    this.results = [];
  };

  TestRunner.prototype.runTests = function(browsers, urls, framework, tunnelIdentifier, testname, tags, build, onTestComplete, callback){

    var me = this;
    var numberOfJobs = browsers.length * urls.length;

    var addResultPromise = function(promise){
      me.results.push(promise);
      grunt.log.writeln(me.results.length, "/", numberOfJobs, 'tests started');
      if (me.results.length == numberOfJobs){

        Q.all(me.results).then(function(results){
          results = results.map(function(result){
            return result.valueOf().passed;
          });

          callback(results);
        });
      }
    };

    urls.forEach(function(url){
      me.runTest(browsers, url, framework, tunnelIdentifier, testname, tags, build, function(taskIds){

        taskIds.forEach(function(taskId){
          var resultPromise = new TestResult(taskId, me.user, me.key, framework, me.testInterval);
          addResultPromise(resultPromise);
          resultPromise.then(function(result){

            var alteredResult = onTestComplete(result);
            if (alteredResult !== undefined){
              result.passed = alteredResult;
            }

            grunt.log.subhead("\nTested %s", url);
            grunt.log.writeln("Platform: %s", result.platform);

            if (tunnelIdentifier && unsupportedPort(url)) {
              grunt.log.writeln("Warning: This url might use a port that is not proxied by Sauce Connect.".yellow);
            }

            if (result.passed === undefined){
              grunt.log.error(result.result.message);
            } else {
              grunt.log.writeln("Passed: %s", result.passed);
            }
            grunt.log.writeln("Url %s", result.url);

          }, function(e){
            grunt.log.error('some error? %s', e);
          });
        });
      });
    });
  };

  TestRunner.prototype.runTest = function(browsers, url, framework, tunnelIdentifier, testname, tags, build, callback){

    var parsePlatforms = function(browsers){
      return browsers.map(function(browser){
        return [browser.platform || "", browser.browserName || "", browser.version || ""];
      });
    };

    var requestParams = {
      method: 'post',
      url: this.url,
      auth: {
        user: this.user,
        pass: this.key
      },
      json: true,
      body: {
        platforms: parsePlatforms(browsers),
        url: url,
        framework: framework,
        name: testname,
        tags: tags,
        build: build
      }
    };

    if (tunnelIdentifier){
      requestParams.body.tunnel = "tunnel-identifier:" + tunnelIdentifier;
    }

    rqst(requestParams, function(error, response, body){

      if (error){
        grunt.log.error("Could not connect to Sauce Labs api: %s", error);
        throw error;
      }

      if (!body['js tests'] || !body['js tests'].length){
          grunt.log.error('Error starting tests through Sauce API: %s', JSON.stringify(body));
          throw new Error('Could not start tests through Sauce API');
      }

      callback(body['js tests']);

    });
  };

  var defaultsObj = {
    username: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
    identifier: Math.floor((new Date()).getTime() / 1000 - 1230768000).toString(),
    tunneled: true,
    tunnelTimeout: 120,
    testInterval: 1000 * 5,
    testReadyTimeout: 1000 * 5,
    onTestComplete: function() {

    },
    testname: "",
    tags: [],
    browsers: [{}]
  };

  function defaults(data) {
    var result = data;
    result.pages = result.url || result.urls;
    if (!_.isArray(result.pages)) {
      result.pages = [result.pages];
    }

    return result;
  }

  function configureLogEvents(tunnel) {
    var methods = ['write', 'writeln', 'error', 'ok', 'debug'];
    methods.forEach(function (method) {
      tunnel.on('log:'+method, function (text) {
        grunt.log[method](text);
      });
      tunnel.on('verbose:'+method, function (text) {
        grunt.verbose[method](text);
      });
    });
  }

  function runTask(arg, framework, callback){

    var test = new TestRunner(arg.username, arg.key, arg.testInterval);

    if (arg.tunneled){
      var tunnel = new SauceTunnel(arg.username, arg.key, arg.identifier, arg.tunneled, arg.tunnelTimeout);
      grunt.log.writeln("=> Starting Tunnel to Sauce Labs".inverse.bold);
      configureLogEvents(tunnel);

      tunnel.start(function(isCreated) {
        if (!isCreated) {
          grunt.log.error("Could not create tunnel to Sauce Labs");
          callback(false);
          return;
        }
        grunt.log.ok("Connected to Saucelabs");

        test.runTests(arg.browsers, arg.pages, framework, arg.identifier, arg.testname, arg.tags, arg.build, arg.onTestComplete, function(status){
          status = status.every(function(passed){ return passed; });
          grunt.log[status ? 'ok' : 'error']("All tests completed with status %s", status);
          grunt.log.writeln("=> Stopping Tunnel to Sauce Labs".inverse.bold);
          tunnel.stop(function() {
            callback(status);
          });
        });
      });

    } else {
      test.runTests(arg.browsers, arg.pages, framework, null, arg.testname, arg.tags, arg.build, arg.onTestComplete, function(status){
        status = status.every(function(passed){ return passed; });
        grunt.log[status ? 'ok' : 'error']("All tests completed with status %s", status);
        callback(status);
      });
    }
  }

  function unsupportedPort(url) {
    // Not all ports are proxied by Sauce Connect. List of supported ports is
    // available at https://saucelabs.com/docs/connect#localhost
    var portRegExp = /:(\d+)\//;
    var matches = portRegExp.exec(url);
    var port = matches ? parseInt(matches[1], 10) : null;
    var supportedPorts = [80, 443, 888, 2000, 2001, 2020, 2109, 2222, 2310, 3000, 3001, 3030,
      3210, 3333, 4000, 4001, 4040, 4321, 4502, 4503, 4567, 5000, 5001, 5050, 5555, 5432, 6000,
      6001, 6060, 6666, 6543, 7000, 7070, 7774, 7777, 8000, 8001, 8003, 8031, 8080, 8081, 8765,
      8888, 9000, 9001, 9080, 9090, 9876, 9877, 9999, 49221, 55001];

    if (port) {
      return supportedPorts.indexOf(port) === -1;
    }

    return false;
  }

  Object.keys(resultParsers).forEach(function(framework) {
    grunt.registerMultiTask('saucelabs-' + framework, 'Run ' + framework + 'test cases using Sauce Labs browsers', function() {
      var done = this.async(),
        arg = defaults(this.options(defaultsObj));

      runTask(arg, framework, done);
    });
  });
};
<commit_msg>fixed task declaration, because it was broken for YUI tests.<commit_after>module.exports = function(grunt) {
  var _ = require('lodash'),
    request = require('request'),
    SauceTunnel = require('sauce-tunnel'),
    Q = require('q'),
    rqst = request.defaults({
      jar: false
    });

  //these result parsers return true if the tests all passed
  var resultParsers = {
    jasmine: function(result){
      return result.passed;
    },
    qunit: function(result){
      if (result.passed === undefined){ return undefined; }
      return result.passed == result.total;
    },
    mocha: function(result){
      if (result.passes === undefined){ return undefined; }
      return result.failures === 0;
    },
    'YUI Test': function(result){
      if (result.passed === undefined){ return undefined; }
      return result.passed == result.total;
    },
    custom: function(result){
      if (result.passed === undefined){ return undefined; }
      return result.failed === 0;
    }
  };

  var TestResult = function(jobId, user, key, framework, testInterval){
    var url = 'https://saucelabs.com/rest/v1/' + user + '/js-tests/status';
    var deferred = Q.defer();

    var requestParams = {
      method: 'post',
      url: url,
      auth: {
        user: user,
        pass: key
      },
      json: true,
      body: {
        "js tests": [jobId]
      }
    };

    var checkStatus = function(){

      rqst(requestParams, function(error, response, body){

        if (error){
          deferred.resolve({
            passed: undefined,
            result: {
              message: "Error connecting to api to get test status: " + error.toString()
            }
          });
          return;
        }

        var testInfo = body['js tests'][0];

        if (testInfo.status == "test error"){
          deferred.resolve({
            passed: undefined,
            result: {
              message: "Test Error"
            }
          });
          return;
        }

        if (!body.completed){
          setTimeout(checkStatus ,testInterval);
        } else {
          testInfo.passed = testInfo.result ? resultParsers[framework](testInfo.result) : false;
          deferred.resolve(testInfo);
        }

      });
    };

    checkStatus();

    return deferred.promise;
  };

  var TestRunner = function(user, key, testInterval) {
    this.user = user;
    this.key = key;
    this.url = 'https://saucelabs.com/rest/v1/' + this.user + '/js-tests';
    this.testInterval = testInterval;
    this.results = [];
  };

  TestRunner.prototype.runTests = function(browsers, urls, framework, tunnelIdentifier, testname, tags, build, onTestComplete, callback){

    var me = this;
    var numberOfJobs = browsers.length * urls.length;

    var addResultPromise = function(promise){
      me.results.push(promise);
      grunt.log.writeln(me.results.length, "/", numberOfJobs, 'tests started');
      if (me.results.length == numberOfJobs){

        Q.all(me.results).then(function(results){
          results = results.map(function(result){
            return result.valueOf().passed;
          });

          callback(results);
        });
      }
    };

    urls.forEach(function(url){
      me.runTest(browsers, url, framework, tunnelIdentifier, testname, tags, build, function(taskIds){

        taskIds.forEach(function(taskId){
          var resultPromise = new TestResult(taskId, me.user, me.key, framework, me.testInterval);
          addResultPromise(resultPromise);
          resultPromise.then(function(result){

            var alteredResult = onTestComplete(result);
            if (alteredResult !== undefined){
              result.passed = alteredResult;
            }

            grunt.log.subhead("\nTested %s", url);
            grunt.log.writeln("Platform: %s", result.platform);

            if (tunnelIdentifier && unsupportedPort(url)) {
              grunt.log.writeln("Warning: This url might use a port that is not proxied by Sauce Connect.".yellow);
            }

            if (result.passed === undefined){
              grunt.log.error(result.result.message);
            } else {
              grunt.log.writeln("Passed: %s", result.passed);
            }
            grunt.log.writeln("Url %s", result.url);

          }, function(e){
            grunt.log.error('some error? %s', e);
          });
        });
      });
    });
  };

  TestRunner.prototype.runTest = function(browsers, url, framework, tunnelIdentifier, testname, tags, build, callback){

    var parsePlatforms = function(browsers){
      return browsers.map(function(browser){
        return [browser.platform || "", browser.browserName || "", browser.version || ""];
      });
    };

    var requestParams = {
      method: 'post',
      url: this.url,
      auth: {
        user: this.user,
        pass: this.key
      },
      json: true,
      body: {
        platforms: parsePlatforms(browsers),
        url: url,
        framework: framework,
        name: testname,
        tags: tags,
        build: build
      }
    };

    if (tunnelIdentifier){
      requestParams.body.tunnel = "tunnel-identifier:" + tunnelIdentifier;
    }

    rqst(requestParams, function(error, response, body){

      if (error){
        grunt.log.error("Could not connect to Sauce Labs api: %s", error);
        throw error;
      }

      if (!body['js tests'] || !body['js tests'].length){
          grunt.log.error('Error starting tests through Sauce API: %s', JSON.stringify(body));
          throw new Error('Could not start tests through Sauce API');
      }

      callback(body['js tests']);

    });
  };

  var defaultsObj = {
    username: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
    identifier: Math.floor((new Date()).getTime() / 1000 - 1230768000).toString(),
    tunneled: true,
    tunnelTimeout: 120,
    testInterval: 1000 * 5,
    testReadyTimeout: 1000 * 5,
    onTestComplete: function() {

    },
    testname: "",
    tags: [],
    browsers: [{}]
  };

  function defaults(data) {
    var result = data;
    result.pages = result.url || result.urls;
    if (!_.isArray(result.pages)) {
      result.pages = [result.pages];
    }

    return result;
  }

  function configureLogEvents(tunnel) {
    var methods = ['write', 'writeln', 'error', 'ok', 'debug'];
    methods.forEach(function (method) {
      tunnel.on('log:'+method, function (text) {
        grunt.log[method](text);
      });
      tunnel.on('verbose:'+method, function (text) {
        grunt.verbose[method](text);
      });
    });
  }

  function runTask(arg, framework, callback){

    var test = new TestRunner(arg.username, arg.key, arg.testInterval);

    if (arg.tunneled){
      var tunnel = new SauceTunnel(arg.username, arg.key, arg.identifier, arg.tunneled, arg.tunnelTimeout);
      grunt.log.writeln("=> Starting Tunnel to Sauce Labs".inverse.bold);
      configureLogEvents(tunnel);

      tunnel.start(function(isCreated) {
        if (!isCreated) {
          grunt.log.error("Could not create tunnel to Sauce Labs");
          callback(false);
          return;
        }
        grunt.log.ok("Connected to Saucelabs");

        test.runTests(arg.browsers, arg.pages, framework, arg.identifier, arg.testname, arg.tags, arg.build, arg.onTestComplete, function(status){
          status = status.every(function(passed){ return passed; });
          grunt.log[status ? 'ok' : 'error']("All tests completed with status %s", status);
          grunt.log.writeln("=> Stopping Tunnel to Sauce Labs".inverse.bold);
          tunnel.stop(function() {
            callback(status);
          });
        });
      });

    } else {
      test.runTests(arg.browsers, arg.pages, framework, null, arg.testname, arg.tags, arg.build, arg.onTestComplete, function(status){
        status = status.every(function(passed){ return passed; });
        grunt.log[status ? 'ok' : 'error']("All tests completed with status %s", status);
        callback(status);
      });
    }
  }

  function unsupportedPort(url) {
    // Not all ports are proxied by Sauce Connect. List of supported ports is
    // available at https://saucelabs.com/docs/connect#localhost
    var portRegExp = /:(\d+)\//;
    var matches = portRegExp.exec(url);
    var port = matches ? parseInt(matches[1], 10) : null;
    var supportedPorts = [80, 443, 888, 2000, 2001, 2020, 2109, 2222, 2310, 3000, 3001, 3030,
      3210, 3333, 4000, 4001, 4040, 4321, 4502, 4503, 4567, 5000, 5001, 5050, 5555, 5432, 6000,
      6001, 6060, 6666, 6543, 7000, 7070, 7774, 7777, 8000, 8001, 8003, 8031, 8080, 8081, 8765,
      8888, 9000, 9001, 9080, 9090, 9876, 9877, 9999, 49221, 55001];

    if (port) {
      return supportedPorts.indexOf(port) === -1;
    }

    return false;
  }

  grunt.registerMultiTask('saucelabs-jasmine', 'Run Jasmine test cases using Sauce Labs browsers', function() {
    var done = this.async(),
      arg = defaults(this.options(defaultsObj));

    runTask(arg, 'jasmine', done);

  });

  grunt.registerMultiTask('saucelabs-qunit', 'Run Qunit test cases using Sauce Labs browsers', function() {
    var done = this.async(),
      arg = defaults(this.options(defaultsObj));

    runTask(arg, 'qunit', done);

  });

  grunt.registerMultiTask('saucelabs-yui', 'Run YUI test cases using Sauce Labs browsers', function() {
    var done = this.async(),
    arg = defaults(this.options(defaultsObj));

    runTask(arg, 'YUI Test', done);

  });

  grunt.registerMultiTask('saucelabs-mocha', 'Run Mocha test cases using Sauce Labs browsers', function() {
    var done = this.async(),
      arg = defaults(this.options(defaultsObj));

    runTask(arg, 'mocha', done);

  });

  grunt.registerMultiTask('saucelabs-custom', 'Run custom test cases using Sauce Labs browsers', function() {
    var done = this.async(),
      arg = defaults(this.options(defaultsObj));

    runTask(arg, 'custom', done);

  });
};
<|endoftext|>


<commit_before>var taskPlatformAdapterPlatform = {
    validate: function(mode, success, error) {
        $('#validateOk').show();
    },
    getTaskParams: function(key, defaultValue, success, error) {
        var res = {'minScore': 0, 'maxScore': 100, 'noScore': 0, 'readOnly': true, 'randomSeed': "0", 'options': {}}; // TODO :: randomSeed
        if(key && key in res) {
            res = res[key];
        } else if(key) {
            res = defaultValue;
        }
        if(success) {
            success(res);
        } else {
            return res;
        }},
    askHint: function(hint, success, error) {
        success();
    },
    updateDisplay: function(params, success, error) {
        success();
    }
};

platform.setPlatform(taskPlatformAdapterPlatform);
$(function () {
    task.load(null, function () {
        var source = window.parent.adapterApi.getSource();
        task.reloadAnswerObject({'easy': [{'blockly': source.sourceCode}]});

        setTimeout(function() {
            $('.contentCentered').hide();
            $('#submitBtn').hide();
            $('#displayHelperAnswering').hide();
            }, 0);
        });

        var updateHeight = null;
        updateHeight = function() {
            window.parent.adapterApi.setHeight($('body').outerHeight(true));
            setTimeout(updateHeight, 1000);
        };
        updateHeight();
        setTimeout(function() {
            task.displayedSubTask.run(function() {
                if(task.displayedSubTask.context.success) {
                    $('#validateOk').show();
                }
                });
        }, 1000);
});

if(window.Blockly) {
  Blockly.JavaScript['input_num'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'parseInt(readStdin())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_next'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    var stdinBuffer = stdinBuffer.substr(re.lastIndex);\n"
                                                  + "    return w;\n"
                                                  + "};";
    var code = 'parseInt(input_word())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_char'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_char'] = "function input_char() {\n"
                                                  + "    var buf = readStdin();\n";
                                                  + "    stdinBuffer = stdinBuffer.substr(1);\n";
                                                  + "    return buf.substr(0, 1);\n";
                                                  + "};\n";
    var code = 'input_char()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_word'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    var stdinBuffer = stdinBuffer.substr(re.lastIndex);\n"
                                                  + "    return w;\n"
                                                  + "};";
    var code = 'input_word()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_line'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'readStdin()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_list'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_num_list'] = "function input_num_list() {\n"
                                                      + "    var parts = readStdin().split(/\\s+/);\n"
                                                      + "    for(var i=0; i<parts.length; i++) {\n"
                                                      + "        parts[i] = parseInt(parts[i]);\n"
                                                      + "    }\n"
                                                      + "    return parts;\n"
                                                      + "};";
    var code = 'input_num_list()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['text_print'] = function(block) {
    return "print(" + (Blockly.JavaScript.valueToCode(block, "TEXT", Blockly.JavaScript.ORDER_NONE) || "''") + ");\n";
  };
  Blockly.JavaScript['text_print_noend'] = Blockly.JavaScript['text_print'];
}
<commit_msg>quickAlgo: Fix regexp execution<commit_after>var taskPlatformAdapterPlatform = {
    validate: function(mode, success, error) {
        $('#validateOk').show();
    },
    getTaskParams: function(key, defaultValue, success, error) {
        var res = {'minScore': 0, 'maxScore': 100, 'noScore': 0, 'readOnly': true, 'randomSeed': "0", 'options': {}}; // TODO :: randomSeed
        if(key && key in res) {
            res = res[key];
        } else if(key) {
            res = defaultValue;
        }
        if(success) {
            success(res);
        } else {
            return res;
        }},
    askHint: function(hint, success, error) {
        success();
    },
    updateDisplay: function(params, success, error) {
        success();
    }
};

platform.setPlatform(taskPlatformAdapterPlatform);
$(function () {
    task.load(null, function () {
        var source = window.parent.adapterApi.getSource();
        task.reloadAnswerObject({'easy': [{'blockly': source.sourceCode}]});

        setTimeout(function() {
            $('.contentCentered').hide();
            $('#submitBtn').hide();
            $('#displayHelperAnswering').hide();
            }, 0);
        });

        var updateHeight = null;
        updateHeight = function() {
            window.parent.adapterApi.setHeight($('body').outerHeight(true));
            setTimeout(updateHeight, 1000);
        };
        updateHeight();
        setTimeout(function() {
            task.displayedSubTask.run(function() {
                if(task.displayedSubTask.context.success) {
                    $('#validateOk').show();
                }
                });
        }, 1000);
});

if(window.Blockly) {
  Blockly.JavaScript['input_num'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'parseInt(readStdin())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_next'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    stdinBuffer = stdinBuffer.substr(w[0].length);\n"
                                                  + "    return w[0];\n"
                                                  + "};";
    var code = 'parseInt(input_word())';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_char'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_char'] = "function input_char() {\n"
                                                  + "    var buf = readStdin();\n";
                                                  + "    stdinBuffer = buf.substr(1);\n";
                                                  + "    return buf.substr(0, 1);\n";
                                                  + "};\n";
    var code = 'input_char()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_word'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_word'] = "function input_word() {\n"
                                                  + "    while (!stdinBuffer || stdinBuffer.trim() == '')\n"
                                                  + "        stdinBuffer = readStdin();\n"
                                                  + "    if (typeof stdinBuffer === 'undefined')\n"
                                                  + "        stdinBuffer = '';\n"
                                                  + "    var re = /\\S+\\s*/;\n"
                                                  + "    var w = re.exec(stdinBuffer);\n"
                                                  + "    stdinBuffer = stdinBuffer.substr(w[0].length);\n"
                                                  + "    return w[0];\n"
                                                  + "};";
    var code = 'input_word()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_line'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    var code = 'readStdin()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['input_num_list'] = function(block) {
    Blockly.JavaScript.definitions_['input_funcs'] = "var stdinBuffer = '';\n"
                                                   + "function readStdin() {\n"
                                                   + "    if (stdinBuffer == '')\n"
                                                   + "        return input();\n"
                                                   + "    if (typeof stdinBuffer === 'undefined')\n"
                                                   + "        stdinBuffer = '';\n"
                                                   + "    return stdinBuffer;\n"
                                                   + "};";
    Blockly.JavaScript.definitions_['input_num_list'] = "function input_num_list() {\n"
                                                      + "    var parts = readStdin().split(/\\s+/);\n"
                                                      + "    for(var i=0; i<parts.length; i++) {\n"
                                                      + "        parts[i] = parseInt(parts[i]);\n"
                                                      + "    }\n"
                                                      + "    return parts;\n"
                                                      + "};";
    var code = 'input_num_list()';
    return [code, Blockly.JavaScript.ORDER_ATOMIC];
  };

  Blockly.JavaScript['text_print'] = function(block) {
    return "print(" + (Blockly.JavaScript.valueToCode(block, "TEXT", Blockly.JavaScript.ORDER_NONE) || "''") + ");\n";
  };
  Blockly.JavaScript['text_print_noend'] = Blockly.JavaScript['text_print'];
}
<|endoftext|>


<commit_before>const assert = require('assert');

// These tests require the controller & router tests
if (!global.queued_controller) {
	require('./25-controller.js');
}

if (!global.queued_router) {
	require('./30-router.js');
}

describe('Helper.Alchemy', function() {

	describe('#getResource()', function() {

		it('should throw an error when called without a conduit', function(next) {
			alchemy.hawkejs.render('static/viewcontent', {}, function rendered(err, res) {

				try {
					assert.strictEqual(!!err, true);
				} catch (err) {
					return next(err);
				}

				if (err.message.indexOf('Unable to find template') > -1) {
					return next(err);
				}

				next();
			});
		});

		it('should render correctly on the server', function(next) {

			let url = global.getRouteUrl('Static#viewContent');

			if (!String(url).endsWith('viewcontent')) {
				return next(new Error('The Static#viewContent url was not found'));
			}

			Blast.fetch(url, function gotResponse(err, res, body) {

				if (err) {
					return next(err);
				}

				let has_name = body.indexOf('SCT:{"name":"Roel"}') > -1;

				assert.strictEqual(has_name, true, 'The expected resource')

				next();
			});
		});

		it('should render correctly in the browser', async function() {

			let url = global.getRouteUrl('Rendertest', {view: 'test', name: 'Roel'});

			await setLocation(url);

			let body = await global.getBodyHtml();

			let has_name = body.indexOf('SCT:{"name":"Roel"}') > -1;

			assert.strictEqual(has_name, false, 'The wrong view has been rendered');

			let route_info = await global.evalPage(function() {
				return hawkejs.scene.helpers.Router.routeUrl('Static#viewContent') + '';
			});

			assert.strictEqual(route_info, '/viewcontent', 'The route could not be found on the client side');

			let navresult = await global.evalPage(async function() {
				// @TODO: this doesn't seem to work?
				await alchemy.openUrl('Static#viewContent');

				return document.location.pathname;
			});

			assert.strictEqual(navresult, '/viewcontent', 'The browser did not navigate to the correct page');

			body = await global.getBodyHtml();

			// Leave the trailing curly brace off, because it might add a `hajax` parameter too
			has_name = body.indexOf('SCT:{"name":"Roel"') > -1;

			assert.strictEqual(has_name, true, 'The client-side render did not produce the expected result');
		});
	});

	describe('#segment(route)', function() {
		it('should render a route', async function() {

			let url = global.getRouteUrl('Static#view', {view: 'segment_test'});

			alchemy.settings.debug = true;

			await setLocation(url);

			let ids = await global.evalPage(function() {

				let elements = document.querySelectorAll('[data-hid]'),
				    element,
				    ids = [],
				    i;

				for (i = 0; i < elements.length; i++) {
					element = elements[i];

					ids.push(element.dataset.hid);
				}

				ids.sort();

				return ids;
			});

			alchemy.settings.debug = false;

			let expected_ids = [
				'hserverside-0',
				'hserverside-1',
				'hserverside-2',
				'hserverside-3',
				'hserverside-4',
				'hserverside-5',
				'hserverside-6',
				'hserverside-7',
				'hserverside-8',
				'hserverside-9'
			];

			assert.deepStrictEqual(ids, expected_ids);
		});
	});

});

describe('Helper.Router', function() {

	describe('#applyDirective', function() {
		it('is used as a directive in Hawkejs templates', function(done) {

			var template = `<a !Router="APIResource" #route_action="test"></a>`;

			var compiled = alchemy.hawkejs.compile({
				template_name: 'test_router',
				template: template,
				throw_error: true
			});

			alchemy.hawkejs.render(compiled, {}, function rendered(err, res) {

				if (err) {
					return next(err);
				}

				assert.strictEqual(res, `<a href="/api/test"></a>`);
				done();
			});

		});
	});
});<commit_msg>Fix helper unit test<commit_after>const assert = require('assert');

// These tests require the controller & router tests
if (!global.queued_controller) {
	require('./25-controller.js');
}

if (!global.queued_router) {
	require('./30-router.js');
}

describe('Helper.Alchemy', function() {

	describe('#getResource()', function() {

		it('should throw an error when called without a conduit', function(next) {

			alchemy.hawkejs.render('static/viewcontent', {}, function rendered(err, res) {

				if (err) {
					return next(err);
				}

				let has_error = res.indexOf('Could not find conduit, alchemy resource will not be fetched') > -1;

				if (!has_error) {
					return next(new Error('Hawkejs should have printed an error in the html'));
				}

				next();
			});
		});

		it('should render correctly on the server', function(next) {

			let url = global.getRouteUrl('Static#viewContent');

			if (!String(url).endsWith('viewcontent')) {
				return next(new Error('The Static#viewContent url was not found'));
			}

			Blast.fetch(url, function gotResponse(err, res, body) {

				if (err) {
					return next(err);
				}

				let has_name = body.indexOf('SCT:{"name":"Roel"}') > -1;

				assert.strictEqual(has_name, true, 'The expected resource')

				next();
			});
		});

		it('should render correctly in the browser', async function() {

			let url = global.getRouteUrl('Rendertest', {view: 'test', name: 'Roel'});

			await setLocation(url);

			let body = await global.getBodyHtml();

			let has_name = body.indexOf('SCT:{"name":"Roel"}') > -1;

			assert.strictEqual(has_name, false, 'The wrong view has been rendered');

			let route_info = await global.evalPage(function() {
				return hawkejs.scene.helpers.Router.routeUrl('Static#viewContent') + '';
			});

			assert.strictEqual(route_info, '/viewcontent', 'The route could not be found on the client side');

			let navresult = await global.evalPage(async function() {
				// @TODO: this doesn't seem to work?
				await alchemy.openUrl('Static#viewContent');

				return document.location.pathname;
			});

			assert.strictEqual(navresult, '/viewcontent', 'The browser did not navigate to the correct page');

			body = await global.getBodyHtml();

			// Leave the trailing curly brace off, because it might add a `hajax` parameter too
			has_name = body.indexOf('SCT:{"name":"Roel"') > -1;

			assert.strictEqual(has_name, true, 'The client-side render did not produce the expected result');
		});
	});

	describe('#segment(route)', function() {
		it('should render a route', async function() {

			let url = global.getRouteUrl('Static#view', {view: 'segment_test'});

			alchemy.settings.debug = true;

			await setLocation(url);

			let ids = await global.evalPage(function() {

				let elements = document.querySelectorAll('[data-hid]'),
				    element,
				    ids = [],
				    i;

				for (i = 0; i < elements.length; i++) {
					element = elements[i];

					ids.push(element.dataset.hid);
				}

				ids.sort();

				return ids;
			});

			alchemy.settings.debug = false;

			let expected_ids = [
				'hserverside-0',
				'hserverside-1',
				'hserverside-2',
				'hserverside-3',
				'hserverside-4',
				'hserverside-5',
				'hserverside-6',
				'hserverside-7',
				'hserverside-8',
				'hserverside-9'
			];

			assert.deepStrictEqual(ids, expected_ids);
		});
	});

});

describe('Helper.Router', function() {

	describe('#applyDirective', function() {
		it('is used as a directive in Hawkejs templates', function(done) {

			var template = `<a !Router="APIResource" #route_action="test"></a>`;

			var compiled = alchemy.hawkejs.compile({
				template_name: 'test_router',
				template: template,
				throw_error: true
			});

			alchemy.hawkejs.render(compiled, {}, function rendered(err, res) {

				if (err) {
					return next(err);
				}

				assert.strictEqual(res, `<a href="/api/test"></a>`);
				done();
			});

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


<commit_before>import File from '../lib/File';

import NexmoStub from './NexmoStub';

var fileAPIs = {
    'getFile': 'get'
};

describe('File Object', function() {

    it('should implement all v1 APIs', function() {
        NexmoStub.checkAllFunctionsAreDefined(fileAPIs, File);
    });

    it('should proxy the function call to the underlying `nexmo` object', function() {
        NexmoStub.checkAllFunctionsAreCalled(fileAPIs, File);
    });
});
<commit_msg>Update test to load correct file<commit_after>import FilesResource from '../lib/FilesResource';

import NexmoStub from './NexmoStub';

var fileAPIs = {
    'getFile': 'get'
};

describe('FilesResource Object', function() {

    it('should implement all v1 APIs', function() {
        NexmoStub.checkAllFunctionsAreDefined(fileAPIs, FilesResource);
    });

    it('should proxy the function call to the underlying `nexmo` object', function() {
        NexmoStub.checkAllFunctionsAreCalled(fileAPIs, FilesResource);
    });
});
<|endoftext|>


<commit_before>var should = require('should');
var hottap = require('hottap').hottap;
var _ = require('underscore');
var Percolator = require('../index').Percolator;
var port = 9000;
var server;

describe('Percolator', function(){
  describe("when parseBody is false", function(){
    beforeEach(function(done){
      server = new Percolator({port : port});
      server.listen(done);
    });
    afterEach(function(done){
      server.close(done);
    });

    it("has default error handlers for 404s", function(done){
        var that = this;
        var url = "http://localhost:" + port + "/DOES_NOT_EXIST";
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("GET",
                                 function(err, response){
                                   response.status.should.equal(404);
                                   JSON.parse(response.body).error.type.should.equal(404);
                                   should.not.exist(err);
                                   done();
                                 });
    });
    it("has default error handlers for 405s", function(done){
        var that = this;
        var url = "http://localhost:" + port + "/";
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("DELETE",
                                 function(err, response){
                                   response.status.should.equal(405);
                                   JSON.parse(response.body).error.type.should.equal(405);
                                   should.not.exist(err);
                                   done();
                                 });
    });
    it("has default error handlers for 501s", function(done){
        var that = this;
        var url = "http://localhost:" + port + "/";
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("TRACE",
                                 function(err, response){
                                   response.status.should.equal(501);
                                   JSON.parse(response.body).error.type.should.equal(501);
                                   should.not.exist(err);
                                   done();
                                 });
    });
    it("has a default error handler for 414s", function(done){
        var that = this;
        var bigpath = "1";
        _.times(4097, function(){bigpath += '1';});
        var url = "http://localhost:" + port + "/" + bigpath;
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("GET",
                                 function(err, response){
                                   response.status.should.equal(414);
                                   JSON.parse(response.body).error.type.should.equal(414);
                                   should.not.exist(err);
                                   done();
                                 });
    });

    it ("exposes a before hook for executing logic before requests", function(done){
      var that = this;
      var url = "http://localhost:" + port + "/";
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World! " + req.decorated);
                                             }});
      server.before(function(req, res, handler, cb){
        req.url.should.equal('/');
        req.decorated = true;
        cb(req, res);
      });
        hottap(url).request("GET",
                                 function(err, response){
                                   response.status.should.equal(200);
                                   response.body.should.equal("Hello World! true");
                                   done();
                                 });
    });

    it ("exposes an after hook for executing logic after requests", function(done){
      var that = this;
      var responded = false;
      var url = "http://localhost:" + port + "/";
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
      server.after(function(req, res){
        req.url.should.equal('/');
        done();
      });
        hottap(url).request("GET",
                                 function(err, response){
                                   responded = true;
                                   response.status.should.equal(200);
                                   response.body.should.equal("Hello World!");
                                 });
    });

    it ("can respond to simple requests", function(done){
      var that = this;
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + server.port + "/";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    done();
                                 });
    });

    it ("passes options on to the req's 'app' namespace", function(done){
      server.route('/', {  GET : function(req, res){
                                               should.exist(req.app);
                                               req.app.port.should.equal(port);
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    done();
                                 });
    });

    it ("adds a router reference to every req", function(done){
        server.route('/', {  GET : function(req, res){
                                                 should.exist(req.router);
                                                 res.end("added router!");
                                               }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    response.body.should.equal('added router!');
                                    done();
                                 });
    });

    it ("HEAD for a GET-only resource returns the same headers, blank resource", function(done){
      server.route('/', {  GET : function(req, res){
                                         res.setHeader('Content-Type', 'text/plain');
                                         res.end('yo yo yo');
                                       }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("HEAD",
                                 function(err, response){
                                   if (err) {
                                     throw err;
                                   }
                                   response.headers['content-type'].should.equal('text/plain');
                                   response.body.should.equal("");
                                   response.status.should.equal(204);
                                   done();
                                 });
    });

    it ("OPTIONS for a GET-only resource returns, GET, HEAD, OPTIONS", function(done){
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("OPTIONS",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    var body = JSON.parse(response.body);
                                    body['allowed methods'].should.eql(["OPTIONS","HEAD","GET"]);
                                    response.headers.allow.should.equal('OPTIONS,HEAD,GET');
                                    response.status.should.equal(200);
                                    done();
                                 });
    });

    describe('when managing a text/plain body', function(){
      it ("parsed body gets added to the req", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    POST : function(req, res){
                                      req.onBody(function(err, body){
                                        body.should.equal('wakka wakka wakka');
                                        res.end("Hello World!");
                                      });
                                    }});
          hottap("http://localhost:" + port + "/").request("POST",
                                                   {"content-type":"text/plain"},
                                                   'wakka wakka wakka',
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(200);
                                                      response.body.should.equal("Hello World!");
                                                      done();
                                                   });
      });
    });
  });

  describe("when staticDir is set", function(){
    beforeEach(function(done){
      var staticDir = __dirname + '/test_fixtures/static';
      server = new Percolator({port : port, staticDir : staticDir});
      server.listen(done);
    });
    afterEach(function(done){
      server.close(done);
    });
    // pending due to static resource use
    it ("can respond to static requests", function(done){
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + server.port + "/static.txt";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    response.body.should.equal("Yep.\n");
                                    done();
                                 });
    });
  });

  describe("when staticDir is set to a non-existant dir", function(){
    afterEach(function(done){
      server.close(done);
    });
    it ("returns an error.", function(done){
      var staticDir = __dirname + '/test_fixtures/NO_EXIST';
      server = new Percolator({port : port, staticDir : staticDir});
      server.listen(function(err){
        if (err) {
          err.should.equal("Your staticDir path could not be found.");
          done();
        }
      });
    });
  });

  describe("when parseBody is true", function(){
    beforeEach(function(done){
      server = new Percolator({port : port, parseBody : true});
      server.listen(done);
    });
    afterEach(function(done){
      server.close(done);
    });
    describe('when managing a json body', function(){
      it ("parsed body gets added to the req", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      req.body.thisisa.should.equal('TEST');
                                      req.rawBody.should.equal('{"thisisa":"TEST"}');
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {"content-type":"application/json"},
                                                   '{"thisisa":"TEST"}',
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(200);
                                                      response.body.should.equal("Hello World!");
                                                      done();
                                                   });
      });
      it ("responds 415 when Content-Type is unsupported", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {"content-type":"application/whatwhat"},
                                                   "",
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(415);
                                                      var parsed = JSON.parse(response.body);
                                                      parsed.error.type.should.equal(415);
                                                      parsed.error.message
                                                                .should.equal("Unsupported Media Type");
                                                      parsed.error.detail
                                                                .should.equal("application/whatwhat");
                                                      done();
                                                   });
      });
      it ("responds 415 when Content-Type is missing on PUT", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {},
                                                   "",
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(415);
                                                      var parsed = JSON.parse(response.body);
                                                      parsed.error.type.should.equal(415);
                                                      parsed.error.message
                                                                .should.equal("Unsupported Media Type");
                                                      parsed.error.detail
                                                                .should.equal("None provided.");
                                                      done();
                                                   });
      });
      it ("responds 400 when Content-Type is json, but body doesn't contain JSON", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {'Content-Type' : 'application/json'},
                                                   "hey wait a minute. this isn't json",
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(400);
                                                      var parsed = JSON.parse(response.body);
                                                      parsed.error.type.should.equal(400);
                                                      parsed.error.message
                                                                .should.equal("Bad Request");
                                                      parsed.error.detail
                                                                .should.match(/^Parse Error/);
                                                      done();
                                                   });
      });
    });

  });
});
<commit_msg>test json parsing with onJson.<commit_after>var should = require('should');
var hottap = require('hottap').hottap;
var _ = require('underscore');
var Percolator = require('../index').Percolator;
var port = 9000;
var server;

describe('Percolator', function(){
  describe("when parseBody is false", function(){
    beforeEach(function(done){
      server = new Percolator({port : port});
      server.listen(done);
    });
    afterEach(function(done){
      server.close(done);
    });

    it("has default error handlers for 404s", function(done){
        var that = this;
        var url = "http://localhost:" + port + "/DOES_NOT_EXIST";
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("GET",
                                 function(err, response){
                                   response.status.should.equal(404);
                                   JSON.parse(response.body).error.type.should.equal(404);
                                   should.not.exist(err);
                                   done();
                                 });
    });
    it("has default error handlers for 405s", function(done){
        var that = this;
        var url = "http://localhost:" + port + "/";
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("DELETE",
                                 function(err, response){
                                   response.status.should.equal(405);
                                   JSON.parse(response.body).error.type.should.equal(405);
                                   should.not.exist(err);
                                   done();
                                 });
    });
    it("has default error handlers for 501s", function(done){
        var that = this;
        var url = "http://localhost:" + port + "/";
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("TRACE",
                                 function(err, response){
                                   response.status.should.equal(501);
                                   JSON.parse(response.body).error.type.should.equal(501);
                                   should.not.exist(err);
                                   done();
                                 });
    });
    it("has a default error handler for 414s", function(done){
        var that = this;
        var bigpath = "1";
        _.times(4097, function(){bigpath += '1';});
        var url = "http://localhost:" + port + "/" + bigpath;
        server.route('/', {  GET : function(req, res){
                                                 res.end("Hello World!");
                                               }});
        hottap(url).request("GET",
                                 function(err, response){
                                   response.status.should.equal(414);
                                   JSON.parse(response.body).error.type.should.equal(414);
                                   should.not.exist(err);
                                   done();
                                 });
    });

    it ("exposes a before hook for executing logic before requests", function(done){
      var that = this;
      var url = "http://localhost:" + port + "/";
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World! " + req.decorated);
                                             }});
      server.before(function(req, res, handler, cb){
        req.url.should.equal('/');
        req.decorated = true;
        cb(req, res);
      });
        hottap(url).request("GET",
                                 function(err, response){
                                   response.status.should.equal(200);
                                   response.body.should.equal("Hello World! true");
                                   done();
                                 });
    });

    it ("exposes an after hook for executing logic after requests", function(done){
      var that = this;
      var responded = false;
      var url = "http://localhost:" + port + "/";
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
      server.after(function(req, res){
        req.url.should.equal('/');
        done();
      });
        hottap(url).request("GET",
                                 function(err, response){
                                   responded = true;
                                   response.status.should.equal(200);
                                   response.body.should.equal("Hello World!");
                                 });
    });

    it ("can respond to simple requests", function(done){
      var that = this;
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + server.port + "/";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    done();
                                 });
    });

    it ("passes options on to the req's 'app' namespace", function(done){
      server.route('/', {  GET : function(req, res){
                                               should.exist(req.app);
                                               req.app.port.should.equal(port);
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    done();
                                 });
    });

    it ("adds a router reference to every req", function(done){
        server.route('/', {  GET : function(req, res){
                                                 should.exist(req.router);
                                                 res.end("added router!");
                                               }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    response.body.should.equal('added router!');
                                    done();
                                 });
    });

    it ("HEAD for a GET-only resource returns the same headers, blank resource", function(done){
      server.route('/', {  GET : function(req, res){
                                         res.setHeader('Content-Type', 'text/plain');
                                         res.end('yo yo yo');
                                       }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("HEAD",
                                 function(err, response){
                                   if (err) {
                                     throw err;
                                   }
                                   response.headers['content-type'].should.equal('text/plain');
                                   response.body.should.equal("");
                                   response.status.should.equal(204);
                                   done();
                                 });
    });

    it ("OPTIONS for a GET-only resource returns, GET, HEAD, OPTIONS", function(done){
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + port + "/";
        hottap(url).request("OPTIONS",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    var body = JSON.parse(response.body);
                                    body['allowed methods'].should.eql(["OPTIONS","HEAD","GET"]);
                                    response.headers.allow.should.equal('OPTIONS,HEAD,GET');
                                    response.status.should.equal(200);
                                    done();
                                 });
    });

    describe('when managing a text/plain body', function(){
      it ("parsed body gets returned in onBody", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    POST : function(req, res){
                                      req.onBody(function(err, body){
                                        body.should.equal('wakka wakka wakka');
                                        res.end("Hello World!");
                                      });
                                    }});
          hottap("http://localhost:" + port + "/").request("POST",
                                                   {"content-type":"text/plain"},
                                                   'wakka wakka wakka',
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(200);
                                                      response.body.should.equal("Hello World!");
                                                      done();
                                                   });
      });
    });
    describe('when managing an application/json body', function(){
      it ("parsed body gets returned in onJson", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    POST : function(req, res){
                                      req.onJson(function(err, body){
                                        should.exist(body.tests);
                                        should.exist(body.tests2);
                                        body.tests.length.should.equal(162);
                                        res.end("Hello World!");
                                      });
                                    }});
          var largerJson = {
            "tests" : [
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test"
            ],
            "tests2" : [
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test",
              "test", "test", "test", "test", "test", "test", "test", "test", "test"
            ],

          };
          hottap("http://localhost:" + port + "/").request("POST",
                                                   {"content-type":"application/json"},
                                                   JSON.stringify(largerJson),
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(200);
                                                      response.body.should.equal("Hello World!");
                                                      done();
                                                   });
      });
    });
  });

  describe("when staticDir is set", function(){
    beforeEach(function(done){
      var staticDir = __dirname + '/test_fixtures/static';
      server = new Percolator({port : port, staticDir : staticDir});
      server.listen(done);
    });
    afterEach(function(done){
      server.close(done);
    });
    // pending due to static resource use
    it ("can respond to static requests", function(done){
      server.route('/', {  GET : function(req, res){
                                               res.end("Hello World!");
                                             }});
        var url = "http://localhost:" + server.port + "/static.txt";
        hottap(url).request("GET",
                                 function(err, response){
                                    if (err) {
                                      throw err;
                                    }
                                    response.status.should.equal(200);
                                    response.body.should.equal("Yep.\n");
                                    done();
                                 });
    });
  });

  describe("when staticDir is set to a non-existant dir", function(){
    afterEach(function(done){
      server.close(done);
    });
    it ("returns an error.", function(done){
      var staticDir = __dirname + '/test_fixtures/NO_EXIST';
      server = new Percolator({port : port, staticDir : staticDir});
      server.listen(function(err){
        if (err) {
          err.should.equal("Your staticDir path could not be found.");
          done();
        }
      });
    });
  });

  describe("when parseBody is true", function(){
    beforeEach(function(done){
      server = new Percolator({port : port, parseBody : true});
      server.listen(done);
    });
    afterEach(function(done){
      server.close(done);
    });
    describe('when managing a json body', function(){
      it ("parsed body gets added to the req", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      req.body.thisisa.should.equal('TEST');
                                      req.rawBody.should.equal('{"thisisa":"TEST"}');
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {"content-type":"application/json"},
                                                   '{"thisisa":"TEST"}',
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(200);
                                                      response.body.should.equal("Hello World!");
                                                      done();
                                                   });
      });
      it ("responds 415 when Content-Type is unsupported", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {"content-type":"application/whatwhat"},
                                                   "",
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(415);
                                                      var parsed = JSON.parse(response.body);
                                                      parsed.error.type.should.equal(415);
                                                      parsed.error.message
                                                                .should.equal("Unsupported Media Type");
                                                      parsed.error.detail
                                                                .should.equal("application/whatwhat");
                                                      done();
                                                   });
      });
      it ("responds 415 when Content-Type is missing on PUT", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {},
                                                   "",
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(415);
                                                      var parsed = JSON.parse(response.body);
                                                      parsed.error.type.should.equal(415);
                                                      parsed.error.message
                                                                .should.equal("Unsupported Media Type");
                                                      parsed.error.detail
                                                                .should.equal("None provided.");
                                                      done();
                                                   });
      });
      it ("responds 400 when Content-Type is json, but body doesn't contain JSON", function(done){
        server.route('/', {  GET : function(req, res){
                                      res.end("Hello World!");
                                    },

                                    PUT : function(req, res){
                                      res.end("Hello World!");
                                    }});
          hottap("http://localhost:" + port + "/").request("PUT",
                                                   {'Content-Type' : 'application/json'},
                                                   "hey wait a minute. this isn't json",
                                                   function(err, response){
                                                      if (err) {
                                                        throw err;
                                                      }
                                                      response.status.should.equal(400);
                                                      var parsed = JSON.parse(response.body);
                                                      parsed.error.type.should.equal(400);
                                                      parsed.error.message
                                                                .should.equal("Bad Request");
                                                      parsed.error.detail
                                                                .should.match(/^Parse Error/);
                                                      done();
                                                   });
      });
    });

  });
});
<|endoftext|>


<commit_before>var PotOfEther = artifacts.require('./PotOfEther.sol');

contract('PotOfEther', accounts => {
  describe('createPot', () => {
    it('should fail when buyIn == 0', async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot('pot1', {
          from: accounts[0],
          value: 0
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty buyIn but didn't fail");
    });

    it('should fail when name.length == 0', async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot('', {
          from: accounts[0],
          value: 1000
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty name but didn't fail");
    });

    it('should emit LogPotCreated event', async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot('banana', {
        from: accounts[0],
        value: 1000
      });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[0].args.name, 'banana');
      assert.equal(result.logs[0].args.buyIn.valueOf(), 1000);
      assert.equal(result.logs[0].args.firstPlayer, accounts[0]);
    });

    it('should emit LogPotJoin event', async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot('papaya', {
        from: accounts[0],
        value: 1000
      });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[1].args.name, 'papaya');
      assert.equal(result.logs[1].args.newPlayer, accounts[0]);
    });
  })
});

<commit_msg>test error on 2 pots with same name<commit_after>var PotOfEther = artifacts.require('./PotOfEther.sol');

contract('PotOfEther', accounts => {
  describe('createPot', () => {
    it('should fail when buyIn == 0', async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot('banana', {
          from: accounts[0],
          value: 0
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty buyIn but didn't fail");
    });

    it('should fail when name.length == 0', async () => {
      var instance = await PotOfEther.new();

      try {
        await instance.createPot('', {
          from: accounts[0],
          value: 1000
        });
      } catch (err) {
        assert(true);
        return;
      }
      assert(false, "empty name but didn't fail");
    });

    it('should fail when name already exists', async () => {
      var instance = await PotOfEther.new();

      await instance.createPot('banana', {
        from: accounts[0],
        value: 1000
      });

      try {
        await instance.createPot('banana', {
          from: accounts[0],
          value: 1000
        });
      } catch (err) {
        assert(true);
        return;
      }

      assert(false, "two pots with same name but didn't fail");
    });

    it('should emit LogPotCreated event', async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot('banana', {
        from: accounts[0],
        value: 1000
      });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[0].args.name, 'banana');
      assert.equal(result.logs[0].args.buyIn.valueOf(), 1000);
      assert.equal(result.logs[0].args.firstPlayer, accounts[0]);
    });

    it('should emit LogPotJoin event', async () => {
      var instance = await PotOfEther.new();

      var result = await instance.createPot('banana', {
        from: accounts[0],
        value: 1000
      });

      assert.equal(result.logs.length, 2);
      assert.equal(result.logs[1].args.name, 'banana');
      assert.equal(result.logs[1].args.newPlayer, accounts[0]);
    });
  })
});

<|endoftext|>