<commit_before>'use strict';

var textToJSON, assert, stringify;

textToJSON = require('./');
assert = require('assert');
stringify = JSON.stringify;

describe('textToJSON', function () {
    it('should be a Function', function () {
        assert(typeof textToJSON === 'function');
    });
});

describe('Comments', function () {
    var customTokens;

    it('should strip line comments', function () {
        var data = textToJSON(
            '% This is a completely commented line.\n' +
            'unicorn'
        );

        assert(stringify(data) === '["unicorn"]');
    });

    it('should strip partial line comments', function () {
        var data = textToJSON(
            'unicorn % This is a partially commented line.'
        );

        assert(stringify(data) === '["unicorn"]');
    });

    it('should NOT strip comments when `comment` is `false`', function () {
        var data = textToJSON(
            'unicorn % This is a partially commented line.', {
                'comment': false
            }
        );

        assert(
            stringify(data) ===
            '["unicorn % This is a partially commented line."]'
        );
    });

    customTokens = {
        'comment': '#'
    };

    it('should strip line comments based on a given token', function () {
        var data = textToJSON(
            '# This is a completely commented line.\n' +
            'unicorn',
            customTokens
        );

        assert(stringify(data) === '["unicorn"]');
    });

    it('should strip partial line comments based on a given token',
        function () {
            var data = textToJSON(
                'unicorn # This is a partially commented line.',
                customTokens
            );

            assert(stringify(data) === '["unicorn"]');
        }
    );
});

describe('White space', function () {
    it('should trim affixed white space', function () {
        var data = textToJSON('  \tunicorn');

        assert(stringify(data) === '["unicorn"]');
    });

    it('should trim suffixed white space', function () {
        var data = textToJSON('unicorn  \t');

        assert(stringify(data) === '["unicorn"]');
    });
});

describe('Empty lines', function () {
    it('should remove empty lines', function () {
        var data = textToJSON('\n\n\nunicorn\r\n');

        assert(stringify(data) === '["unicorn"]');
    });

    it('should remove empty (white space only) lines', function () {
        var data = textToJSON(
            '  \t  \n' +
            'unicorn'
        );

        assert(stringify(data) === '["unicorn"]');
    });
});

describe('End-of-file end-of-line', function () {
    it('should return the same result, with or without EOF EOL', function () {
        assert(stringify(textToJSON('unicorn')) === '["unicorn"]');
        assert(stringify(textToJSON('unicorn\n')) === '["unicorn"]');
        assert(stringify(textToJSON('unicorn\r\n')) === '["unicorn"]');
    });
});

describe('Property-value pairs', function () {
    it('should return an object when a file contains pair delimiters',
        function () {
            assert(
                stringify(textToJSON('unicorn : magic creature')) ===
                '{"unicorn":"magic creature"}'
            );

            assert(stringify(textToJSON(
                    'unicorn : magic creature\n' +
                    '\trainbow:double\t\n' +
                    'doge\t:\tso scare'
                )) === JSON.stringify({
                    'unicorn': 'magic creature',
                    'rainbow': 'double',
                    'doge': 'so scare'
                })
            );
        }
    );

    it('should return an object when a file contains pair delimiters ' +
        'based on a given token', function () {
            var customTokens = {
                'delimiter': '\t'
            };

            assert(
                stringify(
                    textToJSON('unicorn	magic creature', customTokens)
                ) === '{"unicorn":"magic creature"}'
            );

            assert(stringify(textToJSON(
                    'unicorn \t magic creature\n' +
                    '\trainbow\tdouble\t\n' +
                    'doge\t\t\tso scare',
                    customTokens
                )) === JSON.stringify({
                    'unicorn': 'magic creature',
                    'rainbow': 'double',
                    'doge': 'so scare'
                })
            );
        }
    );
});

describe('Values', function () {
    it('should return an array', function () {
        assert(stringify(textToJSON('unicorn')) === '["unicorn"]');

        assert(stringify(textToJSON(
                'unicorn \n' +
                ' doge\n' +
                '\trainbow\t'
            )) === JSON.stringify([
                'doge',
                'rainbow',
                'unicorn'
            ])
        );
    });
});

describe('Mixed property-value pairs and values', function () {
    it('should throw when both property-value pairs and values are provided',
        function () {
            assert.throws(function () {
                textToJSON('unicorn\nrainbow: double');
            }, /`rainbow/);
        }
    );
});

describe('Values', function () {
    it('should throw when duplicate values exist',
        function () {
            assert.throws(function () {
                textToJSON(
                    'unicorn\n' +
                    'doge\n' +
                    'unicorn\n'
                );
            }, /`unicorn/);
        }
    );

    it('should NOT throw when duplicate values exist and `forgiving` is ' +
        '`true`',
        function () {
            assert.doesNotThrow(function () {
                textToJSON(
                    'unicorn\n' +
                    'doge\n' +
                    'unicorn\n', {
                        'forgiving': true
                    }
                );
            });
        }
    );

    it('should log for duplicate values when `forgiving` is `true`',
        function () {
            var log,
                isCalled;

            log = console.log;

            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'unicorn\n' +
                'doge\n' +
                'unicorn\n', {
                    'forgiving': true
                }
            );

            assert(isCalled === true);

            global.console.log = log;
        }
    );

    it('should NOT log for duplicate keys when `forgiving` is `true`' +
        ' and `log` is `false`',
        function () {
            var log,
                isCalled;

            log = console.log;

            /* istanbul ignore next */
            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'unicorn\n' +
                'doge\n' +
                'unicorn\n', {
                    'forgiving': true,
                    'log': false
                }
            );

            assert(isCalled !== true);

            global.console.log = log;
        }
    );
});

describe('Property-value pairs', function () {
    it('should throw when duplicate keys exist',
        function () {
            assert.throws(function () {
                textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: double\n'
                );
            }, /`doge/);
        }
    );

    it('should NOT throw for duplicate keys when `forgiving` is `true`',
        function () {
            assert.doesNotThrow(function () {
                textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: so scare\n', {
                        'forgiving': true
                    }
                );
            });
        }
    );

    it('should log for duplicate keys when `forgiving` is `true`',
        function () {
            var log,
                isCalled;

            log = console.log;

            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': true
                }
            );

            assert(isCalled === true);

            global.console.log = log;
        }
    );

    it('should NOT log for duplicate keys when `forgiving` is `true`' +
        ' and `log` is `false`',
        function () {
            var log,
                isCalled;

            log = console.log;

            /* istanbul ignore next */
            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': true,
                    'log': false
                }
            );

            assert(isCalled !== true);

            global.console.log = log;
        }
    );

    it('should NOT throw when duplicate key-values exist when `forgiving` ' +
        'is `"fix"`',
        function () {
            assert.doesNotThrow(function () {
                textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: so scare\n', {
                        'forgiving': 'fix'
                    }
                );
            });
        }
    );

    it('should NOT throw when duplicate keys with different values exist ' +
        'when `forgiving` is `"fix"`',
        function () {
            assert.doesNotThrow(function () {
                var data;

                data = textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: rainbows\n', {
                        'forgiving': 'fix'
                    }
                );

                assert(stringify(data) === stringify({
                    'doge': 'rainbows',
                    'unicorn': 'magic creature'
                }));
            });
        }
    );

    it('should log for duplicate keys when `forgiving` is `"fix"`',
        function () {
            var log,
                isCalled;

            log = console.log;

            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': 'fix'
                }
            );

            assert(isCalled === true);

            global.console.log = log;
        }
    );

    it('should NOT log for duplicate keys when `forgiving` is `"fix"`' +
        ' and `log` is `false`',
        function () {
            var log,
                isCalled;

            log = console.log;

            /* istanbul ignore next */
            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': 'fix',
                    'log': false
                }
            );

            assert(isCalled !== true);

            global.console.log = log;
        }
    );
});
<commit_msg>Refactor test<commit_after>'use strict';

/**
 * Dependencies.
 */

var textToJSON,
    assert;

textToJSON = require('./');
assert = require('assert');

/**
 * Cached methods.
 */

var stringify;

stringify = JSON.stringify;

/**
 * Tests.
 */

describe('textToJSON', function () {
    it('should be a `function`', function () {
        assert(typeof textToJSON === 'function');
    });
});

describe('Comments', function () {
    it('should strip line comments', function () {
        var data;

        data = textToJSON(
            '% This is a completely commented line.\n' +
            'unicorn'
        );

        assert(stringify(data) === '["unicorn"]');
    });

    it('should strip partial line comments', function () {
        var data;

        data = textToJSON(
            'unicorn % This is a partially commented line.'
        );

        assert(stringify(data) === '["unicorn"]');
    });

    it('should NOT strip comments when `comment` is `false`', function () {
        var data;

        data = textToJSON(
            'unicorn % This is a partially commented line.', {
                'comment': false
            }
        );

        assert(
            stringify(data) ===
            '["unicorn % This is a partially commented line."]'
        );
    });

    it('should strip line comments based on a given token', function () {
        var data;

        data = textToJSON(
            '# This is a completely commented line.\n' +
            'unicorn', {
                'comment': '#'
            }
        );

        assert(stringify(data) === '["unicorn"]');
    });

    it('should strip partial line comments based on a given token',
        function () {
            var data;

            data = textToJSON(
                'unicorn # This is a partially commented line.', {
                    'comment': '#'
                }
            );

            assert(stringify(data) === '["unicorn"]');
        }
    );
});

describe('White space', function () {
    it('should trim affixed white space', function () {
        var data;

        data = textToJSON('  \tunicorn');

        assert(stringify(data) === '["unicorn"]');
    });

    it('should trim suffixed white space', function () {
        var data;

        data = textToJSON('unicorn  \t');

        assert(stringify(data) === '["unicorn"]');
    });
});

describe('Empty lines', function () {
    it('should remove empty lines', function () {
        var data;

        data = textToJSON('\n\n\nunicorn\r\n');

        assert(stringify(data) === '["unicorn"]');
    });

    it('should remove empty (white space only) lines', function () {
        var data;

        data = textToJSON(
            '  \t  \n' +
            'unicorn'
        );

        assert(stringify(data) === '["unicorn"]');
    });
});

describe('End-of-file end-of-line', function () {
    it('should return the same result, with or without EOF EOL', function () {
        assert(stringify(textToJSON('unicorn')) === '["unicorn"]');
        assert(stringify(textToJSON('unicorn\n')) === '["unicorn"]');
        assert(stringify(textToJSON('unicorn\r\n')) === '["unicorn"]');
    });
});

describe('Property-value pairs', function () {
    it('should return an object when a file contains pair delimiters',
        function () {
            assert(
                stringify(textToJSON('unicorn : magic creature')) ===
                '{"unicorn":"magic creature"}'
            );

            assert(stringify(textToJSON(
                    'unicorn : magic creature\n' +
                    '\trainbow:double\t\n' +
                    'doge\t:\tso scare'
                )) === JSON.stringify({
                    'unicorn': 'magic creature',
                    'rainbow': 'double',
                    'doge': 'so scare'
                })
            );
        }
    );

    it('should return an object when a file contains pair delimiters ' +
        'based on a given token',
        function () {
            assert(
                stringify(textToJSON('unicorn	magic creature', {
                    'delimiter': '\t'
                })) === '{"unicorn":"magic creature"}'
            );

            assert(stringify(textToJSON(
                'unicorn \t magic creature\n' +
                '\trainbow\tdouble\t\n' +
                'doge\t\t\tso scare', {
                    'delimiter': '\t'
                })) === JSON.stringify({
                    'unicorn': 'magic creature',
                    'rainbow': 'double',
                    'doge': 'so scare'
                })
            );
        }
    );
});

describe('Values', function () {
    it('should return an array', function () {
        assert(stringify(textToJSON('unicorn')) === '["unicorn"]');

        assert(stringify(textToJSON(
                'unicorn \n' +
                ' doge\n' +
                '\trainbow\t'
            )) === JSON.stringify([
                'doge',
                'rainbow',
                'unicorn'
            ])
        );
    });
});

describe('Mixed property-value pairs and values', function () {
    it('should throw when both property-value pairs and values are provided',
        function () {
            assert.throws(function () {
                textToJSON('unicorn\nrainbow: double');
            }, /`rainbow/);
        }
    );
});

describe('Values', function () {
    it('should throw when duplicate values exist',
        function () {
            assert.throws(function () {
                textToJSON(
                    'unicorn\n' +
                    'doge\n' +
                    'unicorn\n'
                );
            }, /`unicorn/);
        }
    );

    it('should NOT throw when duplicate values exist and `forgiving` is ' +
        '`true`',
        function () {
            assert.doesNotThrow(function () {
                textToJSON(
                    'unicorn\n' +
                    'doge\n' +
                    'unicorn\n', {
                        'forgiving': true
                    }
                );
            });
        }
    );

    it('should log for duplicate values when `forgiving` is `true`',
        function () {
            var log,
                isCalled;

            log = console.log;

            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'unicorn\n' +
                'doge\n' +
                'unicorn\n', {
                    'forgiving': true
                }
            );

            assert(isCalled === true);

            global.console.log = log;
        }
    );

    it('should NOT log for duplicate keys when `forgiving` is `true`' +
        ' and `log` is `false`',
        function () {
            var log,
                isCalled;

            log = console.log;

            /* istanbul ignore next */
            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'unicorn\n' +
                'doge\n' +
                'unicorn\n', {
                    'forgiving': true,
                    'log': false
                }
            );

            assert(isCalled !== true);

            global.console.log = log;
        }
    );
});

describe('Property-value pairs', function () {
    it('should throw when duplicate keys exist',
        function () {
            assert.throws(function () {
                textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: double\n'
                );
            }, /`doge/);
        }
    );

    it('should NOT throw for duplicate keys when `forgiving` is `true`',
        function () {
            assert.doesNotThrow(function () {
                textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: so scare\n', {
                        'forgiving': true
                    }
                );
            });
        }
    );

    it('should log for duplicate keys when `forgiving` is `true`',
        function () {
            var log,
                isCalled;

            log = console.log;

            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': true
                }
            );

            assert(isCalled === true);

            global.console.log = log;
        }
    );

    it('should NOT log for duplicate keys when `forgiving` is `true`' +
        ' and `log` is `false`',
        function () {
            var log,
                isCalled;

            log = console.log;

            /* istanbul ignore next */
            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': true,
                    'log': false
                }
            );

            assert(isCalled !== true);

            global.console.log = log;
        }
    );

    it('should NOT throw when duplicate key-values exist when `forgiving` ' +
        'is `"fix"`',
        function () {
            assert.doesNotThrow(function () {
                textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: so scare\n', {
                        'forgiving': 'fix'
                    }
                );
            });
        }
    );

    it('should NOT throw when duplicate keys with different values exist ' +
        'when `forgiving` is `"fix"`',
        function () {
            assert.doesNotThrow(function () {
                var data;

                data = textToJSON(
                    'doge: so scare\n' +
                    'unicorn: magic creature\n' +
                    'doge: rainbows\n', {
                        'forgiving': 'fix'
                    }
                );

                assert(stringify(data) === stringify({
                    'doge': 'rainbows',
                    'unicorn': 'magic creature'
                }));
            });
        }
    );

    it('should log for duplicate keys when `forgiving` is `"fix"`',
        function () {
            var log,
                isCalled;

            log = console.log;

            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': 'fix'
                }
            );

            assert(isCalled === true);

            global.console.log = log;
        }
    );

    it('should NOT log for duplicate keys when `forgiving` is `"fix"`' +
        ' and `log` is `false`',
        function () {
            var log,
                isCalled;

            log = console.log;

            /* istanbul ignore next */
            global.console.log = function () {
                isCalled = true;
            };

            textToJSON(
                'doge: so scare\n' +
                'unicorn: magic creature\n' +
                'doge: so scare\n', {
                    'forgiving': 'fix',
                    'log': false
                }
            );

            assert(isCalled !== true);

            global.console.log = log;
        }
    );
});
<|endoftext|>


<commit_before>var jsroot = require("jsroot");
var fs = require("fs");
// var seedrandom = require('seedrandom');

require("./../jsroot/demo/examples.js");

console.log('JSROOT version', jsroot.version);

var init_style = null,
    test_mode = "verify", nmatch = 0, ndiff = 0, nnew = 0,
    keyid = 'TH1', theonlykey = false, optid = -1, theonlyoption = -100, itemid = -1,
    entry, entry_name = "", testfile = null, testobj = null;

if (process.argv && (process.argv.length > 2)) {

   for (var cnt=2;cnt<process.argv.length;++cnt)
      switch (process.argv[cnt]) {
        case "-v":
        case "--verify":  test_mode = "verify"; break;
        case "-c":
        case "--create": test_mode = "create"; break;
        case "-k":
        case "--key":
           keyid = process.argv[++cnt];
           theonlykey = true;
           if (!keyid || !examples_main[keyid])
              return console.log('Key not found', keyid);
           break;
        case "-o":
        case "--opt":
           theonlyoption = parseInt(process.argv[++cnt]);
           if (isNaN(theonlyoption) || (theonlyoption<0) || !examples_main[keyid][theonlyoption])
              return console.log('wrong option for key', keyid);

           console.log('Select option', examples_main[keyid][theonlyoption], 'for key', keyid);
           break;
        case "-m":
        case "--more":
           require("./../jsroot/demo/examples_more.js");

           for (var key in examples_more) {
              if (key in examples_main) {
                 for (var n in examples_more[key])
                    examples_main[key].push(examples_more[key][n]);
              } else {
                 examples_main[key] = examples_more[key];
              }
           }

           break;

        default:
           console.log('Usage: node test.js [options]');
           console.log('   -v | --verify : check stored content against current JSROOT version');
           console.log('   -c | --create : perform checks and overwrite when results differ');
           console.log('   -k | --key  keyname : select specific key (class name) like TH1 or TProfile for testing');
           console.log('   -m | --more : use more tests');
           return;
      }
}

function ProduceGlobalStyleCopy() {
   // copy style when painter is loaded
   if (!init_style && jsroot.Painter) init_style = jsroot.gStyle;
}

function ProduceFile(content, extension) {
   if (!entry_name) entry_name = keyid;

   entry_name = entry_name.replace(/\+/g,'p').replace(/\>/g,'more')
                          .replace(/\</g,'less').replace(/\|/g,'I')
                          .replace(/\[/g,'L').replace(/\]/g,'J').replace(/\*/g,'star');

   // in older node.js fs.constants not exists
   var w_ok = fs.constants ? fs.constants.W_OK : fs.W_OK;

   fs.access(keyid, w_ok, function(dir_err) {

      if (dir_err) fs.mkdirSync(keyid);

      var svgname = keyid + "/" + entry_name + extension,
          svg0 = null, result = "MATCH";

      try {
        svg0 = fs.readFileSync(svgname, 'utf-8');
        if (svg0 != content) result = "DIFF";
      } catch(e) {
        svg0 = null;
        result = "NEW";
      }

      switch (result) {
         case "NEW": nnew++; break;
         case "DIFF": ndiff++; break;
         default: nmatch++;
      }

      var clen = content ? content.length : -1;
      console.log(keyid, entry_name, 'result', result, 'len='+clen, (svg0 && result=='DIFF' ? 'rel0='+(clen/svg0.length*100).toFixed(1)+'\%' : ''));

      if ((result === "NEW") || ((test_mode === 'create') && (result!=='MATCH'))) {
         if (clen > 0)
            fs.writeFileSync(svgname, content);
         else if (result !== "NEW")
            fs.unlink(svgname);
      }

      ProcessNextOption();
   });
}

function ProduceSVG(obj, opt) {

   // use only for object reading
   if ((theonlyoption>=0) && theonlyoption!==optid)
      return ProcessNextOption();

   jsroot.MakeSVG( { object: obj, option: opt, width: 1200, height: 800 }, function(svg) {
      ProduceFile(svg, ".svg");
   });
}

function ProduceJSON(tree, opt, branchname) {
   if (!tree) return ProcessNextOption();

   var args = { expr: opt, dump: true };
   if (branchname) {
      if (branchname === "/Event/Gen/Header/m_evtNumber") branchname = "/Event/Gen/Header.m_evtNumber"; // workaround
      args.branch = tree.FindBranch(branchname);
   }

   tree.Draw(args, function(res) {
      if (res) res = JSON.stringify(res); else res = "<fail>";
      ProduceFile(res, ".json");
   });
}

function ProcessNextOption() {

   if (!keyid) {
      console.log('No more data to process');
      console.log("SUMMARY: match", nmatch, "diff", ndiff, "new", nnew);
      return;
   }

   var opts = examples_main[keyid];
   if (!opts) return;

   if ((itemid>=0) || (itemid==-2)) {
      if (itemid==-2) itemid = -1; // special workaround for style entry, which is marked as itemid=-2
      if (++itemid>=opts[optid].items.length) itemid = -1;
   }

   if (itemid<0) { // first check that all items are processed
      if (theonlyoption == optid) {
         keyid = null;
         return ProcessNextOption();
      }
      if (++optid>=opts.length) {
         optid = -1;
         var found = false, next = null;
         for (var key in examples_main) {
            if (key === "TGeo") continue; // skip already here
            if (found) { next = key; break; }
            if (key == keyid) found = true;
         }

         keyid = next;
         if (theonlykey) keyid = null;
         return ProcessNextOption();
      }
   }

   entry = opts[optid];

   entry_name = "";

   // exclude some entries from the test
   if (entry.notest) return ProcessNextOption();

   var filename = "", itemname = "", itemfield = "", jsonname = "", url = "", opt = "",
       filepath = "http://jsroot.gsi.de/files/";
//       filepath = "https://root.cern.ch/js/files/";

   if (entry.file) {
       filename = entry.file;
       if ((filename.indexOf("http:")<0) && (filename.indexOf("https:")<0)) filename = filepath + filename;
   }
   if (entry.item) {
      itemname = entry.item;
      if (entry.itemfield) { itemfield = entry.itemfield; itemname = itemname.substr(0, itemname.length - itemfield.length - 1); }
   }
   if (entry.testopt !== undefined) opt = entry.testopt; else if (entry.opt) opt = entry.opt;
   if (entry.json) {
      jsonname = entry.json;
      if ((jsonname.indexOf("http:")<0) && (jsonname.indexOf("https:")<0)) jsonname = filepath + jsonname;
   }
   if (entry.items) {
      if (itemid<0) {

         if ((itemid==-1) && entry.style) {
            itemid = -2;
            itemname = entry.style; // special case when style should be applied before objects drawing
         } else {
           itemid = 0;
         }
      }
      if (itemid>=0) {
         itemname = entry.items[itemid];
         if (entry.opts && (itemid < entry.opts.length)) opt = entry.opts[itemid];
      }
   }

   if (entry.url) url = entry.url.replace(/\$\$\$/g, filepath); else
   if (entry.asurl) {
      url = ((entry.asurl === "browser") ? "?" : "?nobrowser&");
      url += jsonname ? "json=" + jsonname : "file=" + filename + "&item=" + itemname;
      url += itemname + "&opt=" + opt;
   }

   if ((opt=='inspect') || (opt=='count')) return ProcessNextOption();

   if (itemid >= 0)
      entry_name = (entry.name || keyid) + "_" + itemname + (opt ? "_" + opt : "");
   else
   if ('name' in entry)
      entry_name = entry.name;
   else
      entry_name = opt ? opt : keyid;

   ProduceGlobalStyleCopy();
   if (!entry.style && init_style) jsroot.gStyle = jsroot.extend({}, init_style);

   // ensure default options
   if (jsroot.Painter) jsroot.Painter.createRootColors(); // ensure default colors
   if (jsroot.gStyle.MathJax!==undefined)
      jsroot.gStyle.MathJax = entry.mathjax ? 1 : 0;
   jsroot.gStyle.Latex = entry.latex ? entry.latex : 2;
   // seedrandom('hello.', { global: true }); // set global random
   jsroot.id_counter = 0; // used in some custom styles

   if (keyid === "TTree") {
      if (entry.url || entry.large) return ProcessNextOption(); // ignore direct URL
      jsroot.OpenFile(filename, function(file) {
         var branchname = "", pos = itemname.indexOf(";1//");
         if (pos>0) { branchname = itemname.substr(pos+3); itemname = itemname.substr(0, pos+2); }
         file.ReadObject(itemname, function(tree) {
            ProduceJSON(tree, opt, branchname);
         });
      });
   } else
   if (((url.length > 0) && !entry.asurl)) {
      testfile = testobj = null;
      return ProcessNextOption();
   } else
   if (jsonname.length > 0) {
      testfile = testobj = null;
      jsroot.NewHttpRequest(jsonname, 'object', function(obj) {
         testobj = obj;
         ProduceSVG(testobj, opt);
      }).send();
   } else
   if (filename.length > 0) {
      jsroot.OpenFile(filename, function(file) {
         testfile = file;
         testfile.ReadObject(itemname, function(obj) {
            if (itemid==-2) {
               // special handling of style
               // Check that copy of gStyle exists
               ProduceGlobalStyleCopy();
               // first create copy of existing style
               var newstyle = jsroot.extend({}, jsroot.gStyle);
               // then apply changes to the
               jsroot.gStyle = jsroot.extend(newstyle, obj);
               return ProcessNextOption();
            } else {
               if (itemfield) {
                  if (itemfield == "Overlaps/ov00010") {
                     obj = obj.fOverlaps.arr[10];
                     console.log("foound obj", obj ? obj._typename : "none");
                  } else if (obj[itemfield])
                     obj = obj[itemfield];
               }
               testobj = obj;
               ProduceSVG(testobj, opt);
            }
         });
      });
   } else
   if (itemname.length > 0) {
      testfile.ReadObject(itemname, function(obj) {
         testobj = obj;
         ProduceSVG(testobj, opt);
      });
   } else {
      ProduceSVG(testobj, opt);
   }
}

ProcessNextOption();<commit_msg>Adjust to newer API with OpenFile and ReadObject<commit_after>var jsroot = require("jsroot");
var fs = require("fs");
// var seedrandom = require('seedrandom');

require("./../jsroot/demo/examples.js");

console.log('JSROOT version', jsroot.version);

var init_style = null,
    test_mode = "verify", nmatch = 0, ndiff = 0, nnew = 0,
    keyid = 'TH1', theonlykey = false, optid = -1, theonlyoption = -100, itemid = -1,
    entry, entry_name = "", testfile = null, testobj = null;

if (process.argv && (process.argv.length > 2)) {

   for (var cnt=2;cnt<process.argv.length;++cnt)
      switch (process.argv[cnt]) {
        case "-v":
        case "--verify":  test_mode = "verify"; break;
        case "-c":
        case "--create": test_mode = "create"; break;
        case "-k":
        case "--key":
           keyid = process.argv[++cnt];
           theonlykey = true;
           if (!keyid || !examples_main[keyid])
              return console.log('Key not found', keyid);
           break;
        case "-o":
        case "--opt":
           theonlyoption = parseInt(process.argv[++cnt]);
           if (isNaN(theonlyoption) || (theonlyoption<0) || !examples_main[keyid][theonlyoption])
              return console.log('wrong option for key', keyid);

           console.log('Select option', examples_main[keyid][theonlyoption], 'for key', keyid);
           break;
        case "-m":
        case "--more":
           require("./../jsroot/demo/examples_more.js");

           for (var key in examples_more) {
              if (key in examples_main) {
                 for (var n in examples_more[key])
                    examples_main[key].push(examples_more[key][n]);
              } else {
                 examples_main[key] = examples_more[key];
              }
           }

           break;

        default:
           console.log('Usage: node test.js [options]');
           console.log('   -v | --verify : check stored content against current JSROOT version');
           console.log('   -c | --create : perform checks and overwrite when results differ');
           console.log('   -k | --key  keyname : select specific key (class name) like TH1 or TProfile for testing');
           console.log('   -m | --more : use more tests');
           return;
      }
}

function ProduceGlobalStyleCopy() {
   // copy style when painter is loaded
   if (!init_style && jsroot.Painter) init_style = jsroot.gStyle;
}

function ProduceFile(content, extension) {
   if (!entry_name) entry_name = keyid;

   entry_name = entry_name.replace(/\+/g,'p').replace(/\>/g,'more')
                          .replace(/\</g,'less').replace(/\|/g,'I')
                          .replace(/\[/g,'L').replace(/\]/g,'J').replace(/\*/g,'star');

   // in older node.js fs.constants not exists
   var w_ok = fs.constants ? fs.constants.W_OK : fs.W_OK;

   fs.access(keyid, w_ok, function(dir_err) {

      if (dir_err) fs.mkdirSync(keyid);

      var svgname = keyid + "/" + entry_name + extension,
          svg0 = null, result = "MATCH";

      try {
        svg0 = fs.readFileSync(svgname, 'utf-8');
        if (svg0 != content) result = "DIFF";
      } catch(e) {
        svg0 = null;
        result = "NEW";
      }

      switch (result) {
         case "NEW": nnew++; break;
         case "DIFF": ndiff++; break;
         default: nmatch++;
      }

      var clen = content ? content.length : -1;
      console.log(keyid, entry_name, 'result', result, 'len='+clen, (svg0 && result=='DIFF' ? 'rel0='+(clen/svg0.length*100).toFixed(1)+'\%' : ''));

      if ((result === "NEW") || ((test_mode === 'create') && (result!=='MATCH'))) {
         if (clen > 0)
            fs.writeFileSync(svgname, content);
         else if (result !== "NEW")
            fs.unlink(svgname);
      }

      ProcessNextOption();
   });
}

