How to use hook method in testing-library-react-hooks

Best JavaScript code snippet using testing-library-react-hooks

sandbox_test.py

Source:sandbox_test.py Github

copy

Full Screen

...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):...

Full Screen

Full Screen

hook.js

Source:hook.js Github

copy

Full Screen

...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}...

Full Screen

Full Screen

core.plugin.tests.js

Source:core.plugin.tests.js Github

copy

Full Screen

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 });...

Full Screen

Full Screen

test_odbc.py

Source:test_odbc.py Github

copy

Full Screen

...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()...

Full Screen

Full Screen

hooks.py

Source:hooks.py Github

copy

Full Screen

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)...

Full Screen

Full Screen

hooks.js

Source:hooks.js Github

copy

Full Screen

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 };...

Full Screen

Full Screen

Hook.py

Source:Hook.py Github

copy

Full Screen

...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"})...

Full Screen

Full Screen

hooks_helper_test.py

Source:hooks_helper_test.py Github

copy

Full Screen

...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__':...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import { useCounter } from './useCounter';3test('useCounter', () => {4 const { result } = renderHook(() => useCounter());5 expect(result.current.count).toBe(0);6 act(() => {7 result.current.increment();8 });9 expect(result.current.count).toBe(1);10});11import { useState } from 'react';12export const useCounter = () => {13 const [count, setCount] = useState(0);14 const increment = () => setCount(count + 1);15 return { count, increment };16};

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks'2import { useCounter } from './useCounter'3test('useCounter hook', () => {4 const { result } = renderHook(() => useCounter())5 expect(result.current.count).toBe(0)6 act(() => {7 result.current.increment()8 })9 expect(result.current.count).toBe(1)10 act(() => {11 result.current.decrement()12 })13 expect(result.current.count).toBe(0)14 act(() => {15 result.current.reset()16 })17 expect(result.current.count).toBe(0)18})19import { useState } from 'react'20export const useCounter = () => {21 const [count, setCount] = useState(0)22 const increment = () => setCount(count + 1)23 const decrement = () => setCount(count - 1)24 const reset = () => setCount(0)25 return {26 }27}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import { useFetch } from './useFetch';3test('should return data', async () => {4 const { result, waitForNextUpdate } = renderHook(() =>5 );6 await waitForNextUpdate();7 expect(result.current.data.title).toBe('sunt aut facere repellat provident occaecati excepturi optio reprehenderit');8});9import { useState, useEffect } from 'react';10export function useFetch(url) {11 const [data, setData] = useState(null);12 const [loading, setLoading] = useState(true);13 useEffect(() => {14 setLoading(true);15 fetch(url)16 .then((response) => response.json())17 .then((data) => {18 setData(data);19 setLoading(false);20 });21 }, [url]);22 return { data, loading };23}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { act } from 'react-dom/test-utils';2import { renderHook } from '@testing-library/react-hooks';3import { useCounter } from './useCounter';4describe('useCounter', () => {5 it('should increment counter', () => {6 const { result } = renderHook(() => useCounter());7 act(() => {8 result.current.increment();9 });10 expect(result.current.count).toBe(1);11 });12});13import { useState } from 'react';14export const useCounter = () => {15 const [count, setCount] = useState(0);16 const increment = () => setCount(count + 1);17 return { count, increment };18};19import { act } from 'react-dom/test-utils';20import { renderHook } from '@testing-library/react-hooks';21import { useCounter } from './useCounter';22describe('useCounter', () => {23 it('should increment counter', () => {24 const { result } = renderHook(() => useCounter({ initialCount: 5 }));25 act(() => {26 result.current.increment();27 });28 expect(result.current.count).toBe(6);29 });30});31import { useState } from 'react';32export const useCounter = ({ initialCount = 0 } = {}) => {33 const [count, setCount] = useState(initialCount);34 const increment = () => setCount(count + 1);35 return { count, increment };36};

Full Screen

Using AI Code Generation

copy

Full Screen

