Best JavaScript code snippet using mocha
sandbox_test.py
Source:sandbox_test.py  
...79  def setUp(self):80    super(ModuleOverrideImportHookTest, self).setUp()81    self.test_policies = {}82    self.path = sys.path[:]83    self.hook = sandbox.ModuleOverrideImportHook(self.test_policies)84    sys.path_importer_cache = {}85    sys.modules.pop('distutils', None)86    __import__('distutils').__path__.insert(0, 'dummy/path')87    sys.modules.pop('distutils.util', None)88    sys.modules.pop('thread', None)89    self.imported_modules = set(sys.modules)90    self.path_hooks = sys.path_hooks91  def tearDown(self):92    sys.path_hooks = self.path_hooks93    sys.path_importer_cache = {}94    sys.path = self.path95    added_modules = set(sys.modules) - self.imported_modules96    for name in added_modules:97      del sys.modules[name]98    distutils_modules = [module for module in sys.modules if99                         module.startswith('distutils')]100    for name in distutils_modules:101      del sys.modules[name]102    sys.modules.pop('thread', None)103    super(ModuleOverrideImportHookTest, self).tearDown()104  def test_load_builtin_pass_through(self):105    symbols = dir(__import__('thread'))106    del sys.modules['thread']107    self.test_policies['thread'] = sandbox.ModuleOverridePolicy(108        None, [], {}, default_pass_through=True)109    thread = self.hook.load_module('thread')110    self.assertTrue(isinstance(thread, types.ModuleType))111    self.assertTrue(isinstance(thread.__doc__, str))112    self.assertItemsEqual(symbols + ['__loader__'], dir(thread))113    self.assertEqual(self.hook, thread.__loader__)114  def test_load_builtin_no_pass_through(self):115    self.test_policies['thread'] = sandbox.ModuleOverridePolicy(116        None, [], {}, default_pass_through=False)117    thread = self.hook.load_module('thread')118    self.assertTrue(isinstance(thread, types.ModuleType))119    self.assertItemsEqual(120        ['__doc__', '__name__', '__package__', '__loader__'], dir(thread))121    self.assertEqual(self.hook, thread.__loader__)122  def test_load_with_path_hook(self):123    class DummyPathHook(object):124      def __init__(self, path):125        if path != 'dummy/path':126          raise ImportError127      def find_module(self, unused_fullname):128        return self129      def load_module(self, fullname):130        return imp.new_module('fake name: %s' % fullname)131    self.test_policies['distutils.util'] = sandbox.ModuleOverridePolicy(132        None, [], {}, default_pass_through=True)133    sys.path_hooks = [DummyPathHook]134    util = self.hook.load_module('distutils.util')135    self.assertEqual('fake name: distutils.util', util.__name__)136  def test_load_with_path_hook_cant_find(self):137    class DummyPathHook(object):138      def __init__(self, path):139        if path != 'dummy/path':140          raise ImportError141      def find_module(self, unused_fullname):142        return None143      def load_module(self, fullname):144        raise ImportError145    self.test_policies['distutils.util'] = sandbox.ModuleOverridePolicy(146        None, [], {}, default_pass_through=True)147    sys.path_hooks = [DummyPathHook]148    util = self.hook.load_module('distutils.util')149    self.assertEqual('distutils.util', util.__name__)150  def test_load_without_path_hook(self):151    self.test_policies['urllib'] = sandbox.ModuleOverridePolicy(152        None, [], {}, default_pass_through=True)153    urllib = self.hook.load_module('urllib')154    self.assertIn('urlopen', urllib.__dict__)155    self.assertEqual('urllib', urllib.__name__)156  def test_load_without_path_hook_not_found(self):157    self.test_policies['urllib'] = sandbox.ModuleOverridePolicy(158        None, [], {}, default_pass_through=True)159    self.assertRaises(ImportError, self.hook.load_module, 'fake_module')160  def test_load_already_in_sys_modules(self):161    module = imp.new_module('foo')162    sys.modules['foo'] = module163    self.assertEqual(module, self.hook.load_module('foo'))164  def test_is_package(self):165    self.assertTrue(self.hook.is_package('distutils'))166  def test_is_package_standard_lib(self):167    self.assertTrue(self.hook.is_package('email'))168  def test_is_package_not_package_standard_lib(self):169    self.assertFalse(self.hook.is_package('urllib'))170  def test_is_package_not_package(self):171    self.assertFalse(self.hook.is_package('distutils.util'))172  def test_is_package_does_not_exist(self):173    self.assertRaises(ImportError, self.hook.is_package, 'foo.bar')174  def test_get_source(self):175    with open(__import__('distutils').__file__.replace('.pyc', '.py')) as f:176      source = f.read()177    self.assertEqual(source, self.hook.get_source('distutils'))178  def test_get_source_does_not_exist(self):179    self.assertRaises(ImportError, self.hook.get_source, 'foo.bar')180  def test_get_source_standard_library(self):181    # The expected value is hard to find if the standard library might or might182    # not be zipped so just check that a value is found.183    self.assertTrue(self.hook.get_source('urllib'))184  def test_get_code(self):185    filename = __import__('distutils').__file__.replace('.pyc', '.py')186    with open(filename) as f:187      expected_code = compile(f.read(), filename, 'exec')188    self.assertEqual(expected_code, self.hook.get_code('distutils'))189  def test_get_code_does_not_exist(self):190    self.assertRaises(ImportError, self.hook.get_code, 'foo.bar')191  def test_get_code_standard_library(self):192    # The expected value is hard to find if the standard library might or might193    # not be zipped so just check that a value is found.194    self.assertTrue(self.hook.get_code('urllib'))195  def test_os_module_policy(self):196    hooked_os = imp.new_module('os')197    hooked_os.__dict__.update(os.__dict__)198    sandbox._MODULE_OVERRIDE_POLICIES['os'].apply_policy(hooked_os.__dict__)199    self.assertEqual(stubs.return_minus_one, hooked_os.getpid)200    self.assertNotIn('execv', hooked_os.__dict__)201    self.assertEqual(stubs.os_error_not_implemented, hooked_os.unlink)202    self.assertEqual(stubs.os_error_not_implemented, hooked_os.readlink)203    self.assertEqual(os.walk, hooked_os.walk)204class CModuleImportHookTest(unittest.TestCase):205  def test_find_module_enabled_module(self):206    hook = sandbox.CModuleImportHook([re.compile(r'lxml\.')])207    self.assertIsNone(hook.find_module('lxml'))208    lxml = __import__('lxml')209    self.assertIsNone(hook.find_module('lxml.etree', lxml.__path__))210  def test_find_module_disabled_module(self):211    hook = sandbox.CModuleImportHook([re.compile(r'numpy\.')])212    self.assertIsNone(hook.find_module('lxml'))213    lxml = __import__('lxml')214    self.assertEqual(hook, hook.find_module('lxml.etree', lxml.__path__))215  def test_find_module_not_c_module(self):216    hook = sandbox.CModuleImportHook([])217    self.assertIsNone(hook.find_module('httplib'))218  def test_find_module_whitelisted(self):219    hook = sandbox.CModuleImportHook([])220    for name in sandbox._WHITE_LIST_C_MODULES:221      self.assertIsNone(hook.find_module(name))222  def test_find_module_not_whitelisted(self):223    hook = sandbox.CModuleImportHook([])224    self.assertEqual(hook, hook.find_module('__builtin__'))225  def test_find_module_not_whitelisted_enabled_via_libaries(self):226    hook = sandbox.CModuleImportHook([re.compile(r'__builtin__')])227    self.assertIsNone(hook.find_module('__builtin__'))228  def test_load_module(self):229    hook = sandbox.CModuleImportHook([])230    self.assertRaises(ImportError, hook.load_module, 'lxml')231class PathOverrideImportHookTest(unittest.TestCase):232  def setUp(self):233    self.saved_lxml = lxml234    self.saved_pil = PIL235    self.saved_urllib = urllib236  def tearDown(self):237    sys.modules['urllib'] = self.saved_urllib238    sys.modules['PIL'] = self.saved_pil239    sys.modules['lxml'] = self.saved_lxml240  def test_package_success(self):241    hook = sandbox.PathOverrideImportHook(['lxml'])242    self.assertEqual(hook, hook.find_module('lxml'))243    del sys.modules['lxml']244    hooked_lxml = hook.load_module('lxml')245    self.assertEqual(hooked_lxml.__file__, lxml.__file__)246    self.assertEqual(hooked_lxml.__path__, lxml.__path__)247    self.assertEqual(hooked_lxml.__loader__, hook)248    self.assertEqual([os.path.dirname(self.saved_lxml.__file__)],249                     hook.extra_accessible_paths)250    self.assertFalse(hook.extra_sys_paths)251  def test_package_success_pil_in_sys_path(self):252    hook = sandbox.PathOverrideImportHook(['PIL'])253    self.assertEqual(hook, hook.find_module('PIL'))254    del sys.modules['PIL']255    hooked_pil = hook.load_module('PIL')256    self.assertEqual(hooked_pil.__file__, PIL.__file__)257    self.assertEqual(hooked_pil.__path__, PIL.__path__)258    self.assertEqual(hooked_pil.__loader__, hook)259    self.assertFalse(hook.extra_accessible_paths)260    self.assertEqual([os.path.dirname(self.saved_pil.__file__)],261                     hook.extra_sys_paths)262  def test_module_success(self):263    hook = sandbox.PathOverrideImportHook(['urllib'])264    self.assertEqual(hook, hook.find_module('urllib'))265    del sys.modules['urllib']266    hooked_urllib = hook.load_module('urllib')267    self.assertEqual(hooked_urllib.__file__.replace('.pyc', '.py'),268                     urllib.__file__.replace('.pyc', '.py'))269    self.assertEqual(hooked_urllib.__loader__, hook)270    self.assertNotIn('__path__', hooked_urllib.__dict__)271    self.assertFalse(hook.extra_accessible_paths)272    self.assertFalse(hook.extra_sys_paths)273  def test_disabled_modules(self):274    hook = sandbox.PathOverrideImportHook(['lxml'])275    self.assertFalse(hook.find_module('lxml.foo'))276    self.assertFalse(hook.find_module('numpy'))277    self.assertFalse(hook.find_module('os'))278  def test_module_not_installed(self):279    hook = sandbox.PathOverrideImportHook(['foo'])280    self.assertFalse(hook.find_module('foo'))281    self.assertFalse(hook.extra_accessible_paths)282    self.assertFalse(hook.extra_sys_paths)283  def test_import_alread_in_sys_modules(self):284    hook = sandbox.PathOverrideImportHook(['lxml'])285    self.assertEqual(os, hook.load_module('os'))286class PathRestrictingImportHookTest(unittest.TestCase):287  def setUp(self):288    self.mox = mox.Mox()289    self.mox.StubOutWithMock(imp, 'find_module')290    self.mox.StubOutWithMock(stubs.FakeFile, 'is_file_accessible')291    self.hook = sandbox.PathRestrictingImportHook([re.compile(r'lxml(\..*)?$')])292  def tearDown(self):293    self.mox.UnsetStubs()294  def test_accessible(self):295    imp.find_module('bar', ['foo']).AndReturn((None, 'foo/bar.py',296                                               (None, None, imp.PY_SOURCE)))297    stubs.FakeFile.is_file_accessible('foo/bar.py').AndReturn(True)298    self.mox.ReplayAll()299    self.assertIsNone(self.hook.find_module('foo.bar', ['foo']))300  def test_not_accessible(self):301    imp.find_module('bar', ['foo']).AndReturn((None, 'foo/bar.py',302                                               (None, None, imp.PY_SOURCE)))303    stubs.FakeFile.is_file_accessible('foo/bar.py').AndReturn(False)304    self.mox.ReplayAll()305    self.assertEqual(self.hook, self.hook.find_module('foo.bar', ['foo']))...hook.js
Source:hook.js  
1/**2 * (C) Copyright 2007-2008 Jeremy Maitin-Shepard3 * (C) Copyright 2010 John J. Foerch4 *5 * Use, modification, and distribution are subject to the terms specified in the6 * COPYING file.7**/8require("coroutine.js");9/* Adds the specified function to the specified hook.  To add a local10 * hook, invoke this function as:  add_hook.call(context, hook_name, ...).11 * Note: hook_name must be a string */12function add_hook (hook_name, func, prepend) {13    if (!(hook_name in this))14        this[hook_name] = [];15    var hook = this[hook_name];16    if (hook.indexOf(func) != -1)17        return func;18    if (prepend)19        hook.unshift(func);20    else21        hook.push(func);22    return func;23}24/**25 * Call every function in the array `hook' with the remaining26 * arguments of this function.  Note: This should only be used by27 * define_hook and friends to define hook.run(...) functions.  Hooks28 * should always be run by calling hook.run(...).29 */30function run_hooks (hook, args) {31    if (hook == null)32        return;33    for (let i = 0, hlen = hook.length; i < hlen; ++i)34        hook[i].apply(null, Array.prototype.slice.call(args));35}36function run_hooks_until_success (hook, args) {37    if (hook == null)38        return false;39    var result;40    for (let i = 0, hlen = hook.length; i < hlen; ++i)41        if ((result = hook[i].apply(null, Array.prototype.slice.call(args))))42            return result;43    return false;44}45function run_hooks_until_failure (hook, args) {46    if (hook == null)47        return true;48    for (let i = 0, hlen = hook.length; i < hlen; ++i)49        if (!hook[i].apply(null, Array.prototype.slice.call(args)))50            return false;51    return true;52}53function run_coroutine_hooks (hook, args) {54    if (hook == null)55        yield co_return();56    for (let i = 0, hlen = hook.length; i < hlen; ++i)57        yield hook[i].apply(null, Array.prototype.slice.call(args));58}59function run_coroutine_hooks_until_success (hook, args) {60    if (hook == null)61        yield co_return(false);62    var result;63    for (let i = 0, hlen = hook.length; i < hlen; ++i)64        if ((result = yield hook[i].apply(null, Array.prototype.slice.call(args))))65            yield co_return(result);66    yield co_return(false);67}68function run_coroutine_hooks_until_failure (hook, args) {69    if (hook == null)70        yield co_return(true);71    for (let i = 0, hlen = hook.length; i < hlen; ++i)72        if (!(yield hook[i].apply(null, Array.prototype.slice.call(args))))73            yield co_return(false);74    yield co_return(true);75}76const RUN_HOOK = 'RUN_HOOK';77const RUN_HOOK_UNTIL_SUCCESS = 'RUN_HOOK_UNTIL_SUCCESS';78const RUN_HOOK_UNTIL_FAILURE = 'RUN_HOOK_UNTIL_FAILURE';79/* This should only be used by define_hook functions */80function initialize_hook (run, hook_name, hook_type, doc_string, extra_doc_string) {81    var docstrings = {82        RUN_HOOK: "Each hook function is run in sequence.",83        RUN_HOOK_UNTIL_SUCCESS:84        "Each hook function is run in sequence until one returns a "+85            "logically true value.  That value is returned.",86        RUN_HOOK_UNTIL_FAILURE:87        "Each hook function is run in sequence until one returns a "+88            "logically false value.  If no function returns such a "+89            "value, then the result of the hook will be `true'."90    };91    var h = this[hook_name];92    if (h == null)93        h = this[hook_name] = [];94    if (hook_type == null)95        hook_type = RUN_HOOK;96    h.run = run;97    h.hook_type = hook_type;98    h.hook_name = hook_name;99    h.doc_string =100        (doc_string? doc_string + "\n" : "") +101        docstrings[hook_type] +102        (extra_doc_string? "\n" + extra_doc_string : "");103    h.source_code_reference = get_caller_source_code_reference(1);104    return h;105}106function define_hook (hook_name, hook_type, doc_string) {107    const prototype = {108        RUN_HOOK: function () {109            run_hooks(this, arguments);110        },111        RUN_HOOK_UNTIL_SUCCESS: function () {112            return run_hooks_until_success(this, arguments);113        },114        RUN_HOOK_UNTIL_FAILURE: function () {115            return run_hooks_until_failure(this, arguments);116        }117    };118    initialize_hook(prototype[hook_type || RUN_HOOK],119                    hook_name, hook_type, doc_string);120}121function define_coroutine_hook (hook_name, hook_type, doc_string) {122    const prototype = {123        RUN_HOOK: function () {124            yield run_coroutine_hooks(this, arguments);125        },126        RUN_HOOK_UNTIL_SUCCESS: function () {127            var result = yield run_coroutine_hooks_until_success(this, arguments);128            yield co_return(result);129        },130        RUN_HOOK_UNTIL_FAILURE: function () {131            var result = yield run_coroutine_hooks_until_failure(this, arguments);132            yield co_return(result);133        }134    };135    initialize_hook(prototype[hook_type || RUN_HOOK],136                    hook_name, hook_type, doc_string);137}138function simple_local_hook_definer (extra_doc_string) {139    const prototype = {140        RUN_HOOK: function (x) {141            var hook_name = this.hook_name;142            if (hook_name in x)143                run_hooks(x[hook_name], arguments);144            run_hooks(this, arguments);145        },146        RUN_HOOK_UNTIL_SUCCESS: function (x) {147            var hook_name = this.hook_name;148            var result;149            if ((hook_name in x) && (result = run_hooks_until_success(x[hook_name], arguments)))150                return result;151            return run_hooks_until_success(conkeror[hook_name], arguments);152        },153        RUN_HOOK_UNTIL_FAILURE: function (x) {154            var hook_name = this.hook_name;155            if ((hook_name in x) && !run_hooks_until_success(x[hook_name], arguments))156                return false;157            return run_hooks_until_failure(conkeror[hook_name], arguments);158        }159    };160    return function (hook_name, hook_type, doc_string) {161        initialize_hook(prototype[hook_type || RUN_HOOK],162                        hook_name, hook_type, doc_string,163                        extra_doc_string);164    };165}166function simple_local_coroutine_hook_definer (extra_doc_string) {167    const prototype = {168        RUN_HOOK: function (x) {169            var hook_name = this.hook_name;170            if (hook_name in x)171                yield run_coroutine_hooks(x[hook_name], arguments);172            yield run_coroutine_hooks(this, arguments);173        },174        RUN_HOOK_UNTIL_SUCCESS: function (x) {175            var hook_name = this.hook_name;176            var result;177            if ((hook_name in x) &&178                (result = yield run_coroutine_hooks_until_success(x[hook_name], arguments)))179            {180                yield co_return(result);181            }182            result = yield run_coroutine_hooks_until_success(conkeror[hook_name], arguments);183            yield co_return(result);184        },185        RUN_HOOK_UNTIL_FAILURE: function (x) {186            var hook_name = this.hook_name;187            if ((hook_name in x) &&188                !(yield run_coroutine_hooks_until_success(x[hook_name], arguments)))189            {190                yield co_return(false);191            }192            var result = yield run_coroutine_hooks_until_failure(conkeror[hook_name], arguments);193            yield co_return(result);194        }195    };196    return function (hook_name, hook_type, doc_string) {197        initialize_hook(prototype[hook_type || RUN_HOOK],198                        hook_name, hook_type, doc_string,199                        extra_doc_string);200    };201}202function local_hook_definer (prop_name, extra_doc_string) {203    const prototype = {204        RUN_HOOK: function (x) {205            var hook_name = this.hook_name;206            if (hook_name in x)207                run_hooks(x[hook_name], arguments);208            if (hook_name in x[prop_name])209                run_hooks(x[prop_name][hook_name], arguments);210            run_hooks(this, arguments);211        },212        RUN_HOOK_UNTIL_SUCCESS: function (x) {213            var hook_name = this.hook_name;214            var result;215            if ((hook_name in x) && (result = run_hooks_until_success(x[hook_name], arguments)))216                return result;217            if ((hook_name in x[prop_name]) && (result = run_hooks_until_success(x[prop_name][hook_name], arguments)))218                return result;219            return run_hooks_until_success(conkeror[hook_name], arguments);220        },221        RUN_HOOK_UNTIL_FAILURE: function (x) {222            var hook_name = this.hook_name;223            if ((hook_name in x) && !run_hooks_until_success(x[hook_name], arguments))224                return false;225            if ((hook_name in x[prop_name]) && !run_hooks_until_success(x[prop_name][hook_name], arguments))226                return false;227            return run_hooks_until_failure(conkeror[hook_name], arguments);228        }229    };230    return function (hook_name, hook_type, doc_string) {231        initialize_hook(prototype[hook_type || RUN_HOOK],232                        hook_name, hook_type, doc_string,233                        extra_doc_string);234    };235}236function local_coroutine_hook_definer (prop_name, extra_doc_string) {237    const prototype = {238        RUN_HOOK: function (x) {239            var hook_name = this.hook_name;240            if (hook_name in x)241                yield run_coroutine_hooks(x[hook_name], arguments);242            if (hook_name in x[prop_name])243                yield run_coroutine_hooks(x[prop_name][hook_name], arguments);244            yield run_coroutine_hooks(this, arguments);245        },246        RUN_HOOK_UNTIL_SUCCESS: function (x) {247            var hook_name = this.hook_name;248            var result;249            if ((hook_name in x) &&250                (result = yield run_coroutine_hooks_until_success(x[hook_name], arguments)))251            {252                yield co_return(result);253            }254            if ((hook_name in x[prop_name]) &&255                (result = yield run_coroutine_hooks_until_success(x[prop_name][hook_name], arguments)))256            {257                yield co_return(result);258            }259            result = yield run_coroutine_hooks_until_success(conkeror[hook_name], arguments);260            yield co_return(result);261        },262        RUN_HOOK_UNTIL_FAILURE: function (x) {263            var hook_name = this.hook_name;264            if ((hook_name in x) &&265                !(yield run_coroutine_hooks_until_success(x[hook_name], arguments)))266            {267                yield co_return(false);268            }269            if ((hook_name in x[prop_name]) &&270                !(yield run_coroutine_hooks_until_success(x[prop_name][hook_name], arguments)))271            {272                yield co_return(false);273            }274            var result = yield run_coroutine_hooks_until_failure(conkeror[hook_name], arguments);275            yield co_return(result);276        }277    };278    return function (hook_name, hook_type, doc_string) {279        initialize_hook(prototype[hook_type || RUN_HOOK],280                        hook_name, hook_type, doc_string,281                        extra_doc_string);282    };283}284function remove_hook (hook_name, func) {285    var hook = this[hook_name];286    var index;287    if (hook && (index = hook.indexOf(func)) != -1)288        hook.splice(index, 1);289}...core.plugin.tests.js
Source:core.plugin.tests.js  
1describe('Chart.plugins', function() {2	beforeEach(function() {3		this._plugins = Chart.plugins.getAll();4		Chart.plugins.clear();5	});6	afterEach(function() {7		Chart.plugins.clear();8		Chart.plugins.register(this._plugins);9		delete this._plugins;10	});11	describe('Chart.plugins.register', function() {12		it('should register a plugin', function() {13			Chart.plugins.register({});14			expect(Chart.plugins.count()).toBe(1);15			Chart.plugins.register({});16			expect(Chart.plugins.count()).toBe(2);17		});18		it('should register an array of plugins', function() {19			Chart.plugins.register([{}, {}, {}]);20			expect(Chart.plugins.count()).toBe(3);21		});22		it('should succeed to register an already registered plugin', function() {23			var plugin = {};24			Chart.plugins.register(plugin);25			expect(Chart.plugins.count()).toBe(1);26			Chart.plugins.register(plugin);27			expect(Chart.plugins.count()).toBe(1);28			Chart.plugins.register([{}, plugin, plugin]);29			expect(Chart.plugins.count()).toBe(2);30		});31	});32	describe('Chart.plugins.unregister', function() {33		it('should unregister a plugin', function() {34			var plugin = {};35			Chart.plugins.register(plugin);36			expect(Chart.plugins.count()).toBe(1);37			Chart.plugins.unregister(plugin);38			expect(Chart.plugins.count()).toBe(0);39		});40		it('should unregister an array of plugins', function() {41			var plugins = [{}, {}, {}];42			Chart.plugins.register(plugins);43			expect(Chart.plugins.count()).toBe(3);44			Chart.plugins.unregister(plugins.slice(0, 2));45			expect(Chart.plugins.count()).toBe(1);46		});47		it('should succeed to unregister a plugin not registered', function() {48			var plugin = {};49			Chart.plugins.register(plugin);50			expect(Chart.plugins.count()).toBe(1);51			Chart.plugins.unregister({});52			expect(Chart.plugins.count()).toBe(1);53			Chart.plugins.unregister([{}, plugin]);54			expect(Chart.plugins.count()).toBe(0);55		});56	});57	describe('Chart.plugins.notify', function() {58		it('should call inline plugins with arguments', function() {59			var plugin = {hook: function() {}};60			var chart = window.acquireChart({61				plugins: [plugin]62			});63			spyOn(plugin, 'hook');64			Chart.plugins.notify(chart, 'hook', 42);65			expect(plugin.hook.calls.count()).toBe(1);66			expect(plugin.hook.calls.first().args[0]).toBe(chart);67			expect(plugin.hook.calls.first().args[1]).toBe(42);68			expect(plugin.hook.calls.first().args[2]).toEqual({});69		});70		it('should call global plugins with arguments', function() {71			var plugin = {hook: function() {}};72			var chart = window.acquireChart({});73			spyOn(plugin, 'hook');74			Chart.plugins.register(plugin);75			Chart.plugins.notify(chart, 'hook', 42);76			expect(plugin.hook.calls.count()).toBe(1);77			expect(plugin.hook.calls.first().args[0]).toBe(chart);78			expect(plugin.hook.calls.first().args[1]).toBe(42);79			expect(plugin.hook.calls.first().args[2]).toEqual({});80		});81		it('should call plugin only once even if registered multiple times', function() {82			var plugin = {hook: function() {}};83			var chart = window.acquireChart({84				plugins: [plugin, plugin]85			});86			spyOn(plugin, 'hook');87			Chart.plugins.register([plugin, plugin]);88			Chart.plugins.notify(chart, 'hook');89			expect(plugin.hook.calls.count()).toBe(1);90		});91		it('should call plugins in the correct order (global first)', function() {92			var results = [];93			var chart = window.acquireChart({94				plugins: [{95					hook: function() {96						results.push(1);97					}98				}, {99					hook: function() {100						results.push(2);101					}102				}, {103					hook: function() {104						results.push(3);105					}106				}]107			});108			Chart.plugins.register([{109				hook: function() {110					results.push(4);111				}112			}, {113				hook: function() {114					results.push(5);115				}116			}, {117				hook: function() {118					results.push(6);119				}120			}]);121			var ret = Chart.plugins.notify(chart, 'hook');122			expect(ret).toBeTruthy();123			expect(results).toEqual([4, 5, 6, 1, 2, 3]);124		});125		it('should return TRUE if no plugin explicitly returns FALSE', function() {126			var chart = window.acquireChart({127				plugins: [{128					hook: function() {}129				}, {130					hook: function() {131						return null;132					}133				}, {134					hook: function() {135						return 0;136					}137				}, {138					hook: function() {139						return true;140					}141				}, {142					hook: function() {143						return 1;144					}145				}]146			});147			var plugins = chart.config.plugins;148			plugins.forEach(function(plugin) {149				spyOn(plugin, 'hook').and.callThrough();150			});151			var ret = Chart.plugins.notify(chart, 'hook');152			expect(ret).toBeTruthy();153			plugins.forEach(function(plugin) {154				expect(plugin.hook).toHaveBeenCalled();155			});156		});157		it('should return FALSE if any plugin explicitly returns FALSE', function() {158			var chart = window.acquireChart({159				plugins: [{160					hook: function() {}161				}, {162					hook: function() {163						return null;164					}165				}, {166					hook: function() {167						return false;168					}169				}, {170					hook: function() {171						return 42;172					}173				}, {174					hook: function() {175						return 'bar';176					}177				}]178			});179			var plugins = chart.config.plugins;180			plugins.forEach(function(plugin) {181				spyOn(plugin, 'hook').and.callThrough();182			});183			var ret = Chart.plugins.notify(chart, 'hook');184			expect(ret).toBeFalsy();185			expect(plugins[0].hook).toHaveBeenCalled();186			expect(plugins[1].hook).toHaveBeenCalled();187			expect(plugins[2].hook).toHaveBeenCalled();188			expect(plugins[3].hook).not.toHaveBeenCalled();189			expect(plugins[4].hook).not.toHaveBeenCalled();190		});191	});192	describe('config.options.plugins', function() {193		it('should call plugins with options at last argument', function() {194			var plugin = {id: 'foo', hook: function() {}};195			var chart = window.acquireChart({196				options: {197					plugins: {198						foo: {a: '123'},199					}200				}201			});202			spyOn(plugin, 'hook');203			Chart.plugins.register(plugin);204			Chart.plugins.notify(chart, 'hook');205			Chart.plugins.notify(chart, 'hook', ['bla']);206			Chart.plugins.notify(chart, 'hook', ['bla', 42]);207			expect(plugin.hook.calls.count()).toBe(3);208			expect(plugin.hook.calls.argsFor(0)[1]).toEqual({a: '123'});209			expect(plugin.hook.calls.argsFor(1)[2]).toEqual({a: '123'});210			expect(plugin.hook.calls.argsFor(2)[3]).toEqual({a: '123'});211		});212		it('should call plugins with options associated to their identifier', function() {213			var plugins = {214				a: {id: 'a', hook: function() {}},215				b: {id: 'b', hook: function() {}},216				c: {id: 'c', hook: function() {}}217			};218			Chart.plugins.register(plugins.a);219			var chart = window.acquireChart({220				plugins: [plugins.b, plugins.c],221				options: {222					plugins: {223						a: {a: '123'},224						b: {b: '456'},225						c: {c: '789'}226					}227				}228			});229			spyOn(plugins.a, 'hook');230			spyOn(plugins.b, 'hook');231			spyOn(plugins.c, 'hook');232			Chart.plugins.notify(chart, 'hook');233			expect(plugins.a.hook).toHaveBeenCalled();234			expect(plugins.b.hook).toHaveBeenCalled();235			expect(plugins.c.hook).toHaveBeenCalled();236			expect(plugins.a.hook.calls.first().args[1]).toEqual({a: '123'});237			expect(plugins.b.hook.calls.first().args[1]).toEqual({b: '456'});238			expect(plugins.c.hook.calls.first().args[1]).toEqual({c: '789'});239		});240		it('should not called plugins when config.options.plugins.{id} is FALSE', function() {241			var plugins = {242				a: {id: 'a', hook: function() {}},243				b: {id: 'b', hook: function() {}},244				c: {id: 'c', hook: function() {}}245			};246			Chart.plugins.register(plugins.a);247			var chart = window.acquireChart({248				plugins: [plugins.b, plugins.c],249				options: {250					plugins: {251						a: false,252						b: false253					}254				}255			});256			spyOn(plugins.a, 'hook');257			spyOn(plugins.b, 'hook');258			spyOn(plugins.c, 'hook');259			Chart.plugins.notify(chart, 'hook');260			expect(plugins.a.hook).not.toHaveBeenCalled();261			expect(plugins.b.hook).not.toHaveBeenCalled();262			expect(plugins.c.hook).toHaveBeenCalled();263		});264		it('should call plugins with default options when plugin options is TRUE', function() {265			var plugin = {id: 'a', hook: function() {}};266			Chart.defaults.global.plugins.a = {a: 42};267			Chart.plugins.register(plugin);268			var chart = window.acquireChart({269				options: {270					plugins: {271						a: true272					}273				}274			});275			spyOn(plugin, 'hook');276			Chart.plugins.notify(chart, 'hook');277			expect(plugin.hook).toHaveBeenCalled();278			expect(plugin.hook.calls.first().args[1]).toEqual({a: 42});279		});280		it('should call plugins with default options if plugin config options is undefined', function() {281			var plugin = {id: 'a', hook: function() {}};282			Chart.defaults.global.plugins.a = {a: 'foobar'};283			Chart.plugins.register(plugin);284			spyOn(plugin, 'hook');285			var chart = window.acquireChart();286			Chart.plugins.notify(chart, 'hook');287			expect(plugin.hook).toHaveBeenCalled();288			expect(plugin.hook.calls.first().args[1]).toEqual({a: 'foobar'});289		});290	});...test_odbc.py
Source:test_odbc.py  
...32                **dict(login='login', password='password', host='host', schema='schema', port=1234),33                **conn_params,34            }35        )36        hook = OdbcHook(**hook_params)37        hook.get_connection = mock.Mock()38        hook.get_connection.return_value = connection39        return hook40    def test_driver_in_extra(self):41        conn_params = dict(extra=json.dumps(dict(Driver='Fake Driver', Fake_Param='Fake Param')))42        hook = self.get_hook(conn_params=conn_params)43        expected = (44            'DRIVER={Fake Driver};'45            'SERVER=host;'46            'DATABASE=schema;'47            'UID=login;'48            'PWD=password;'49            'Fake_Param=Fake Param;'50        )...hooks.py
Source:hooks.py  
...51        else:52            _RUNNING_HOOKS[tool] = False53            return res54    return wrapper55class Hook(object):56    """A compiler class that may be hooked"""57    def __init__(self, target, toolchain):58        _HOOKS.clear()59        self._cmdline_hooks = {}60        self.toolchain = toolchain61        target.init_hooks(self, toolchain)62    # Hook various functions directly63    @staticmethod64    def _hook_add(hook_type, hook_step, function):65        """Add a hook to a compile function66        Positional arguments:67        hook_type - one of the _HOOK_TYPES68        hook_step - one of the _HOOK_STEPS69        function - the function to add to the list of hooks...hooks.js
Source:hooks.js  
...39			if (Array.isArray(data.method) && data.method.every(method => typeof method === 'function' || typeof method === 'string')) {40				// Go go gadget recursion!41				async.eachSeries(data.method, function (method, next) {42					const singularData = Object.assign({}, data, { method: method });43					Plugins.registerHook(id, singularData, next);44				}, callback);45			} else if (typeof data.method === 'string' && data.method.length > 0) {46				method = data.method.split('.').reduce(function (memo, prop) {47					if (memo && memo[prop]) {48						return memo[prop];49					}50					// Couldn't find method by path, aborting51					return null;52				}, Plugins.libraries[data.id]);53				// Write the actual method reference to the hookObj54				data.method = method;55				Plugins.internals._register(data, callback);56			} else if (typeof data.method === 'function') {57				Plugins.internals._register(data, callback);58			} else {59				winston.warn('[plugins/' + id + '] Hook method mismatch: ' + data.hook + ' => ' + data.method);60				return callback();61			}62		}63	};64	Plugins.unregisterHook = function (id, hook, method) {65		var hooks = Plugins.loadedHooks[hook] || [];66		Plugins.loadedHooks[hook] = hooks.filter(function (hookData) {67			return hookData && hookData.id !== id && hookData.method !== method;68		});69	};70	Plugins.fireHook = function (hook, params, callback) {71		callback = typeof callback === 'function' ? callback : function () {};72		var hookList = Plugins.loadedHooks[hook];73		var hookType = hook.split(':')[0];74		winston.verbose('[plugins/fireHook]', hook);75		switch (hookType) {76		case 'filter':77			fireFilterHook(hook, hookList, params, callback);78			break;79		case 'action':80			fireActionHook(hook, hookList, params, callback);81			break;82		case 'static':83			fireStaticHook(hook, hookList, params, callback);84			break;85		default:86			winston.warn('[plugins] Unknown hookType: ' + hookType + ', hook : ' + hook);87			callback();88			break;89		}90	};91	function fireFilterHook(hook, hookList, params, callback) {92		if (!Array.isArray(hookList) || !hookList.length) {93			return callback(null, params);94		}95		async.reduce(hookList, params, function (params, hookObj, next) {96			if (typeof hookObj.method !== 'function') {97				if (global.env === 'development') {98					winston.warn('[plugins] Expected method for hook \'' + hook + '\' in plugin \'' + hookObj.id + '\' not found, skipping.');99				}100				return next(null, params);101			}102			hookObj.method(params, next);103		}, callback);104	}105	function fireActionHook(hook, hookList, params, callback) {106		if (!Array.isArray(hookList) || !hookList.length) {107			return callback();108		}109		async.each(hookList, function (hookObj, next) {110			if (typeof hookObj.method !== 'function') {111				if (global.env === 'development') {112					winston.warn('[plugins] Expected method for hook \'' + hook + '\' in plugin \'' + hookObj.id + '\' not found, skipping.');113				}114				return next();115			}116			hookObj.method(params);117			next();118		}, callback);119	}120	function fireStaticHook(hook, hookList, params, callback) {121		if (!Array.isArray(hookList) || !hookList.length) {122			return callback();123		}124		async.each(hookList, function (hookObj, next) {125			if (typeof hookObj.method === 'function') {126				var timedOut = false;127				var timeoutId = setTimeout(function () {128					winston.warn('[plugins] Callback timed out, hook \'' + hook + '\' in plugin \'' + hookObj.id + '\'');129					timedOut = true;130					next();131				}, 5000);132				try {133					hookObj.method(params, function () {134						clearTimeout(timeoutId);...Hook.py
Source:Hook.py  
...22#                                                                              #23# ##############################################################################24import Framework25import datetime26class Hook(Framework.TestCase):27    def setUp(self):28        Framework.TestCase.setUp(self)29        self.hook = self.g.get_user().get_repo("PyGithub").get_hook(257993)30    def testAttributes(self):31        self.assertTrue(self.hook.active)  # WTF32        self.assertEqual(self.hook.config, {"url": "http://foobar.com"})33        self.assertEqual(self.hook.created_at, datetime.datetime(2012, 5, 19, 6, 1, 45))34        self.assertEqual(self.hook.events, ["push"])35        self.assertEqual(self.hook.id, 257993)36        self.assertEqual(self.hook.last_response.status, "ok")37        self.assertEqual(self.hook.last_response.message, "OK")38        self.assertEqual(self.hook.last_response.code, 200)39        self.assertEqual(self.hook.name, "web")40        self.assertEqual(self.hook.updated_at, datetime.datetime(2012, 5, 29, 18, 49, 47))...hooks_helper_test.py
Source:hooks_helper_test.py  
1# Copyright 2017 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for hooks_helper."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19import unittest20import tensorflow as tf  # pylint: disable=g-bad-import-order21from official.utils.logs import hooks_helper22class BaseTest(unittest.TestCase):23  def test_raise_in_non_list_names(self):24    with self.assertRaises(ValueError):25      hooks_helper.get_train_hooks(26          'LoggingTensorHook, ProfilerHook', model_dir="", batch_size=256)27  def test_raise_in_invalid_names(self):28    invalid_names = ['StepCounterHook', 'StopAtStepHook']29    with self.assertRaises(ValueError):30      hooks_helper.get_train_hooks(invalid_names, model_dir="", batch_size=256)31  def validate_train_hook_name(self,32                               test_hook_name,33                               expected_hook_name,34                               **kwargs):35    returned_hook = hooks_helper.get_train_hooks(36        [test_hook_name], model_dir="", **kwargs)37    self.assertEqual(len(returned_hook), 1)38    self.assertIsInstance(returned_hook[0], tf.estimator.SessionRunHook)39    self.assertEqual(returned_hook[0].__class__.__name__.lower(),40                     expected_hook_name)41  def test_get_train_hooks_logging_tensor_hook(self):42    self.validate_train_hook_name('LoggingTensorHook', 'loggingtensorhook')43  def test_get_train_hooks_profiler_hook(self):44    self.validate_train_hook_name('ProfilerHook', 'profilerhook')45  def test_get_train_hooks_examples_per_second_hook(self):46    self.validate_train_hook_name('ExamplesPerSecondHook',47                                  'examplespersecondhook')48  def test_get_logging_metric_hook(self):49    test_hook_name = 'LoggingMetricHook'50    self.validate_train_hook_name(test_hook_name, 'loggingmetrichook')51if __name__ == '__main__':...Using AI Code Generation
1const { before, after } = require('mocha');2const { Builder, By, Key, until } = require('selenium-webdriver');3describe('My First Test', function() {4  let driver;5  before(async function() {6    driver = await new Builder().forBrowser('chrome').build();7  });8  after(async function() {9    await driver.quit();10  });11  it('should open browser', async function() {12    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);13    await driver.wait(until.titleIs('webdriver - Google Search'), 1000);14  });15});16const { before, after } = require('mocha');17const { Builder, By, Key, until } = require('selenium-webdriver');18describe('My First Test', function() {19  let driver;20  before(async function() {21    driver = await new Builder().forBrowser('firefox').build();22  });23  after(async function() {24    await driver.quit();25  });26  it('should open browser', async function() {27    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN);28    await driver.wait(until.titleIs('webdriver - Google Search'), 1000);29  });30});Using AI Code Generation
1const {After, Before} = require('cucumber');2Before(function () {3});4After(function () {5});6const {Given, When, Then} = require('cucumber');7Given('I am on the Google search page', function () {8    return 'pending';9});10When('I search for {string}', function (string) {11    return 'pending';12});13Then('the page title should start with {string}', function (string) {14    return 'pending';15});16Then('the search result should contain {string}', function (string) {17    return 'pending';18});191 scenario (1 passed)204 steps (4 passed)211 scenario (1 passed)224 steps (4 passed)231 scenario (1 passed)244 steps (4 passed)251 scenario (1 passed)264 steps (4 passed)271 scenario (1 passed)284 steps (4 passed)Using AI Code Generation
1const { Before, After, setDefaultTimeout } = require('cucumber');2setDefaultTimeout(60 * 1000);3Before(function (scenario) {4});5After(function (scenario) {6});7const { Before, After, setDefaultTimeout } = require('cucumber');8setDefaultTimeout(60 * 1000);9Before(function (scenario) {10});11After(function (scenario) {12});13const { Before, After, setDefaultTimeout } = require('cucumber');14setDefaultTimeout(60 * 1000);15Before(function (scenario) {16});17After(function (scenario) {18});19const { Before, After, setDefaultTimeout } = require('cucumber');20setDefaultTimeout(60 * 1000);21Before(function (scenario) {22});23After(function (scenario) {24});25const { Before, After, setDefaultTimeout } = require('cucumber');26setDefaultTimeout(60 * 1000);27Before(function (scenario) {28});29After(function (scenario) {30});31const { Before, After, setDefaultTimeout } = require('cucumber');32setDefaultTimeout(60 * 1000);33Before(function (scenario) {34});35After(function (scenario) {36});37const { Before, After, setDefaultTimeout } = require('cucumber');38setDefaultTimeout(60 * 1000);39Before(function (scenario) {40});41After(function (scenario) {42});Using AI Code Generation
1const { before, after, beforeEach, afterEach } = require('mocha');2const { expect } = require('chai');3describe('Test Hooks', () => {4  before(function () {5    console.log('before');6  });7  after(function () {8    console.log('after');9  });10  beforeEach(function () {11    console.log('beforeEach');12  });13  afterEach(function () {14    console.log('afterEach');15  });16  it('Test case 1', () => {17    expect(true).to.be.true;18  });19  it('Test case 2', () => {20    expect(true).to.be.true;21  });22});Using AI Code Generation
1const {After, Before} = require('cucumber');2const {setDefaultTimeout} = require('cucumber');3setDefaultTimeout(60 * 1000);4var createDriver = require('./driver.js');5var driver;6Before(function () {7    driver = createDriver();8});9After(function () {10    driver.quit();11});12module.exports = function() {13    this.World = function World() {14        this.driver = driver;15    };16};17var webdriver = require('selenium-webdriver');18var chrome = require('selenium-webdriver/chrome');19var path = require('chromedriver').path;20var service = new chrome.ServiceBuilder(path).build();21chrome.setDefaultService(service);22var driver = new webdriver.Builder()23    .forBrowser('chrome')24    .build();25module.exports = function() {26    return driver;27};Using AI Code Generation
1var assert = require('assert');2var hook = require('mocha').Hook;3var hook = new Hook('beforeEach', function() {4  console.log("Before Each Test");5});6hook.run();7var hook = new Hook('afterEach', function() {8  console.log("After Each Test");9});10hook.run();11var hook = new Hook('before', function() {12  console.log("Before All Test");13});14hook.run();15var hook = new Hook('after', function() {16  console.log("After All Test");17});18hook.run();19var hook = new Hook('afterAll', function() {20  console.log("After All Test");21});22hook.run();23var hook = new Hook('beforeAll', function() {24  console.log("Before All Test");25});26hook.run();27var hook = new Hook('beforeEach', function() {28  console.log("Before Each Test");29});30hook.run();31var hook = new Hook('afterEach', function() {32  console.log("After Each Test");33});34hook.run();35var hook = new Hook('after', function() {36  console.log("After All Test");37});38hook.run();39var hook = new Hook('before', function() {40  console.log("Before All Test");41});42hook.run();43var hook = new Hook('afterAll', function() {44  console.log("After All Test");45});46hook.run();47var hook = new Hook('beforeAll', function() {48  console.log("Before All Test");49});50hook.run();51var hook = new Hook('afterEach', function() {52  console.log("After Each Test");53});54hook.run();55var hook = new Hook('beforeEach', function() {56  console.log("Before Each Test");57});58hook.run();59var hook = new Hook('after', functionUsing AI Code Generation
1var assert = require("assert");2var webdriver = require('selenium-webdriver');3var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();4describe('Test', function() {5    beforeEach(function(done) {6        done();7    });8    afterEach(function(done) {9        driver.quit();10        done();11    });12    it('should have a title', function(done) {13        driver.getTitle().then(function(title) {14            assert.equal(title, 'Google');15            done();16        });17    });18});19{20  "scripts": {21  },22  "devDependencies": {23  }24}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