function ProduceSVG(obj, opt) {

   // use only for object reading
   if ((theonlyoption>=0) && theonlyoption!==optid)
      return ProcessNextOption();

   jsroot.MakeSVG( { object: obj, option: opt, width: 1200, height: 800 }, function(svg) {
      ProduceFile(svg, ".svg");
   });
}

function ProduceJSON(tree, opt, branchname) {
   if (!tree) return ProcessNextOption();

   var args = { expr: opt, dump: true };
   if (branchname) {
      if (branchname === "/Event/Gen/Header/m_evtNumber") branchname = "/Event/Gen/Header.m_evtNumber"; // workaround
      args.branch = tree.FindBranch(branchname);
   }

   tree.Draw(args, function(res) {
      if (res) res = JSON.stringify(res); else res = "<fail>";
      ProduceFile(res, ".json");
   });
}

function ProcessNextOption() {

   if (!keyid) {
      console.log('No more data to process');
      console.log("SUMMARY: match", nmatch, "diff", ndiff, "new", nnew);
      return;
   }

   var opts = examples_main[keyid];
   if (!opts) return;

   if ((itemid>=0) || (itemid==-2)) {
      if (itemid==-2) itemid = -1; // special workaround for style entry, which is marked as itemid=-2
      if (++itemid>=opts[optid].items.length) itemid = -1;
   }

   if (itemid<0) { // first check that all items are processed
      if (theonlyoption == optid) {
         keyid = null;
         return ProcessNextOption();
      }
      if (++optid>=opts.length) {
         optid = -1;
         var found = false, next = null;
         for (var key in examples_main) {
            if (key === "TGeo") continue; // skip already here
            if (found) { next = key; break; }
            if (key == keyid) found = true;
         }

         keyid = next;
         if (theonlykey) keyid = null;
         return ProcessNextOption();
      }
   }

   entry = opts[optid];

   entry_name = "";

   // exclude some entries from the test
   if (entry.notest) return ProcessNextOption();

   var filename = "", itemname = "", itemfield = "", jsonname = "", url = "", opt = "",
       filepath = "http://jsroot.gsi.de/files/";
//       filepath = "https://root.cern.ch/js/files/";

   if (entry.file) {
       filename = entry.file;
       if ((filename.indexOf("http:")<0) && (filename.indexOf("https:")<0)) filename = filepath + filename;
   }
   if (entry.item) {
      itemname = entry.item;
      if (entry.itemfield) { itemfield = entry.itemfield; itemname = itemname.substr(0, itemname.length - itemfield.length - 1); }
   }
   if (entry.testopt !== undefined) opt = entry.testopt; else if (entry.opt) opt = entry.opt;
   if (entry.json) {
      jsonname = entry.json;
      if ((jsonname.indexOf("http:")<0) && (jsonname.indexOf("https:")<0)) jsonname = filepath + jsonname;
   }
   if (entry.items) {
      if (itemid<0) {

         if ((itemid==-1) && entry.style) {
            itemid = -2;
            itemname = entry.style; // special case when style should be applied before objects drawing
         } else {
           itemid = 0;
         }
      }
      if (itemid>=0) {
         itemname = entry.items[itemid];
         if (entry.opts && (itemid < entry.opts.length)) opt = entry.opts[itemid];
      }
   }

   if (entry.url) url = entry.url.replace(/\$\$\$/g, filepath); else
   if (entry.asurl) {
      url = ((entry.asurl === "browser") ? "?" : "?nobrowser&");
      url += jsonname ? "json=" + jsonname : "file=" + filename + "&item=" + itemname;
      url += itemname + "&opt=" + opt;
   }

   if ((opt=='inspect') || (opt=='count')) return ProcessNextOption();

   if (itemid >= 0)
      entry_name = (entry.name || keyid) + "_" + itemname + (opt ? "_" + opt : "");
   else
   if ('name' in entry)
      entry_name = entry.name;
   else
      entry_name = opt ? opt : keyid;

   ProduceGlobalStyleCopy();
   if (!entry.style && init_style) jsroot.gStyle = jsroot.extend({}, init_style);

   // ensure default options
   if (jsroot.Painter) jsroot.Painter.createRootColors(); // ensure default colors
   if (jsroot.gStyle.MathJax!==undefined)
      jsroot.gStyle.MathJax = entry.mathjax ? 1 : 0;
   jsroot.gStyle.Latex = entry.latex ? entry.latex : 2;
   // seedrandom('hello.', { global: true }); // set global random
   jsroot.id_counter = 0; // used in some custom styles

   if (keyid === "TTree") {
      if (entry.url || entry.large) return ProcessNextOption(); // ignore direct URL
      jsroot.OpenFile(filename).then(file => {
         var branchname = "", pos = itemname.indexOf(";1//");
         if (pos>0) { branchname = itemname.substr(pos+3); itemname = itemname.substr(0, pos+2); }
         file.ReadObject(itemname).then(tree => {
            ProduceJSON(tree, opt, branchname);
         });
      });
   } else if (((url.length > 0) && !entry.asurl)) {
      testfile = testobj = null;
      return ProcessNextOption();
   } else if (jsonname.length > 0) {
      testfile = testobj = null;
      jsroot.HttpRequest(jsonname, 'object').then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt);
      });
   } else if (filename.length > 0) {
      jsroot.OpenFile(filename).then(file => {
         testfile = file;
         testfile.ReadObject(itemname).then(obj => {
            if (itemid==-2) {
               // special handling of style
               // Check that copy of gStyle exists
               ProduceGlobalStyleCopy();
               // first create copy of existing style
               var newstyle = jsroot.extend({}, jsroot.gStyle);
               // then apply changes to the
               jsroot.gStyle = jsroot.extend(newstyle, obj);
               return ProcessNextOption();
            } else {
               if (itemfield) {
                  if (itemfield == "Overlaps/ov00010") {
                     obj = obj.fOverlaps.arr[10];
                     console.log("foound obj", obj ? obj._typename : "none");
                  } else if (obj[itemfield])
                     obj = obj[itemfield];
               }
               testobj = obj;
               ProduceSVG(testobj, opt);
            }
         });
      });
   } else if (itemname.length > 0) {
      testfile.ReadObject(itemname).then(obj => {
         testobj = obj;
         ProduceSVG(testobj, opt);
      });
   } else {
      ProduceSVG(testobj, opt);
   }
}

ProcessNextOption();<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2015 Stephen Howell, stephenhowell@outlook.com

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

(function (ext) {
    //var
    var jointData = { "SpineBase": null, "SpineMid": null, "Neck": null, "Head": null, "ShoulderLeft": null, "ElbowLeft": null, "WristLeft": null, "HandLeft": null, "ShoulderRight": null, "ElbowRight": null, "WristRight": null, "HandRight": null, "HipLeft": null, "KneeLeft": null, "AnkleLeft": null, "FootLeft": null, "HipRight": null, "KneeRight": null, "AnkleRight": null, "FootRight": null, "SpineShoulder": null, "HandTipLeft": null, "ThumbLeft": null, "HandTipRight": null, "ThumbRight": null };

    var bodies = [jointData, jointData, jointData, jointData, jointData, jointData];
    var rightHandState = "Unknown";
    var leftHandState = "Unknown";

    var JoinedHands = false;
    var WaveRight = false;
    var WaveLeft = false;
    var SwipeLeft = false;
    var SwipeRight = false;
    var SwipeUp = false;
    var SwipeDown = false;

    var connection = new WebSocket('ws://localhost:8181/');
    ext.connect = function (address, port)
    {
        connection = new WebSocket('ws://' + address + ':' + port + '/');
    };

    connection.onopen = function () {
        console.log('Connection open!');
    }

    connection.onclose = function () {
        console.log('Connection closed');
    }

    connection.onerror = function (error) {
        console.log('Error detected: ' + error.toString());
    }

    connection.onmessage = function (e) {
        var kdata = JSON.parse(e.data);
        // console.log(JSON.stringify(kdata));
        // Check if it's a body (could be a face etc.)
        if (kdata.type == "body") {
            bodies[kdata.index] = kdata.joints;
            rightHandState = kdata.rightHandState;
            leftHandState = kdata.leftHandState;
        }
        else if (kdata.type == "gesture") {
            switch(kdata.gesture)
            {
                //     Hands joined in front of chest.
                case "JoinedHands":
                    JoinedHands = true;
                    break;
                //     Waving using the right hand.
                case "WaveRight":
                    WaveRight = true;
                    break;
                //     Waving using the left hand.
                case "WaveLeft":
                    WaveLeft = true;
                    break;
                //     Hand moved horizontally from right to left.
                case "SwipeLeft":
                    SwipeLeft = true;
                    break;
                //     Hand moved horizontally from left to right.
                case "SwipeRight":
                    SwipeRight = true;
                    break;
                //     Hand moved vertically from hip center to head.
                case "SwipeUp":
                    SwipeUp = true;
                    break;
                //     Hand moved vertically from head to hip center.
                case "SwipeDown":
                    SwipeDown = true;
                    break;

            }

        }
    }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function () { if (connection.socket.connected) { connection.socket.disconnect(); } };

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function () {
        if (connection.readyState == 1) {
            return { status: 2, msg: 'Connected' };
        }
        else {
            connection = new WebSocket('ws://localhost:8181/'); // Does nae work at all
            return {
                status: 1, msg: 'Not connected, attempting reconnection, make sure Kinect2ScratchX is running!'
            };
        }
    };

    ext.Disconnect = function (callback) {
        if (!(connection === null)) {
            if (connection.readyState == 1) {
                //console.log("disconnecting from server");
                connection.close();
            } else { console.log("Disconnect: socket already disconnected"); }
        }
    };

    ext.getLimbValue = function (coordinate, side, bodyPart, index) {

        var joint = jointData[bodyPart + side]; // bodies...index...
        if (coordinate == "x")
            return joint[0];
        else if (coordinate == "y")
            return joint[1];
        else if (coordinate == "z")
            return joint[2];
        else
            return 0;
    };

    //jointData.Head[0]
    ext.getTorsoValue = function (coordinate, torsoJoint) {
        var joint = jointData[torsoJoint];
        if (coordinate == "x")
            return joint[0];
        else if (coordinate == "y")
            return joint[1];
        else if (coordinate == "z")
            return joint[2];
        else
            return 0;
    };

    ext.getHandState = function (side, state) {
        if (side == "Right" && rightHandState == state)
            return true;

        if (side == "Left" && leftHandState == state)
            return true;

        return false;
    };

    // Leaving these out for now...
    /*
    ext.joinedHandsDetected = function () {
        var j = handStateData[side + "Hand"];
        return JSON.stringify(j[state]);
    };

    ext.waveDetected = function (side) {
        console.log("In WaveDetected");
        var waveVal = false;
        if (side == "Right")
        {
            waveVal = WaveRight;
            WaveRight = false;
        }
        else if (side == "Left")
        {
            waveVal = WaveLeft;
            WaveLeft = false;
        }
        return waveVal;
    };

    ext.swipeDetected = function (swipeDirection) {

        return false;
    };
    */
    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            //['w', 'Listen to Kinect at address %n on port %n', 'connect', 'localhost', '8181'],
            ['h', 'When a person enters view', 'userEntered'],
            ['r', 'number of tracked people', 'getTrackedUsers'],
            ['r', '%m.coordinate of %m.side %m.limbs of %m.index', 'getLimbValue', 'x', 'Right', 'Hand', 'Closest Person'],
			['r', 'get %m.coordinate position of %m.side %m.limbs', 'getLimbValue', 'y', 'Right', 'Hand'],
			['r', 'get %m.coordinate position of %m.torso', 'getTorsoValue', 'x', 'Head'],
			['b', '%m.side Hand is %m.state', 'getHandState', 'Right', 'Closed'],
            ['b', '%m.side Hand is %m.state', 'getHandState', 'Left', 'Lasso'],
            ['h', 'When a person exits view', 'userLost']
            //['b', 'hands joined', 'handsJoined'],
			//['h', 'When Wave %m.side detected', 'waveDetected', 'Right'],
			//['h', 'When Swipe %m.swipeDirections detected', 'swipeDetected', 'Right'],
			//['h', 'When Joined Hands detected', 'joinedHandsDetected']
        ],
        menus: {
            index: ["Closest Person", "Person 1", "Person 2", "Person 3", "Person 4", "Person 5", "Person 6"],
            coordinate: ["x", "y", "z"],
            side: ["Right", "Left"],
            swipeDirections: ["Right", "Left", "Up", "Down"],
            state: ["Open", "Closed", "Lasso", "Unknown"],
            torso: ["Head", "Neck", "SpineShoulder", "SpineMid", "SpineBase"],
            limbs: ["Shoulder", "Elbow", "Wrist", "Hand", "HandTip", "Thumb", "Hip", "Knee", "Ankle", "Foot"]
        },
        url: 'http://stephenhowell.github.io'
    };

    // Register the extension
    ScratchExtensions.register('Kinectv2 To ScratchX 3.14', descriptor, ext);

})({});

<commit_msg>more blocks<commit_after>// The MIT License (MIT)

// Copyright (c) 2015 Stephen Howell, stephenhowell@outlook.com

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

(function (ext) {
    //var
    var jointData = { "SpineBase": null, "SpineMid": null, "Neck": null, "Head": null, "ShoulderLeft": null, "ElbowLeft": null, "WristLeft": null, "HandLeft": null, "ShoulderRight": null, "ElbowRight": null, "WristRight": null, "HandRight": null, "HipLeft": null, "KneeLeft": null, "AnkleLeft": null, "FootLeft": null, "HipRight": null, "KneeRight": null, "AnkleRight": null, "FootRight": null, "SpineShoulder": null, "HandTipLeft": null, "ThumbLeft": null, "HandTipRight": null, "ThumbRight": null };

    var bodies = [jointData, jointData, jointData, jointData, jointData, jointData];
    var rightHandState = "Unknown";
    var leftHandState = "Unknown";

    var JoinedHands = false;
    var WaveRight = false;
    var WaveLeft = false;
    var SwipeLeft = false;
    var SwipeRight = false;
    var SwipeUp = false;
    var SwipeDown = false;

    var connection = new WebSocket('ws://localhost:8181/');
    ext.connect = function (address, port)
    {
        connection = new WebSocket('ws://' + address + ':' + port + '/');
    };

    connection.onopen = function () {
        console.log('Connection open!');
    }

    connection.onclose = function () {
        console.log('Connection closed');
    }

    connection.onerror = function (error) {
        console.log('Error detected: ' + error.toString());
    }

    connection.onmessage = function (e) {
        var kdata = JSON.parse(e.data);
        // console.log(JSON.stringify(kdata));
        // Check if it's a body (could be a face etc.)
        if (kdata.type == "body") {
            bodies[kdata.index] = kdata.joints;
            rightHandState = kdata.rightHandState;
            leftHandState = kdata.leftHandState;
        }
        else if (kdata.type == "gesture") {
            switch(kdata.gesture)
            {
                //     Hands joined in front of chest.
                case "JoinedHands":
                    JoinedHands = true;
                    break;
                //     Waving using the right hand.
                case "WaveRight":
                    WaveRight = true;
                    break;
                //     Waving using the left hand.
                case "WaveLeft":
                    WaveLeft = true;
                    break;
                //     Hand moved horizontally from right to left.
                case "SwipeLeft":
                    SwipeLeft = true;
                    break;
                //     Hand moved horizontally from left to right.
                case "SwipeRight":
                    SwipeRight = true;
                    break;
                //     Hand moved vertically from hip center to head.
                case "SwipeUp":
                    SwipeUp = true;
                    break;
                //     Hand moved vertically from head to hip center.
                case "SwipeDown":
                    SwipeDown = true;
                    break;

            }

        }
    }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function () { if (connection.socket.connected) { connection.socket.disconnect(); } };

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function () {
        if (connection.readyState == 1) {
            return { status: 2, msg: 'Connected' };
        }
        else {
            connection = new WebSocket('ws://localhost:8181/'); // Does nae work at all
            return {
                status: 1, msg: 'Not connected, attempting reconnection, make sure Kinect2ScratchX is running!'
            };
        }
    };

    ext.Disconnect = function (callback) {
        if (!(connection === null)) {
            if (connection.readyState == 1) {
                //console.log("disconnecting from server");
                connection.close();
            } else { console.log("Disconnect: socket already disconnected"); }
        }
    };

    ext.getLimbValue = function (coordinate, side, bodyPart, index) {

        var joint = jointData[bodyPart + side]; // bodies...index...
        if (coordinate == "x")
            return joint[0];
        else if (coordinate == "y")
            return joint[1];
        else if (coordinate == "z")
            return joint[2];
        else
            return 0;
    };

    //jointData.Head[0]
    ext.getTorsoValue = function (coordinate, torsoJoint) {
        var joint = jointData[torsoJoint];
        if (coordinate == "x")
            return joint[0];
        else if (coordinate == "y")
            return joint[1];
        else if (coordinate == "z")
            return joint[2];
        else
            return 0;
    };

    ext.getHandState = function (side, state) {
        if (side == "Right" && rightHandState == state)
            return true;

        if (side == "Left" && leftHandState == state)
            return true;

        return false;
    };

    // Leaving these out for now...
    /*
    ext.joinedHandsDetected = function () {
        var j = handStateData[side + "Hand"];
        return JSON.stringify(j[state]);
    };

    ext.waveDetected = function (side) {
        console.log("In WaveDetected");
        var waveVal = false;
        if (side == "Right")
        {
            waveVal = WaveRight;
            WaveRight = false;
        }
        else if (side == "Left")
        {
            waveVal = WaveLeft;
            WaveLeft = false;
        }
        return waveVal;
    };

    ext.swipeDetected = function (swipeDirection) {

        return false;
    };
    */
    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            //['w', 'Listen to Kinect at address %n on port %n', 'connect', 'localhost', '8181'],
            ['h', 'When a person enters view', 'userEntered'],
            ['r', 'number of tracked people', 'getTrackedUsers'],
            ['r', '%m.coordinate of %m.side %m.limbs of %m.index', 'getLimbValue', 'x', 'Right', 'Hand', 'Closest Person'],
            ['r', '%m.coordinate of %m.side %m.limbs of %m.index', 'getLimbValue', 'y', 'Right', 'Hand', 'Closest Person'],
            ['r', '%m.coordinate of %m.side %m.limbs of %m.index', 'getLimbValue', 'z', 'Right', 'Hand', 'Closest Person'],
			['r', 'get %m.coordinate position of %m.torso', 'getTorsoValue', 'x', 'Head'],
			['b', '%m.side Hand is %m.state', 'getHandState', 'Right', 'Closed'],
            ['b', '%m.side Hand is %m.state', 'getHandState', 'Left', 'Lasso'],
            ['h', 'When a person exits view', 'userLost']
            //['b', 'hands joined', 'handsJoined'],
			//['h', 'When Wave %m.side detected', 'waveDetected', 'Right'],
			//['h', 'When Swipe %m.swipeDirections detected', 'swipeDetected', 'Right'],
			//['h', 'When Joined Hands detected', 'joinedHandsDetected']
        ],
        menus: {
            index: ["Closest Person", "Person 1", "Person 2", "Person 3", "Person 4", "Person 5", "Person 6"],
            coordinate: ["x", "y", "z"],
            side: ["Right", "Left"],
            swipeDirections: ["Right", "Left", "Up", "Down"],
            state: ["Open", "Closed", "Lasso", "Unknown"],
            torso: ["Head", "Neck", "SpineShoulder", "SpineMid", "SpineBase"],
            limbs: ["Shoulder", "Elbow", "Wrist", "Hand", "HandTip", "Thumb", "Hip", "Knee", "Ankle", "Foot"]
        },
        url: 'http://stephenhowell.github.io'
    };

    // Register the extension
    ScratchExtensions.register('Kinectv2 To ScratchX 3.14', descriptor, ext);

})({});

<|endoftext|>


<commit_before>'use strict';

var spache, assert;

spache = require('./');
assert = require('assert');

describe('spache', function () {
    it('should be an `Object`', function () {
        assert(typeof spache === 'object');
    });
});

describe('spache.is(word)', function () {
    it('should return true if a word is listed in Spache', function () {
        assert(spache.is('train') === true);
    });

    it('should return false if a word is not listed in Spache', function () {
        assert(spache.is('unicorn') === false);
    });
});

describe('spache.all()', function () {
    var all = spache.all();

    it('should return an array', function () {
        assert('length' in all);
        assert(typeof all === 'object');
    });

    it('every entry should be lowercase', function () {
        var iterator = -1,
            length = all.length;

        while (++iterator < length) {
            assert(all[iterator].toLowerCase() === all[iterator]);
        }
    });

    it('every entry should only occur once', function () {
        var iterator = -1,
            length = all.length;

        while (++iterator < length) {
            assert(all.indexOf(all[iterator], iterator + 1) === -1);
        }
    });

    it('should be immutable', function () {
        all.push('unicorn');

        assert(spache.all().indexOf('unicorn') === -1);
    });
});

describe('spache.add(word) and spache.remove(word)',
    function () {
        it('should add and remove a word', function () {
            assert(spache.is('unicorn') === false);

            spache.add('unicorn');
            assert(spache.is('unicorn') === true);

            spache.remove('unicorn');
            assert(spache.is('unicorn') === false);
        });

        it('should add and remove multiple words', function () {
            assert(spache.is('unicorn') === false);
            assert(spache.is('rainbow') === false);

            spache.add('unicorn', 'rainbow');
            assert(spache.is('unicorn') === true);
            assert(spache.is('rainbow') === true);

            spache.remove('unicorn', 'rainbow');
            assert(spache.is('unicorn') === false);
            assert(spache.is('rainbow') === false);
        });

        it('should fail silently when removing a non-existing word',
            function () {
                assert(spache.is('unicorn') === false);
                spache.remove('unicorn');
                assert(spache.is('unicorn') === false);
            }
        );
    }
);
<commit_msg>Refactor test<commit_after>'use strict';

/**
 * Dependencies.
 */

var spache,
    assert;

spache = require('./');
assert = require('assert');

/**
 * Tests.
 */

describe('spache', function () {
    it('should be an `Object`', function () {
        assert(typeof spache === 'object');
    });
});

describe('spache.is(word)', function () {
    it('should return true if a word is listed', function () {
        assert(spache.is('train') === true);
    });

    it('should return false if a word is not listed', function () {
        assert(spache.is('unicorn') === false);
    });
});

describe('spache.all()', function () {
    var all;

    all = spache.all();

    it('should return an array', function () {
        assert('length' in all);
        assert(typeof all === 'object');
    });

    it('every entry should be lowercase', function () {
        all.forEach(function (word) {
            assert(word.toLowerCase() === word);
        });
    });

    it('every entry should only occur once', function () {
        all.forEach(function (word, index) {
            assert(all.indexOf(word, index + 1) === -1);
        });
    });

    it('should be immutable', function () {
        all.push('unicorn');

        assert(spache.all().indexOf('unicorn') === -1);
    });
});

describe('spache.add(word) and spache.remove(word)',
    function () {
        it('should add and remove a word', function () {
            assert(spache.is('unicorn') === false);

            spache.add('unicorn');

            assert(spache.is('unicorn') === true);

            spache.remove('unicorn');

            assert(spache.is('unicorn') === false);
        });

        it('should add and remove multiple words', function () {
            assert(spache.is('unicorn') === false);
            assert(spache.is('rainbow') === false);

            spache.add('unicorn', 'rainbow');

            assert(spache.is('unicorn') === true);
            assert(spache.is('rainbow') === true);

            spache.remove('unicorn', 'rainbow');

            assert(spache.is('unicorn') === false);
            assert(spache.is('rainbow') === false);
        });

        it('should fail silently when removing a non-existing word',
            function () {
                assert(spache.is('unicorn') === false);

                spache.remove('unicorn');

                assert(spache.is('unicorn') === false);
            }
        );
    }
);
<|endoftext|>


<commit_before>import postcss from 'postcss';
import test    from 'ava';

import plugin from './';

function run(t, input, output, opts = { }) {
    return postcss([ plugin(opts) ]).process(input)
        .then( result => {
            t.deepEqual(result.css, output);
            t.deepEqual(result.warnings().length, 0);
        });
}

const optDefault = {
    filterByProps: ['color', 'border-color']
};

test('default settings', t => {
    let input = `.foo {
        color: #000;
        width: 10px;
        display: block;
    }`;
    let output = `:root {
        --color-1: #000;
        --width-1: 10px;
        --display-1: block;\n}\n.foo {
        color: var(--color-1);
        width: var(--width-1);
        display: var(--display-1);
    }`;
    return run(t, input, output, { });
});

test('repeated values', t => {
    let input = `.foo {
        color: blue;
    }
    .bar {
        color: blue;
    }`;
    let output = `:root {
        --color-1: blue;\n}
    .foo {
        color: var(--color-1);
    }
    .bar {
        color: var(--color-1);
    }`;
    return run(t, input, output, optDefault);
});