1import {renderHook} from '@testing-library/react-hooks';2import {useFetch} from './useFetch';3describe('useFetch', () => {4 it('should return data', async () => {5 const {result, waitForNextUpdate} = renderHook(() =>6 );7 expect(result.current.data).toBe(null);8 expect(result.current.loading).toBe(true);9 await waitForNextUpdate();10 expect(result.current.data).not.toBe(null);11 expect(result.current.loading).toBe(false);12 });13});14import {useState, useEffect} from 'react';15import axios from 'axios';16export const useFetch = url => {17 const [data, setData] = useState(null);18 const [loading, setLoading] = useState(true);19 useEffect(() => {20 const fetchData = async () => {21 const result = await axios(url);22 setData(result.data);23 setLoading(false);24 };25 fetchData();26 }, [url]);27 return {data, loading};28};29import {renderHook} from '@testing-library/react-hooks';30import {useFetch} from './useFetch';31describe('useFetch', () => {32 it('should return data', async () => {33 const {result, waitForNextUpdate} = renderHook(() =>34 );35 expect(result.current.data).toBe(null);36 expect(result.current.loading).toBe(true);37 await waitForNextUpdate();38 expect(result.current.data).not.toBe(null);39 expect(result.current.loading).toBe(false);40 });41});42import {useState, useEffect} from 'react';43import axios from 'axios';44export const useFetch = url => {45 const [data, setData] = useState(null);46 const [loading, setLoading] = useState(true);47 useEffect(() => {48 const fetchData = async () => {49 const result = await axios(url);50 setData(result.data);51 setLoading(false);52 };53 fetchData();54 }, [url]);55 return {data, loading};56};57import {renderHook} from '@testing-library/react-hooks';58import {useFetch} from './useFetch';59describe('useFetch', () => {60 it('should return data', async () => {61 const {result, waitFor

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import useCounter from 'useCounter';3describe('useCounter', () => {4 it('should return default value', () => {5 const { result } = renderHook(() => useCounter());6 expect(result.current.count).toBe(0);7 });8 it('should return incremented value', () => {9 const { result } = renderHook(() => useCounter());10 result.current.increment();11 expect(result.current.count).toBe(1);12 });13 it('should return decremented value', () => {14 const { result } = renderHook(() => useCounter());15 result.current.decrement();16 expect(result.current.count).toBe(-1);17 });18});19import { useState } from 'react';20export default function useCounter(initialValue = 0) {21 const [count, setCount] = useState(initialValue);22 const increment = () => {23 setCount((prevCount) => prevCount + 1);24 };25 const decrement = () => {26 setCount((prevCount) => prevCount - 1);27 };28 return { count, increment, decrement };29}30import { renderHook, act } from '@testing-library/react-hooks';31import useCounter from './useCounter';32describe('useCounter', () => {33 it('should return default value', () => {34 const { result } = renderHook(() => useCounter());35 expect(result.current.count).toBe(0);36 });37 it('should return incremented value', () => {38 const { result } = renderHook(() => useCounter());39 act(() => {40 result.current.increment();41 });42 expect(result.current.count).toBe(1);43 });44 it('should return decremented value', () => {45 const { result } = renderHook(() => useCounter());46 act(() => {47 result.current.decrement();48 });49 expect(result.current.count).toBe(-1);50 });51});52import { useState, useCallback } from 'react';53export default function useCounter(initialValue = 0) {54 const [count, setCount] = useState(initialValue);55 const increment = useCallback(() => {56 setCount((prevCount) => prevCount + 1);57 }, []);58 const decrement = useCallback(() => {59 setCount((prevCount

Full Screen

Using AI Code Generation

copy

Full Screen

1import { renderHook } from '@testing-library/react-hooks';2import { useFetch } from './useFetch';3describe('useFetch', () => {4 it('should fetch data and return status', async () => {5 const { result, waitForNextUpdate } = renderHook(() =>6 );7 expect(result.current.status).toBe('loading');8 await waitForNextUpdate();9 expect(result.current.status).toBe('success');10 expect(result.current.data).toEqual({11 });12 });13});14import { useState, useEffect } from 'react';15export function useFetch(url) {16 const [data, setData] = useState(null);17 const [status, setStatus] = useState('loading');18 useEffect(() => {19 fetch(url)20 .then(res => res.json())21 .then(data => {22 setData(data);23 setStatus('success');24 })25 .catch(error => {26 setStatus('error');27 console.log(error);28 });29 }, [url]);30 return { data, status };31}32import React from 'react';33import { useFetch } from './useFetch';34function App() {35 const { data, status } = useFetch(36 );37 return (38 {status === 'loading' && <div>Loading data...</div>}39 {status === 'error' && <div>Error fetching data</div>}40 {status === 'success' && <pre>{JSON.stringify(data, null, 2)}</pre>}41 );42}43export default App;

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run testing-library-react-hooks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful