Best JavaScript code snippet using best
sandbox_test.py
Source:sandbox_test.py
...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):...
hook.js
Source:hook.js
...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
...23import pyodbc24from airflow.models import Connection25from airflow.providers.odbc.hooks.odbc import OdbcHook26class TestOdbcHook:27 def get_hook(self=None, hook_params=None, conn_params=None):28 hook_params = hook_params or {}29 conn_params = conn_params or {}30 connection = Connection(31 **{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 )51 assert hook.odbc_connection_string == expected52 def test_driver_in_both(self):53 conn_params = dict(extra=json.dumps(dict(Driver='Fake Driver', Fake_Param='Fake Param')))54 hook_params = dict(driver='ParamDriver')55 hook = self.get_hook(hook_params=hook_params, conn_params=conn_params)56 expected = (57 'DRIVER={ParamDriver};'58 'SERVER=host;'59 'DATABASE=schema;'60 'UID=login;'61 'PWD=password;'62 'Fake_Param=Fake Param;'63 )64 assert hook.odbc_connection_string == expected65 def test_dsn_in_extra(self):66 conn_params = dict(extra=json.dumps(dict(DSN='MyDSN', Fake_Param='Fake Param')))67 hook = self.get_hook(conn_params=conn_params)68 expected = 'DSN=MyDSN;SERVER=host;DATABASE=schema;UID=login;PWD=password;Fake_Param=Fake Param;'69 assert hook.odbc_connection_string == expected70 def test_dsn_in_both(self):71 conn_params = dict(extra=json.dumps(dict(DSN='MyDSN', Fake_Param='Fake Param')))72 hook_params = dict(driver='ParamDriver', dsn='ParamDSN')73 hook = self.get_hook(hook_params=hook_params, conn_params=conn_params)74 expected = (75 'DRIVER={ParamDriver};'76 'DSN=ParamDSN;'77 'SERVER=host;'78 'DATABASE=schema;'79 'UID=login;'80 'PWD=password;'81 'Fake_Param=Fake Param;'82 )83 assert hook.odbc_connection_string == expected84 def test_get_uri(self):85 conn_params = dict(extra=json.dumps(dict(DSN='MyDSN', Fake_Param='Fake Param')))86 hook_params = dict(dsn='ParamDSN')87 hook = self.get_hook(hook_params=hook_params, conn_params=conn_params)88 uri_param = quote_plus(89 'DSN=ParamDSN;SERVER=host;DATABASE=schema;UID=login;PWD=password;Fake_Param=Fake Param;'90 )91 expected = 'mssql+pyodbc:///?odbc_connect=' + uri_param92 assert hook.get_uri() == expected93 def test_connect_kwargs_from_hook(self):94 hook = self.get_hook(95 hook_params=dict(96 connect_kwargs={97 'attrs_before': {98 1: 2,99 pyodbc.SQL_TXN_ISOLATION: pyodbc.SQL_TXN_READ_UNCOMMITTED,100 },101 'readonly': True,102 'autocommit': False,103 }104 ),105 )106 assert hook.connect_kwargs == {107 'attrs_before': {1: 2, pyodbc.SQL_TXN_ISOLATION: pyodbc.SQL_TXN_READ_UNCOMMITTED},108 'readonly': True,109 'autocommit': False,110 }111 def test_connect_kwargs_from_conn(self):112 extra = json.dumps(113 dict(114 connect_kwargs={115 'attrs_before': {116 1: 2,117 pyodbc.SQL_TXN_ISOLATION: pyodbc.SQL_TXN_READ_UNCOMMITTED,118 },119 'readonly': True,120 'autocommit': True,121 }122 )123 )124 hook = self.get_hook(conn_params=dict(extra=extra))125 assert hook.connect_kwargs == {126 'attrs_before': {1: 2, pyodbc.SQL_TXN_ISOLATION: pyodbc.SQL_TXN_READ_UNCOMMITTED},127 'readonly': True,128 'autocommit': True,129 }130 def test_connect_kwargs_from_conn_and_hook(self):131 """132 When connect_kwargs in both hook and conn, should be merged properly.133 Hook beats conn.134 """135 conn_extra = json.dumps(dict(connect_kwargs={'attrs_before': {1: 2, 3: 4}, 'readonly': False}))136 hook_params = dict(137 connect_kwargs={'attrs_before': {3: 5, pyodbc.SQL_TXN_ISOLATION: 0}, 'readonly': True}138 )139 hook = self.get_hook(conn_params=dict(extra=conn_extra), hook_params=hook_params)140 assert hook.connect_kwargs == {141 'attrs_before': {1: 2, 3: 5, pyodbc.SQL_TXN_ISOLATION: 0},142 'readonly': True,143 }144 def test_connect_kwargs_bool_from_uri(self):145 """146 Bools will be parsed from uri as strings147 """148 conn_extra = json.dumps(dict(connect_kwargs={'ansi': 'true'}))149 hook = self.get_hook(conn_params=dict(extra=conn_extra))150 assert hook.connect_kwargs == {151 'ansi': True,152 }153 def test_driver(self):154 hook = self.get_hook(hook_params=dict(driver='Blah driver'))155 assert hook.driver == 'Blah driver'156 hook = self.get_hook(hook_params=dict(driver='{Blah driver}'))157 assert hook.driver == 'Blah driver'158 hook = self.get_hook(conn_params=dict(extra='{"driver": "Blah driver"}'))159 assert hook.driver == 'Blah driver'160 hook = self.get_hook(conn_params=dict(extra='{"driver": "{Blah driver}"}'))161 assert hook.driver == 'Blah driver'162 def test_database(self):163 hook = self.get_hook(hook_params=dict(database='abc'))164 assert hook.database == 'abc'165 hook = self.get_hook()166 assert hook.database == 'schema'167 def test_sqlalchemy_scheme_default(self):168 hook = self.get_hook()169 uri = hook.get_uri()170 assert urlparse(uri).scheme == 'mssql+pyodbc'171 def test_sqlalchemy_scheme_param(self):172 hook = self.get_hook(hook_params=dict(sqlalchemy_scheme='my-scheme'))173 uri = hook.get_uri()174 assert urlparse(uri).scheme == 'my-scheme'175 def test_sqlalchemy_scheme_extra(self):176 hook = self.get_hook(conn_params=dict(extra=json.dumps(dict(sqlalchemy_scheme='my-scheme'))))177 uri = hook.get_uri()...
hooks.py
Source:hooks.py
1""" Configurable hooks in the build system. Can be used by various platforms2to customize the build process.3"""4################################################################################5# Hooks for the various parts of the build process6# Internal mapping of hooks per tool7_HOOKS = {}8# Internal mapping of running hooks9_RUNNING_HOOKS = {}10# Available hook types11_HOOK_TYPES = ["binary", "compile", "link", "assemble"]12# Available hook steps13_HOOK_STEPS = ["pre", "replace", "post"]14# Hook the given function. Use this function as a decorator15def hook_tool(function):16 """Decorate a function as a tool that may be hooked"""17 tool = function.__name__18 tool_flag = "_" + tool + "_done"19 def wrapper(t_self, *args, **kwargs):20 """The hooked function itself"""21 # if a hook for this tool is already running, it's most likely22 # coming from a derived class, so don't hook the super class version23 if _RUNNING_HOOKS.get(tool, False):24 return function(t_self, *args, **kwargs)25 _RUNNING_HOOKS[tool] = True26 # If this tool isn't hooked, return original function27 if tool not in _HOOKS:28 res = function(t_self, *args, **kwargs)29 _RUNNING_HOOKS[tool] = False30 return res31 tooldesc = _HOOKS[tool]32 setattr(t_self, tool_flag, False)33 # If there is a replace hook, execute the replacement instead34 if "replace" in tooldesc:35 res = tooldesc["replace"](t_self, *args, **kwargs)36 # If the replacement has set the "done" flag, exit now37 # Otherwise continue as usual38 if getattr(t_self, tool_flag, False):39 _RUNNING_HOOKS[tool] = False40 return res41 # Execute pre-function before main function if specified42 if "pre" in tooldesc:43 tooldesc["pre"](t_self, *args, **kwargs)44 # Execute the main function now45 res = function(t_self, *args, **kwargs)46 # Execute post-function after main function if specified47 if "post" in tooldesc:48 post_res = tooldesc["post"](t_self, *args, **kwargs)49 _RUNNING_HOOKS[tool] = False50 return post_res or res51 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 hooks70 """71 if hook_type not in _HOOK_TYPES or hook_step not in _HOOK_STEPS:72 return False73 if hook_type not in _HOOKS:74 _HOOKS[hook_type] = {}75 _HOOKS[hook_type][hook_step] = function76 return True77 def hook_add_compiler(self, hook_step, function):78 """Add a hook to the compiler79 Positional Arguments:80 hook_step - one of the _HOOK_STEPS81 function - the function to add to the list of hooks82 """83 return self._hook_add("compile", hook_step, function)84 def hook_add_linker(self, hook_step, function):85 """Add a hook to the linker86 Positional Arguments:87 hook_step - one of the _HOOK_STEPS88 function - the function to add to the list of hooks89 """90 return self._hook_add("link", hook_step, function)91 def hook_add_assembler(self, hook_step, function):92 """Add a hook to the assemble93 Positional Arguments:94 hook_step - one of the _HOOK_STEPS95 function - the function to add to the list of hooks96 """97 return self._hook_add("assemble", hook_step, function)98 def hook_add_binary(self, hook_step, function):99 """Add a hook to the elf to binary tool100 Positional Arguments:101 hook_step - one of the _HOOK_STEPS102 function - the function to add to the list of hooks103 """104 return self._hook_add("binary", hook_step, function)105 # Hook command lines106 def _hook_cmdline(self, hook_type, function):107 """Add a hook to a command line function108 Positional arguments:109 hook_type - one of the _HOOK_TYPES110 function - the function to add to the list of hooks111 """112 if hook_type not in _HOOK_TYPES:113 return False114 self._cmdline_hooks[hook_type] = function115 return True116 def hook_cmdline_compiler(self, function):117 """Add a hook to the compiler command line118 Positional arguments:119 function - the function to call120 """121 return self._hook_cmdline("compile", function)122 def hook_cmdline_linker(self, function):123 """Add a hook to the linker command line124 Positional arguments:125 function - the function to call126 """127 return self._hook_cmdline("link", function)128 def hook_cmdline_assembler(self, function):129 """Add a hook to the assembler command line130 Positional arguments:131 function - the function to call132 """133 return self._hook_cmdline("assemble", function)134 def hook_cmdline_binary(self, function):135 """Add a hook to the elf to bin tool command line136 Positional arguments:137 function - the function to call138 """139 return self._hook_cmdline("binary", function)140 # Return the command line after applying the hook141 def _get_cmdline(self, hook_type, cmdline):142 """Get the command line after running all hooks143 Positional arguments:144 hook_type - one of the _HOOK_TYPES145 cmdline - the initial command line146 """147 if hook_type in self._cmdline_hooks:148 cmdline = self._cmdline_hooks[hook_type](149 self.toolchain.__class__.__name__, cmdline)150 return cmdline151 def get_cmdline_compiler(self, cmdline):152 """Get the compiler command line after running all hooks153 Positional arguments:154 cmdline - the initial command line155 """156 return self._get_cmdline("compile", cmdline)157 def get_cmdline_linker(self, cmdline):158 """Get the linker command line after running all hooks159 Positional arguments:160 cmdline - the initial command line161 """162 return self._get_cmdline("link", cmdline)163 def get_cmdline_assembler(self, cmdline):164 """Get the assmebler command line after running all hooks165 Positional arguments:166 cmdline - the initial command line167 """168 return self._get_cmdline("assemble", cmdline)169 def get_cmdline_binary(self, cmdline):170 """Get the binary command line after running all hooks171 Positional arguments:172 cmdline - the initial command line173 """174 return self._get_cmdline("binary", cmdline)...
hooks.js
Source:hooks.js
1'use strict';2var winston = require('winston');3var async = require('async');4module.exports = function (Plugins) {5 Plugins.deprecatedHooks = {6 };7 Plugins.internals = {8 _register: function (data, callback) {9 Plugins.loadedHooks[data.hook] = Plugins.loadedHooks[data.hook] || [];10 Plugins.loadedHooks[data.hook].push(data);11 callback();12 },13 };14 /*15 `data` is an object consisting of (* is required):16 `data.hook`*, the name of the NodeBB hook17 `data.method`*, the method called in that plugin (can be an array of functions)18 `data.priority`, the relative priority of the method when it is eventually called (default: 10)19 */20 Plugins.registerHook = function (id, data, callback) {21 callback = callback || function () {};22 if (!data.hook) {23 winston.warn('[plugins/' + id + '] registerHook called with invalid data.hook', data);24 return callback();25 }26 var method;27 if (Object.keys(Plugins.deprecatedHooks).indexOf(data.hook) !== -1) {28 winston.warn('[plugins/' + id + '] Hook `' + data.hook + '` is deprecated, ' +29 (Plugins.deprecatedHooks[data.hook] ?30 'please use `' + Plugins.deprecatedHooks[data.hook] + '` instead.' :31 'there is no alternative.'32 ));33 }34 if (data.hook && data.method) {35 data.id = id;36 if (!data.priority) {37 data.priority = 10;38 }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);135 if (!timedOut) {136 next.apply(null, arguments);137 }138 });139 } catch (err) {140 winston.error('[plugins] Error executing \'' + hook + '\' in plugin \'' + hookObj.id + '\'');141 winston.error(err);142 clearTimeout(timeoutId);143 next();144 }145 } else {146 next();147 }148 }, callback);149 }150 Plugins.hasListeners = function (hook) {151 return !!(Plugins.loadedHooks[hook] && Plugins.loadedHooks[hook].length > 0);152 };...
Hook.py
Source:Hook.py
...25import 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))41 self.assertEqual(self.hook.url, "https://api.github.com/repos/jacquev6/PyGithub/hooks/257993")42 def testEditWithMinimalParameters(self):43 self.hook.edit("web", {"url": "http://foobar.com/hook"})...
hooks_helper_test.py
Source:hooks_helper_test.py
...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
1var hook = require('hook.io').hook;2var util = require('util');3var Test4 = exports.Test4 = function(options) {4 hook.call(this, options);5};6util.inherits(Test4, hook);7Test4.prototype._start = function(callback) {8 this.emit('hook::ready');9 callback();10};11Test4.prototype._stop = function(callback) {12 callback();13};14Test4.prototype.test = function(data, callback) {15 console.log('test4: ' + data);16 callback(null, 'test4: ' + data);17};18Test4.prototype.test2 = function(data, callback) {19 console.log('test4: ' + data);20 callback(null, 'test4: ' + data);21};22Test4.prototype.test3 = function(data, callback) {23 console.log('test4: ' + data);24 callback(null, 'test4: ' + data);25};26Test4.prototype.test4 = function(data, callback) {27 console.log('test4: ' + data);28 callback(null, 'test4: ' + data);29};30Test4.prototype.test5 = function(data, callback) {31 console.log('test4: ' + data);32 callback(null, 'test4: ' + data);33};34Test4.prototype.test6 = function(data, callback) {35 console.log('test4: ' + data);36 callback(null, 'test4: ' + data);37};38Test4.prototype.test7 = function(data, callback) {39 console.log('test4: ' + data);40 callback(null, 'test4: ' + data);41};42Test4.prototype.test8 = function(data, callback) {43 console.log('test4: ' + data);44 callback(null, 'test4: ' + data);45};46Test4.prototype.test9 = function(data, callback) {47 console.log('test4: ' + data);48 callback(null, 'test4: ' + data);49};50Test4.prototype.test10 = function(data, callback) {51 console.log('test4: ' + data);52 callback(null, 'test4: ' + data);53};54Test4.prototype.test11 = function(data, callback) {55 console.log('test4: ' + data);56 callback(null, 'test4: ' + data);57};58Test4.prototype.test12 = function(data, callback) {59 console.log('test4: ' +
Using AI Code Generation
1var fs = require('fs');2var data = fs.readFileSync('input.txt');3console.log(data.toString());4console.log("Program Ended");5fs.readFile('input.txt', function (err, data) {6if (err) return console.error(err);7console.log(data.toString());8});9console.log("Program Ended");10var events = require('events');11var eventEmitter = new events.EventEmitter();12var listner1 = function listner1() {13console.log('listner1 executed.');14}15var listner2 = function listner2() {16console.log('listner2 executed.');17}18eventEmitter.addListener('connection', listner1);19eventEmitter.on('connection', listner2);20var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter, 'connection');21console.log(eventListeners + " Listner(s) listening to connection event");22eventEmitter.emit('connection');23eventEmitter.removeListener('connection', listner1);24console.log("Listner1 will not listen now.");25eventEmitter.emit('connection');26eventListeners = require('events').EventEmitter.listenerCount(eventEmitter, 'connection');27console.log(eventListeners + " Listner(s) listening to connection event");28console.log("Program Ended.");29var fs = require("fs");30var data = '';31var readerStream = fs.createReadStream('input.txt');32readerStream.setEncoding('UTF8');33readerStream.on('data', function(chunk) {34data += chunk;35});36readerStream.on('end',function(){37console.log(data);38});39readerStream.on('error', function(err){40console.log(err.stack);41});42console.log("Program Ended");43var fs = require("fs");44var data = 'Simply Easy Learning';45var writerStream = fs.createWriteStream('output.txt');46writerStream.write(data,'UTF8');
Using AI Code Generation
1module.exports = function(){2 console.log('Hello World');3}4module.exports = function(){5 console.log('Hello World');6}7module.exports = function(){8 console.log('Hello World');9}10module.exports = function(){11 console.log('Hello World');12}13module.exports = function(){14 console.log('Hello World');15}16module.exports = function(){17 console.log('Hello World');18}19module.exports = function(){20 console.log('Hello World');21}22module.exports = function(){23 console.log('Hello World');24}25module.exports = function(){26 console.log('Hello World');27}28module.exports = function(){29 console.log('Hello World');30}31module.exports = function(){32 console.log('Hello World');33}34module.exports = function(){35 console.log('Hello World');36}37module.exports = function(){38 console.log('Hello World');39}40module.exports = function(){41 console.log('Hello World');42}
Using AI Code Generation
1var hook = require('./hook');2var path = require('path');3hook.hookRequire(path.resolve(__dirname, 'test3.js'), function (exports, name, basedir) {4 console.log('Hooked ' + name + ' from ' + basedir);5 return exports;6});7hook.hookRequire(path.resolve(__dirname, 'test3.js'), function (exports, name, basedir) {8 console.log('Hooked ' + name + ' from ' + basedir);9 return exports;10});11var test3 = require('./test3');12test3();13hook.unhookRequire(path.resolve(__dirname, 'test3.js'));14hook.unhookRequire(path.resolve(__dirname, 'test3.js'));15hook.unhookRequire(path.resolve(__dirname, 'test3.js'));16hook.unhookRequire(path.resolve(__dirname, 'test3.js'));17var test3 = require('./test3');18test3();19hook.hookRequire(path.resolve(__dirname, 'test3.js'), function (exports, name, basedir) {20 console.log('Hooked ' + name + ' from ' + basedir);21 return exports;22});23var test3 = require('./test3');24test3();25hook.unhookRequire(path.resolve(__dirname, 'test3.js'));26hook.unhookRequire(path.resolve(__dirname, 'test3.js'));27hook.unhookRequire(path.resolve(__dirname, 'test3.js'));28hook.unhookRequire(path.resolve(__dirname, 'test3.js'));29var test3 = require('./test3');30test3();31hook.hookRequire(path.resolve(__dirname, 'test3.js
Using AI Code Generation
1const BestBuyApi = require('./bestbuyapi');2const util = require('util');3const bestBuyApi = new BestBuyApi();4bestBuyApi.getCategories(function (error, data) {5 if (error) {6 console.log(error);7 }8 else {9 console.log(util.inspect(data, false, null));10 }11});12const BestBuyApi = require('./bestbuyapi');13const util = require('util');14const bestBuyApi = new BestBuyApi();15bestBuyApi.getProductsByCategory(3944, function (error, data) {16 if (error) {17 console.log(error);18 }19 else {20 console.log(util.inspect(data, false, null));21 }22});23const BestBuyApi = require('./bestbuyapi');24const util = require('util');25const bestBuyApi = new BestBuyApi();26bestBuyApi.getProductById(4800200, function (error, data) {27 if (error) {28 console.log(error);29 }30 else {31 console.log(util.inspect(data, false, null));32 }33});34const BestBuyApi = require('./bestbuyapi');35const util = require('util');36const bestBuyApi = new BestBuyApi();37bestBuyApi.getProductBySku(4800200, function (error, data) {38 if (error) {39 console.log(error);40 }41 else {42 console.log(util.inspect(data, false, null));43 }44});45const BestBuyApi = require('./bestbuyapi');46const util = require('util');47const bestBuyApi = new BestBuyApi();48bestBuyApi.getProductByName('Apple iPhone 5s', function (error, data) {49 if (error) {50 console.log(error);51 }52 else {53 console.log(util.inspect(data, false, null));54 }55});
Using AI Code Generation
1var myObject = (function () {2 var value = 0;3 return {4 increment: function (inc) {5 value += typeof inc === 'number' ? inc : 1;6 },7 getValue: function () {8 return value;9 }10 };11}());12Function.prototype.method = function (name, func) {13 if (!this.prototype[name]) {14 this.prototype[name] = func;15 return this;16 }17};18Function.method('curry', function () {19 args = slice.apply(arguments),20 that = this;21 return function () {22 return that.apply(null, args.concat(slice.apply(arguments)));23 };24});25var try_it = function () {26 try {27 myObject.increment(2);28 myObject.increment();29 } catch (e) {30 document.writeln(e);31 }32};33var try_it = function () {34 try {35 myObject.double();36 } catch (e) {37 document.writeln(e);38 }39};40try_it();41var try_it = function () {42 try {43 myObject.increment(2, 3);44 } catch (e) {45 document.writeln(e);46 }47};48try_it();49var try_it = function () {50 try {51 myObject.increment();52 } catch (e) {53 document.writeln(e);54 }55};56try_it();57var try_it = function () {58 try {59 myObject.increment('five');60 } catch (e) {61 document.writeln(e);62 }
Using AI Code Generation
1var hook = new BestPractice.Hook();2hook.addHook('test4', function () {3 console.log('test4');4});5hook.callHook('test4');6hook.removeHook('test4');7hook.callHook('test4');8var hook = new BestPractice.Hook();9hook.addHook('test5', function () {10 console.log('test5');11});12hook.callHook('test5');13hook.removeHook('test5');14hook.callHook('test5');15var hook = new BestPractice.Hook();16hook.addHook('test6', function () {17 console.log('test6');18});19hook.callHook('test6');20hook.removeHook('test6');21hook.callHook('test6');22var hook = new BestPractice.Hook();23hook.addHook('test7', function () {24 console.log('test7');25});26hook.callHook('test7');27hook.removeHook('test7');28hook.callHook('test7');29var hook = new BestPractice.Hook();30hook.addHook('test8', function () {
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!!