/***************Color types*************************/
test('HSL', t => {
    let input = `.foo {
        border: 1px solid hsl(120,100%,50%, 0.5);
    }`;
    let output = `:root {
        --border-1: hsl(120,100%,50%, 0.5);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('HSLA', t => {
    let input = `.foo {
        border: 1px solid hsla(120,100%,50%, 0.5);
    }`;
    let output = `:root {
        --border-1: hsla(120,100%,50%, 0.5);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('color keyword', t => {
    let input = `.foo {
        border: 1px solid black;
    }`;
    let output = `:root {
        --border-1: black;\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('RGB', t => {
    let input = `.foo {
        border: 1px solid rgb(120, 100, 50);
    }`;
    let output = `:root {
        --border-1: rgb(120, 100, 50);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('RGBA', t => {
    let input = `.foo {
        border: 1px solid rgba(120, 100, 50, 0.4);
    }`;
    let output = `:root {
        --border-1: rgba(120, 100, 50, 0.4);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('short hex', t => {
    let input = `.foo {
        border: 1px solid #000;
    }`;
    let output = `:root {
        --border-1: #000;\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('long hex', t => {
    let input = `.foo {
        border: 1px solid #101113;
    }`;
    let output = `:root {
        --border-1: #101113;\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

/******************************************************/

test('exist root element', t => {
    let input = `:root {
        --base-font-size: 16px;
    }
    .foo {
        color: #000;
        font-size: var(--base-font-size);
    }`;
    let output = `:root {
        --base-font-size: 16px;
        --color-1: #000;
    }
    .foo {
        color: var(--color-1);
        font-size: var(--base-font-size);
    }`;
    return run(t, input, output, { });
});

test('several colors in one property', t => {
    let input = `.foo {
        box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
    }`;
    let output = `:root {
        --box-shadow-1: #dcffa6;
        --box-shadow-2: #000;\n}\n.foo {
        box-shadow: inset 0 2px 0px var(--box-shadow-1), 0 2px 5px var(--box-shadow-2);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('custom element for css variables', t => {
    let input = `.foo {
        --color-1: black;
    }
    .bar {
        border-color: red;
    }`;
    let output = `.foo {
        --color-1: black;
        --border-color-1: red;
    }
    .bar {
        border-color: var(--border-color-1);
    }`;
    return run(t, input, output, { scope: '.foo' });
});

test('filter by color and props', t => {
    let input = `.foo {
        border: 1px solid #000;
        background-color: red;
    }`;
    let output = `:root {
        --border-1: #000;\n}\n.foo {
        border: 1px solid var(--border-1);
        background-color: red;
    }`;
    return run(t, input, output, {
        onlyColor: true,
        filterByProps: ['border']
    });
});

test('default value in css variable', t => {
    let input = `:root {
        --base-color: #fff;
    }
    .foo {
        color: var(--base-color, #000);
        border: 1px solid #eee;
    }`;
    let output = `:root {
        --base-color: #fff;
        --border-1: #eee;
    }
    .foo {
        color: var(--base-color, #000);
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});
<commit_msg>Fix comments in tests<commit_after>import postcss from 'postcss';
import test    from 'ava';

import plugin from './';

function run(t, input, output, opts = { }) {
    return postcss([ plugin(opts) ]).process(input)
        .then( result => {
            t.deepEqual(result.css, output);
            t.deepEqual(result.warnings().length, 0);
        });
}

const optDefault = {
    filterByProps: ['color', 'border-color']
};

test('default settings', t => {
    let input = `.foo {
        color: #000;
        width: 10px;
        display: block;
    }`;
    let output = `:root {
        --color-1: #000;
        --width-1: 10px;
        --display-1: block;\n}\n.foo {
        color: var(--color-1);
        width: var(--width-1);
        display: var(--display-1);
    }`;
    return run(t, input, output, { });
});

test('repeated values', t => {
    let input = `.foo {
        color: blue;
    }
    .bar {
        color: blue;
    }`;
    let output = `:root {
        --color-1: blue;\n}
    .foo {
        color: var(--color-1);
    }
    .bar {
        color: var(--color-1);
    }`;
    return run(t, input, output, optDefault);
});

/** *************Color types*********************** **/
test('HSL', t => {
    let input = `.foo {
        border: 1px solid hsl(120,100%,50%, 0.5);
    }`;
    let output = `:root {
        --border-1: hsl(120,100%,50%, 0.5);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('HSLA', t => {
    let input = `.foo {
        border: 1px solid hsla(120,100%,50%, 0.5);
    }`;
    let output = `:root {
        --border-1: hsla(120,100%,50%, 0.5);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('color keyword', t => {
    let input = `.foo {
        border: 1px solid black;
    }`;
    let output = `:root {
        --border-1: black;\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('RGB', t => {
    let input = `.foo {
        border: 1px solid rgb(120, 100, 50);
    }`;
    let output = `:root {
        --border-1: rgb(120, 100, 50);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('RGBA', t => {
    let input = `.foo {
        border: 1px solid rgba(120, 100, 50, 0.4);
    }`;
    let output = `:root {
        --border-1: rgba(120, 100, 50, 0.4);\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('short hex', t => {
    let input = `.foo {
        border: 1px solid #000;
    }`;
    let output = `:root {
        --border-1: #000;\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('long hex', t => {
    let input = `.foo {
        border: 1px solid #101113;
    }`;
    let output = `:root {
        --border-1: #101113;\n}\n.foo {
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});

/** ************************************************** **/

test('exist root element', t => {
    let input = `:root {
        --base-font-size: 16px;
    }
    .foo {
        color: #000;
        font-size: var(--base-font-size);
    }`;
    let output = `:root {
        --base-font-size: 16px;
        --color-1: #000;
    }
    .foo {
        color: var(--color-1);
        font-size: var(--base-font-size);
    }`;
    return run(t, input, output, { });
});

test('several colors in one property', t => {
    let input = `.foo {
        box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
    }`;
    let output = `:root {
        --box-shadow-1: #dcffa6;
        --box-shadow-2: #000;\n}\n.foo {
        box-shadow: inset 0 2px 0px var(--box-shadow-1), 0 2px 5px var(--box-shadow-2);
    }`;
    return run(t, input, output, { onlyColor: true });
});

test('custom element for css variables', t => {
    let input = `.foo {
        --color-1: black;
    }
    .bar {
        border-color: red;
    }`;
    let output = `.foo {
        --color-1: black;
        --border-color-1: red;
    }
    .bar {
        border-color: var(--border-color-1);
    }`;
    return run(t, input, output, { scope: '.foo' });
});

test('filter by color and props', t => {
    let input = `.foo {
        border: 1px solid #000;
        background-color: red;
    }`;
    let output = `:root {
        --border-1: #000;\n}\n.foo {
        border: 1px solid var(--border-1);
        background-color: red;
    }`;
    return run(t, input, output, {
        onlyColor: true,
        filterByProps: ['border']
    });
});

test('default value in css variable', t => {
    let input = `:root {
        --base-color: #fff;
    }
    .foo {
        color: var(--base-color, #000);
        border: 1px solid #eee;
    }`;
    let output = `:root {
        --base-color: #fff;
        --border-1: #eee;
    }
    .foo {
        color: var(--base-color, #000);
        border: 1px solid var(--border-1);
    }`;
    return run(t, input, output, { onlyColor: true });
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var nock = require('nock');
var avail = require('./');
var symbols = require('log-symbols');

var fixtures = {
  results: [
    {
      domain: 'avail.io',
      path: '',
      availability: 'available'
    },
    {
      domain: 'avail.com',
      path: '',
      availability: 'unavailable'
    }
  ]
};

nock('https://domainr.com')
  .get('/api/json/search?q=avail&client_id=avail')
  .reply(200, fixtures);

describe('avail', function(){
  it('available', function(){
    avail('avail', function (domains) {
      assert.equal(domains[0], 'avail.io ' + symbols.success);
    });
  });

  it('unavailable', function(){
    avail('avail', function (domains) {
      assert.equal(domains[1], 'avail.com ' +  symbols.error);
    });
  });
});
<commit_msg>Update unit tests<commit_after>'use strict';

var assert = require('assert');
var nock = require('nock');
var avail = require('./');

var fixtures = {
  results: [
    {
      domain: 'avail.io',
      path: '',
      availability: 'available'
    },
    {
      domain: 'avail.com',
      path: '',
      availability: 'unavailable'
    },
    {
      domain: 'avail.com',
      path: '/pathtest',
      availability: 'unavailable'
    }
  ]
};

nock('https://domainr.com')
  .get('/api/json/search?q=avail&client_id=avail')
  .reply(200, fixtures);

describe('avail', function(){
  it('available', function(){
    avail('avail', function (domains) {
      assert.equal(domains[0].domain, 'avail.io');
      assert.equal(domains[0].availability, 'available');
    });
  });

  it('unavailable', function(){
    avail('avail', function (domains) {
      assert.equal(domains[1].domain, 'avail.com');
      assert.equal(domains[1].availability, 'unavailable');
    });
  });

  it('result with path', function(){
    avail('avail', function (domains) {
      assert.equal(domains[2].domain, 'avail.com/pathtest');
      assert.equal(domains[2].availability, 'unavailable');
    });
  });
});
<|endoftext|>


<commit_before>/* globals describe,it,before */

// Quick polyfill
if (!Object.assign) {
  Object.assign = require('lodash.assign');
}

var expect = require('chai').expect;
var boosh = require('./');
var getPackage = require('./lib/getPackage.js');
var removeKeys = require('./lib/removeKeys.js');
var filenameWithoutExt = require('./lib/filenameWithoutExt.js');

describe('getPackage', function() {
  it('Should get package.json', function() {
    var pkg = getPackage();
    expect(pkg.name).to.equal('booshjs');
  });
});

describe('filenameWithoutExt', function() {
  it('Should return filenames without extensions', function() {
    expect(filenameWithoutExt('path/to/file.html')).to.equal('file');
    expect(filenameWithoutExt('./relative/path/to/something.js')).to.equal('something');
    expect(filenameWithoutExt('/abs/path/to/something/else.clj')).to.equal('else');
  });
});

describe('removeKeys', function() {
  it('Should remote keys from an object', function() {
    var obj = {
      in: 'some value',
      out: 'another value',
      isDev: false,
      entry: 'app.js',
    };

    var newObj = removeKeys(obj, ['in', 'out', 'isDev']);
    expect(newObj.in).to.be.undefined;
    expect(newObj.out).to.be.undefined;
    expect(newObj.isDev).to.be.undefined;
    expect(newObj.entry).to.equal('app.js');
  });

  it('Should not mutate original object', function() {
    var obj = {
      in: 'some value',
      out: 'another value',
      isDev: false,
      entry: 'app.js',
    };
    removeKeys(obj, ['in', 'out', 'isDev']);
    expect(obj).to.eql(obj);
  });
});

describe('boosh', function() {
  var validConfig = {
    in: '/path/to/file',
    out: '/path/to/file',
    isDev: true,
  };

  it('should throw when no config object is passed', function() {
    expect(boosh).to.throw(Error, 'Invariant Violation: Expected a configuration object.');
  });

  it('should throw when required options are not passed', function() {
    expect(boosh.bind(boosh, {
      in: null,
      out: '/path/to/file',
    })).to.throw(Error, 'Invariant Violation: Configuration object must have an `in` property.');

    expect(boosh.bind(boosh, {
      in: '/path/to/file',
      out: null,
    })).to.throw(Error, 'Invariant Violation: Configuration object must have an `out` property.');

    expect(boosh.bind(boosh, {
      in: '/path/to/file',
      out: '/path/to/file',
    })).to.not.throw();
  });

  it('Should accept entry and output as valid forms of in or out', function() {
    expect(boosh.bind(boosh, {
      entry: '/path/to/file',
      out: '/path/to/file',
    })).to.not.throw();

    expect(boosh.bind(boosh, {
      in: '/path/to/file',
      output: '/path/to/file',
    })).to.not.throw();

    expect(boosh.bind(boosh, {
      entry: '/path/to/file',
      output: '/path/to/file',
      isDev: true,
    })).to.not.throw();
  });

  it('Should not export an object with custom options defined', function() {
    var config = boosh(validConfig);

    expect(config.in).to.be.undefined;
    expect(config.out).to.be.undefined;
    expect(config.isDev).to.be.undefined;
    expect(config.entry).to.be.ok;
    expect(config.output).to.be.ok;
  });

  it('Should pass the https param in to dev server', function() {
    var config = boosh(Object.assign({}, validConfig, { https: true }));
    expect(config.devServer.https).to.be.true;
  });

  it('Should pass the port param in to dev server', function() {
    var config = boosh(Object.assign({}, validConfig, { port: 1234 }));
    expect(config.devServer.port).to.equal(1234);
  });

  it('Should base input keys on filenames', function() {
    var config = boosh({
      in: 'oh-hai.js',
      out: 'some/path/',
      isDev: false,
    });

    expect(config.entry).to.have.key('oh-hai');
  });

  it('Can take a hash as input to the `in` parameter', function() {
    var obj = {
      in: {
        ohHai: 'oh-hai.js',
        login: 'src/login.js',
      },
      out: 'some/path/',
      isDev: false,
    };

    var config = boosh(obj);

    expect(config.entry).to.eql(obj.in);

    obj.isDev = true;

    config = boosh(obj);

    expect(config.entry.ohHai).to.contain(obj.in.ohHai);
    expect(config.entry.login).to.contain(obj.in.login);
  });

  it('Should allow overwriting via standard webpack config', function() {
    var config = boosh({
      in: 'app.js',
      out: 'some/path/',
      isDev: true,
    });

    expect(config.entry.app).to.be.instanceOf(Array);

    config = boosh({
      out: 'bleh',
      entry: {
        app: 'some/thang.js',
      },
    });

    expect(config.entry.app).to.equal('some/thang.js');
  });
});

<commit_msg>Fix capitalization in test names<commit_after>/* globals describe,it,before */

// Quick polyfill
if (!Object.assign) {
  Object.assign = require('lodash.assign');
}

var expect = require('chai').expect;
var boosh = require('./');
var getPackage = require('./lib/getPackage.js');
var removeKeys = require('./lib/removeKeys.js');
var filenameWithoutExt = require('./lib/filenameWithoutExt.js');

describe('getPackage', function() {
  it('Should get package.json', function() {
    var pkg = getPackage();
    expect(pkg.name).to.equal('booshjs');
  });
});

describe('filenameWithoutExt', function() {
  it('Should return filenames without extensions', function() {
    expect(filenameWithoutExt('path/to/file.html')).to.equal('file');
    expect(filenameWithoutExt('./relative/path/to/something.js')).to.equal('something');
    expect(filenameWithoutExt('/abs/path/to/something/else.clj')).to.equal('else');
  });
});

describe('removeKeys', function() {
  it('Should remote keys from an object', function() {
    var obj = {
      in: 'some value',
      out: 'another value',
      isDev: false,
      entry: 'app.js',
    };

    var newObj = removeKeys(obj, ['in', 'out', 'isDev']);
    expect(newObj.in).to.be.undefined;
    expect(newObj.out).to.be.undefined;
    expect(newObj.isDev).to.be.undefined;
    expect(newObj.entry).to.equal('app.js');
  });

  it('Should not mutate original object', function() {
    var obj = {
      in: 'some value',
      out: 'another value',
      isDev: false,
      entry: 'app.js',
    };
    removeKeys(obj, ['in', 'out', 'isDev']);
    expect(obj).to.eql(obj);
  });
});

describe('boosh', function() {
  var validConfig = {
    in: '/path/to/file',
    out: '/path/to/file',
    isDev: true,
  };

  it('Should throw when no config object is passed', function() {
    expect(boosh).to.throw(Error, 'Invariant Violation: Expected a configuration object.');
  });

  it('Should throw when required options are not passed', function() {
    expect(boosh.bind(boosh, {
      in: null,
      out: '/path/to/file',
    })).to.throw(Error, 'Invariant Violation: Configuration object must have an `in` property.');

    expect(boosh.bind(boosh, {
      in: '/path/to/file',
      out: null,
    })).to.throw(Error, 'Invariant Violation: Configuration object must have an `out` property.');

    expect(boosh.bind(boosh, {
      in: '/path/to/file',
      out: '/path/to/file',
    })).to.not.throw();
  });

  it('Should accept entry and output as valid forms of in or out', function() {
    expect(boosh.bind(boosh, {
      entry: '/path/to/file',
      out: '/path/to/file',
    })).to.not.throw();

    expect(boosh.bind(boosh, {
      in: '/path/to/file',
      output: '/path/to/file',
    })).to.not.throw();

    expect(boosh.bind(boosh, {
      entry: '/path/to/file',
      output: '/path/to/file',
      isDev: true,
    })).to.not.throw();
  });

  it('Should not export an object with custom options defined', function() {
    var config = boosh(validConfig);

    expect(config.in).to.be.undefined;
    expect(config.out).to.be.undefined;
    expect(config.isDev).to.be.undefined;
    expect(config.entry).to.be.ok;
    expect(config.output).to.be.ok;
  });

  it('Should pass the https param in to dev server', function() {
    var config = boosh(Object.assign({}, validConfig, { https: true }));
    expect(config.devServer.https).to.be.true;
  });

  it('Should pass the port param in to dev server', function() {
    var config = boosh(Object.assign({}, validConfig, { port: 1234 }));
    expect(config.devServer.port).to.equal(1234);
  });

  it('Should base input keys on filenames', function() {
    var config = boosh({
      in: 'oh-hai.js',
      out: 'some/path/',
      isDev: false,
    });

    expect(config.entry).to.have.key('oh-hai');
  });

  it('Can take a hash as input to the `in` parameter', function() {
    var obj = {
      in: {
        ohHai: 'oh-hai.js',
        login: 'src/login.js',
      },
      out: 'some/path/',
      isDev: false,
    };

    var config = boosh(obj);

    expect(config.entry).to.eql(obj.in);

    obj.isDev = true;

    config = boosh(obj);

    expect(config.entry.ohHai).to.contain(obj.in.ohHai);
    expect(config.entry.login).to.contain(obj.in.login);
  });

  it('Should allow overwriting via standard webpack config', function() {
    var config = boosh({
      in: 'app.js',
      out: 'some/path/',
      isDev: true,
    });

    expect(config.entry.app).to.be.instanceOf(Array);

    config = boosh({
      out: 'bleh',
      entry: {
        app: 'some/thang.js',
      },
    });

    expect(config.entry.app).to.equal('some/thang.js');
  });
});

<|endoftext|>


<commit_before>var sharify = require('./');

describe('sharify', function() {

  describe('constructor', function() {

    beforeEach(function () {
      sharify.data = {};
    });

    it('returns middleware that adds the data to locals', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.data.foo.should.equal('bar');
    });

    it('returns middleware that properly escapes HTML within JSON', function() {
      var locals = {};
      sharify.data.escapeHTML = '--></script>';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.script().should.include('window.__sharifyData = {"escapeHTML":"--\\>\\u003c/script>"};');
    });

    it('returns middleware that adds a sharify script to locals', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.script().should.include('window.__sharifyData = {"foo":"bar"};');
    });

    it('exports the data to be required elsewhere', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      var sd = require('./').data;
      sd.foo.should.equal('bar');
    });

    it('does not persist res.locals', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      locals.sd.location = "NY";
      locals.sharify.script().should.include('window.__sharifyData = {"foo":"bar","location":"NY"};');

      locals = {};
      sharify({}, { locals: locals }, function(){});
      locals.sharify.script().should.include('window.__sharifyData = {"foo":"bar"};');
    });

    it('does not inject locals data into the constant data', function() {
      var locals = {};
      sharify.data.foo = 'baz';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.data.foo = 'bar';
      locals.sd.foo = 'bar';
      sharify.data.foo.should.equal('baz');
      locals.sd.foo.should.equal('bar');
    });
  });

  describe('on the client', function() {

    it('loads __sharifyData', function() {
      global.window = { __sharifyData: { moo: 'bam' } };
      var sharify = require('./');
      sharify.bootstrapOnClient();
      sharify.data.moo.should.equal('bam');
    });

    it('exposes sd and sharify.data globals for client/server template reuse', function() {
      global.window = { __sharifyData: { moo: 'bam' } };
      var sharify = require('./');
      sharify.bootstrapOnClient();
      window.sharify.data.moo.should.equal('bam');
      window.sd.moo.should.equal('bam');
    });
  });
});
<commit_msg>Update specs to use containEql<commit_after>var sharify = require('./');

describe('sharify', function() {

  describe('constructor', function() {

    beforeEach(function () {
      sharify.data = {};
    });

    it('returns middleware that adds the data to locals', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.data.foo.should.equal('bar');
    });

    it('returns middleware that properly escapes HTML within JSON', function() {
      var locals = {};
      sharify.data.escapeHTML = '--></script>';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.script().should.containEql('window.__sharifyData = {"escapeHTML":"--\\>\\u003c/script>"};');
    });

    it('returns middleware that adds a sharify script to locals', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.script().should.containEql('window.__sharifyData = {"foo":"bar"};');
    });

    it('exports the data to be required elsewhere', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      var sd = require('./').data;
      sd.foo.should.equal('bar');
    });

    it('does not persist res.locals', function() {
      var locals = {};
      sharify.data.foo = 'bar';
      sharify({}, { locals: locals }, function(){});
      locals.sd.location = "NY";
      locals.sharify.script().should.containEql('window.__sharifyData = {"foo":"bar","location":"NY"};');

      locals = {};
      sharify({}, { locals: locals }, function(){});
      locals.sharify.script().should.containEql('window.__sharifyData = {"foo":"bar"};');
    });

    it('does not inject locals data into the constant data', function() {
      var locals = {};
      sharify.data.foo = 'baz';
      sharify({}, { locals: locals }, function(){});
      locals.sharify.data.foo = 'bar';
      locals.sd.foo = 'bar';
      sharify.data.foo.should.equal('baz');
      locals.sd.foo.should.equal('bar');
    });
  });

  describe('on the client', function() {

    it('loads __sharifyData', function() {
      global.window = { __sharifyData: { moo: 'bam' } };
      var sharify = require('./');
      sharify.bootstrapOnClient();
      sharify.data.moo.should.equal('bam');
    });

    it('exposes sd and sharify.data globals for client/server template reuse', function() {
      global.window = { __sharifyData: { moo: 'bam' } };
      var sharify = require('./');
      sharify.bootstrapOnClient();
      window.sharify.data.moo.should.equal('bam');
      window.sd.moo.should.equal('bam');
    });
  });
});
<|endoftext|>