How to use Runner method in wpt

Best JavaScript code snippet using wpt

perftestsrunner_unittest.py

Source:perftestsrunner_unittest.py Github

copy

Full Screen

...103 def create_runner(self, args=[], driver_class=TestDriver):104 options, parsed_args = PerfTestsRunner._parse_args(args)105 test_port = TestPort(host=MockHost(), options=options)106 test_port.create_driver = lambda worker_number=None, no_timeout=False: driver_class()107 runner = PerfTestsRunner(args=args, port=test_port)108 runner._host.filesystem.maybe_make_directory(runner._base_path, 'inspector')109 runner._host.filesystem.maybe_make_directory(runner._base_path, 'Bindings')110 runner._host.filesystem.maybe_make_directory(runner._base_path, 'Parser')111 return runner112 def run_test(self, test_name):113 runner = self.create_runner()114 driver = MainTest.TestDriver()115 return runner._run_single_test(ChromiumStylePerfTest(test_name, runner._host.filesystem.join('some-dir', test_name)), driver)116 def test_run_passing_test(self):117 self.assertTrue(self.run_test('pass.html'))118 def test_run_silent_test(self):119 self.assertFalse(self.run_test('silent.html'))120 def test_run_failed_test(self):121 self.assertFalse(self.run_test('failed.html'))...

Full Screen

Full Screen

test_runner.py

Source:test_runner.py Github

copy

Full Screen

...48 def test_runInOrder(self):49 """50 L{Runner.run} calls the expected methods in order.51 """52 runner = DummyRunner({})53 runner.run()54 self.assertEqual(55 runner.calledMethods,56 [57 "killIfRequested",58 "startLogging",59 "startReactor",60 "reactorExited",61 ]62 )63 def test_runUsesPIDFile(self):64 """65 L{Runner.run} uses the provided PID file.66 """67 pidFile = DummyPIDFile()68 runner = DummyRunner(pidFile=pidFile)69 self.assertFalse(pidFile.entered)70 self.assertFalse(pidFile.exited)71 runner.run()72 self.assertTrue(pidFile.entered)73 self.assertTrue(pidFile.exited)74 def test_runAlreadyRunning(self):75 """76 L{Runner.run} exits with L{ExitStatus.EX_USAGE} and the expected77 message if a process is already running that corresponds to the given78 PID file.79 """80 pidFile = PIDFile(DummyFilePath(self.pidFileContent))81 pidFile.isRunning = lambda: True82 runner = DummyRunner(pidFile=pidFile)83 runner.run()84 self.assertEqual(self.exit.status, ExitStatus.EX_CONFIG)85 self.assertEqual(self.exit.message, "Already running.")86 def test_killNotRequested(self):87 """88 L{Runner.killIfRequested} when C{kill} is false doesn't exit and89 doesn't indiscriminately murder anyone.90 """91 runner = Runner({})92 runner.killIfRequested()93 self.assertEqual(self.kill.calls, [])94 self.assertFalse(self.exit.exited)95 def test_killRequestedWithoutPIDFile(self):96 """97 L{Runner.killIfRequested} when C{kill} is true but C{pidFile} is98 L{nonePIDFile} exits with L{ExitStatus.EX_USAGE} and the expected99 message; and also doesn't indiscriminately murder anyone.100 """101 runner = Runner(kill=True)102 runner.killIfRequested()103 self.assertEqual(self.kill.calls, [])104 self.assertEqual(self.exit.status, ExitStatus.EX_USAGE)105 self.assertEqual(self.exit.message, "No PID file specified.")106 def test_killRequestedWithPIDFile(self):107 """108 L{Runner.killIfRequested} when C{kill} is true and given a C{pidFile}109 performs a targeted killing of the appropriate process.110 """111 pidFile = PIDFile(DummyFilePath(self.pidFileContent))112 runner = Runner(kill=True, pidFile=pidFile)113 runner.killIfRequested()114 self.assertEqual(self.kill.calls, [(self.pid, SIGTERM)])115 self.assertEqual(self.exit.status, ExitStatus.EX_OK)116 self.assertIdentical(self.exit.message, None)117 def test_killRequestedWithPIDFileCantRead(self):118 """119 L{Runner.killIfRequested} when C{kill} is true and given a C{pidFile}120 that it can't read exits with L{ExitStatus.EX_IOERR}.121 """122 pidFile = PIDFile(DummyFilePath(None))123 def read():124 raise OSError(errno.EACCES, "Permission denied")125 pidFile.read = read126 runner = Runner(kill=True, pidFile=pidFile)127 runner.killIfRequested()128 self.assertEqual(self.exit.status, ExitStatus.EX_IOERR)129 self.assertEqual(self.exit.message, "Unable to read PID file.")130 def test_killRequestedWithPIDFileEmpty(self):131 """132 L{Runner.killIfRequested} when C{kill} is true and given a C{pidFile}133 containing no value exits with L{ExitStatus.EX_DATAERR}.134 """135 pidFile = PIDFile(DummyFilePath(b""))136 runner = Runner(kill=True, pidFile=pidFile)137 runner.killIfRequested()138 self.assertEqual(self.exit.status, ExitStatus.EX_DATAERR)139 self.assertEqual(self.exit.message, "Invalid PID file.")140 def test_killRequestedWithPIDFileNotAnInt(self):141 """142 L{Runner.killIfRequested} when C{kill} is true and given a C{pidFile}143 containing a non-integer value exits with L{ExitStatus.EX_DATAERR}.144 """145 pidFile = PIDFile(DummyFilePath(b"** totally not a number, dude **"))146 runner = Runner(kill=True, pidFile=pidFile)147 runner.killIfRequested()148 self.assertEqual(self.exit.status, ExitStatus.EX_DATAERR)149 self.assertEqual(self.exit.message, "Invalid PID file.")150 def test_startLogging(self):151 """152 L{Runner.startLogging} sets up a filtering observer with a log level153 predicate set to the given log level that contains a file observer of154 the given type which writes to the given file.155 """156 logFile = BytesIO()157 # Patch the log beginner so that we don't try to start the already158 # running (started by trial) logging system.159 class LogBeginner(object):160 def beginLoggingTo(self, observers):161 LogBeginner.observers = observers162 self.patch(_runner, "globalLogBeginner", LogBeginner())163 # Patch FilteringLogObserver so we can capture its arguments164 class MockFilteringLogObserver(FilteringLogObserver):165 def __init__(166 self, observer, predicates,167 negativeObserver=lambda event: None168 ):169 MockFilteringLogObserver.observer = observer170 MockFilteringLogObserver.predicates = predicates171 FilteringLogObserver.__init__(172 self, observer, predicates, negativeObserver173 )174 self.patch(_runner, "FilteringLogObserver", MockFilteringLogObserver)175 # Patch FileLogObserver so we can capture its arguments176 class MockFileLogObserver(FileLogObserver):177 def __init__(self, outFile):178 MockFileLogObserver.outFile = outFile179 FileLogObserver.__init__(self, outFile, str)180 # Start logging181 runner = Runner(182 defaultLogLevel=LogLevel.critical,183 logFile=logFile,184 fileLogObserverFactory=MockFileLogObserver,185 )186 runner.startLogging()187 # Check for a filtering observer188 self.assertEqual(len(LogBeginner.observers), 1)189 self.assertIsInstance(LogBeginner.observers[0], FilteringLogObserver)190 # Check log level predicate with the correct default log level191 self.assertEqual(len(MockFilteringLogObserver.predicates), 1)192 self.assertIsInstance(193 MockFilteringLogObserver.predicates[0],194 LogLevelFilterPredicate195 )196 self.assertIdentical(197 MockFilteringLogObserver.predicates[0].defaultLogLevel,198 LogLevel.critical199 )200 # Check for a file observer attached to the filtering observer201 self.assertIsInstance(202 MockFilteringLogObserver.observer, MockFileLogObserver203 )204 # Check for the file we gave it205 self.assertIdentical(206 MockFilteringLogObserver.observer.outFile, logFile207 )208 def test_startReactorWithoutReactor(self):209 """210 L{Runner.startReactor} without the C{reactor} argument runs the default211 reactor.212 """213 reactor = MockReactor(self)214 self.patch(_runner, "defaultReactor", reactor)215 runner = Runner()216 runner.startReactor()217 self.assertTrue(reactor.hasInstalled)218 self.assertTrue(reactor.hasRun)219 def test_startReactorWithReactor(self):220 """221 L{Runner.startReactor} with the C{reactor} argument runs the given222 reactor.223 """224 reactor = MockReactor(self)225 runner = Runner(reactor=reactor)226 runner.startReactor()227 self.assertTrue(reactor.hasRun)228 def test_startReactorWhenRunning(self):229 """230 L{Runner.startReactor} ensures that C{whenRunning} is called with231 C{whenRunningArguments} when the reactor is running.232 """233 self._testHook("whenRunning", "startReactor")234 def test_whenRunningWithArguments(self):235 """236 L{Runner.whenRunning} calls C{whenRunning} with237 C{whenRunningArguments}.238 """239 self._testHook("whenRunning")240 def test_reactorExitedWithArguments(self):241 """242 L{Runner.whenRunning} calls C{reactorExited} with243 C{reactorExitedArguments}.244 """245 self._testHook("reactorExited")246 def _testHook(self, methodName, callerName=None):247 """248 Verify that the named hook is run with the expected arguments as249 specified by the arguments used to create the L{Runner}, when the250 specified caller is invoked.251 @param methodName: The name of the hook to verify.252 @type methodName: L{str}253 @param callerName: The name of the method that is expected to cause the254 hook to be called.255 If C{None}, use the L{Runner} method with the same name as the256 hook.257 @type callerName: L{str}258 """259 if callerName is None:260 callerName = methodName261 arguments = dict(a=object(), b=object(), c=object())262 argumentsSeen = []263 def hook(**arguments):264 argumentsSeen.append(arguments)265 runnerArguments = {266 methodName: hook,267 "{}Arguments".format(methodName): arguments.copy(),268 }269 runner = Runner(reactor=MockReactor(self), **runnerArguments)270 hookCaller = getattr(runner, callerName)271 hookCaller()272 self.assertEqual(len(argumentsSeen), 1)273 self.assertEqual(argumentsSeen[0], arguments)274class DummyRunner(Runner):275 """276 Stub for L{Runner}.277 Keep track of calls to some methods without actually doing anything.278 """279 def __init__(self, *args, **kwargs):280 Runner.__init__(self, *args, **kwargs)281 self.calledMethods = []282 def killIfRequested(self):283 self.calledMethods.append("killIfRequested")284 def startLogging(self):285 self.calledMethods.append("startLogging")286 def startReactor(self):287 self.calledMethods.append("startReactor")288 def reactorExited(self):...

Full Screen

Full Screen

top_7_stress.py

Source:top_7_stress.py Github

copy

Full Screen

1# Copyright 2014 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4from telemetry.page import page as page_module5from telemetry.page import shared_page_state6from telemetry import story7def _GetCurrentLocation(action_runner):8 return action_runner.EvaluateJavaScript('document.location.href')9def _WaitForLocationChange(action_runner, old_href):10 action_runner.WaitForJavaScriptCondition(11 'document.location.href != "%s"' % old_href)12class Top7StressPage(page_module.Page):13 def __init__(self, url, page_set, name=''):14 super(Top7StressPage, self).__init__(15 url=url, page_set=page_set, name=name,16 shared_page_state_class=shared_page_state.SharedDesktopPageState,17 credentials_path = 'data/credentials.json')18 self.archive_data_file = 'data/top_7_stress.json'19 def RunPageInteractions(self, action_runner):20 raise NotImplementedError()21class GoogleWebSearchPage(Top7StressPage):22 """ Why: top google property; a google tab is often open """23 def __init__(self, page_set):24 super(GoogleWebSearchPage, self).__init__(25 url='https://www.google.com/#hl=en&q=barack+obama',26 page_set=page_set)27 def RunNavigateSteps(self, action_runner):28 super(GoogleWebSearchPage, self).RunNavigateSteps(action_runner)29 action_runner.WaitForElement(text='Next')30 def RunPageInteractions(self, action_runner):31 with action_runner.CreateGestureInteraction('ScrollAction'):32 action_runner.ScrollPage()33 old_href = _GetCurrentLocation(action_runner)34 action_runner.ClickElement(text='Next')35 _WaitForLocationChange(action_runner, old_href)36 action_runner.WaitForElement(text='Next')37 with action_runner.CreateGestureInteraction('ScrollAction'):38 action_runner.ScrollPage()39 old_href = _GetCurrentLocation(action_runner)40 action_runner.ClickElement(text='Next')41 _WaitForLocationChange(action_runner, old_href)42 action_runner.WaitForElement(text='Next')43 with action_runner.CreateGestureInteraction('ScrollAction'):44 action_runner.ScrollPage()45 old_href = _GetCurrentLocation(action_runner)46 action_runner.ClickElement(text='Next')47 _WaitForLocationChange(action_runner, old_href)48 action_runner.WaitForElement(text='Previous')49 with action_runner.CreateGestureInteraction('ScrollAction'):50 action_runner.ScrollPage()51 old_href = _GetCurrentLocation(action_runner)52 action_runner.ClickElement(text='Previous')53 _WaitForLocationChange(action_runner, old_href)54 action_runner.WaitForElement(text='Previous')55 with action_runner.CreateGestureInteraction('ScrollAction'):56 action_runner.ScrollPage()57 old_href = _GetCurrentLocation(action_runner)58 action_runner.ClickElement(text='Previous')59 _WaitForLocationChange(action_runner, old_href)60 action_runner.WaitForElement(text='Previous')61 with action_runner.CreateGestureInteraction('ScrollAction'):62 action_runner.ScrollPage()63 old_href = _GetCurrentLocation(action_runner)64 action_runner.ClickElement(text='Previous')65 _WaitForLocationChange(action_runner, old_href)66 action_runner.WaitForElement(text='Images')67 with action_runner.CreateGestureInteraction('ScrollAction'):68 action_runner.ScrollPage()69 old_href = _GetCurrentLocation(action_runner)70 action_runner.ClickElement(text='Images')71 _WaitForLocationChange(action_runner, old_href)72 action_runner.WaitForElement(text='Images')73class GmailPage(Top7StressPage):74 """ Why: productivity, top google properties """75 def __init__(self, page_set):76 super(GmailPage, self).__init__(77 url='https://mail.google.com/mail/',78 page_set=page_set)79 self.credentials = 'google'80 def RunNavigateSteps(self, action_runner):81 super(GmailPage, self).RunNavigateSteps(action_runner)82 action_runner.WaitForJavaScriptCondition(83 'window.gmonkey !== undefined &&'84 'document.getElementById("gb") !== null')85 def RunPageInteractions(self, action_runner):86 old_href = _GetCurrentLocation(action_runner)87 action_runner.ClickElement(88 'a[href="https://mail.google.com/mail/u/0/?shva=1#starred"]')89 _WaitForLocationChange(action_runner, old_href)90 old_href = _GetCurrentLocation(action_runner)91 action_runner.ClickElement(92 'a[href="https://mail.google.com/mail/u/0/?shva=1#inbox"]')93 _WaitForLocationChange(action_runner, old_href)94class GoogleCalendarPage(Top7StressPage):95 """ Why: productivity, top google properties """96 def __init__(self, page_set):97 super(GoogleCalendarPage, self).__init__(98 url='https://www.google.com/calendar/',99 page_set=page_set)100 self.credentials = 'google'101 def RunNavigateSteps(self, action_runner):102 super(GoogleCalendarPage, self).RunNavigateSteps(action_runner)103 action_runner.Wait(2)104 action_runner.WaitForElement('div[class~="navForward"]')105 action_runner.ExecuteJavaScript('''106 (function() {107 var elem = document.createElement('meta');108 elem.name='viewport';109 elem.content='initial-scale=1';110 document.body.appendChild(elem);111 })();''')112 action_runner.Wait(1)113 def RunPageInteractions(self, action_runner):114 action_runner.ClickElement('div[class~="navForward"]')115 action_runner.Wait(2)116 action_runner.WaitForElement('div[class~="navForward"]')117 action_runner.ClickElement('div[class~="navForward"]')118 action_runner.Wait(2)119 action_runner.WaitForElement('div[class~="navForward"]')120 action_runner.ClickElement('div[class~="navForward"]')121 action_runner.Wait(2)122 action_runner.WaitForElement('div[class~="navForward"]')123 action_runner.ClickElement('div[class~="navForward"]')124 action_runner.Wait(2)125 action_runner.WaitForElement('div[class~="navBack"]')126 action_runner.ClickElement('div[class~="navBack"]')127 action_runner.Wait(2)128 action_runner.WaitForElement('div[class~="navBack"]')129 action_runner.ClickElement('div[class~="navBack"]')130 action_runner.Wait(2)131 action_runner.WaitForElement('div[class~="navBack"]')132 action_runner.ClickElement('div[class~="navBack"]')133 action_runner.Wait(2)134 action_runner.WaitForElement('div[class~="navBack"]')135 action_runner.ClickElement('div[class~="navBack"]')136 action_runner.Wait(2)137 action_runner.WaitForElement('div[class~="navBack"]')138class GooglePlusPage(Top7StressPage):139 """ Why: social; top google property; Public profile; infinite scrolls """140 def __init__(self, page_set):141 super(GooglePlusPage, self).__init__(142 url='https://plus.google.com/110031535020051778989/posts',143 page_set=page_set)144 self.credentials = 'google'145 def RunNavigateSteps(self, action_runner):146 super(GooglePlusPage, self).RunNavigateSteps(action_runner)147 action_runner.WaitForElement(text='Home')148 def RunPageInteractions(self, action_runner):149 action_runner.ClickElement(text='Home')150 action_runner.Wait(2)151 action_runner.WaitForElement(text='Profile')152 action_runner.ClickElement(text='Profile')153 action_runner.Wait(2)154 action_runner.WaitForElement(text='Explore')155 action_runner.ClickElement(text='Explore')156 action_runner.Wait(2)157 action_runner.WaitForElement(text='Events')158 action_runner.ClickElement(text='Events')159 action_runner.Wait(2)160 action_runner.WaitForElement(text='Communities')161 action_runner.ClickElement(text='Communities')162 action_runner.Wait(2)163 action_runner.WaitForElement(text='Home')164class BlogspotPage(Top7StressPage):165 """ Why: #11 (Alexa global), google property; some blogger layouts have166 infinite scroll but more interesting """167 def __init__(self, page_set):168 super(BlogspotPage, self).__init__(169 url='http://googlewebmastercentral.blogspot.com/',170 page_set=page_set,171 name='Blogger')172 def RunNavigateSteps(self, action_runner):173 super(BlogspotPage, self).RunNavigateSteps(action_runner)174 action_runner.WaitForElement(text='accessibility')175 def RunPageInteractions(self, action_runner):176 action_runner.ClickElement(text='accessibility')177 action_runner.WaitForNavigate()178 with action_runner.CreateGestureInteraction('ScrollAction'):179 action_runner.ScrollPage()180 # Insert 300ms wait to simulate user finger movement,181 # and ensure scheduling of idle tasks.182 action_runner.Wait(0.3)183 action_runner.ClickElement(text='advanced')184 action_runner.WaitForNavigate()185 with action_runner.CreateGestureInteraction('ScrollAction'):186 action_runner.ScrollPage()187 action_runner.Wait(0.3)188 action_runner.ClickElement(text='beginner')189 action_runner.WaitForNavigate()190 with action_runner.CreateGestureInteraction('ScrollAction'):191 action_runner.ScrollPage()192 action_runner.Wait(0.3)193 action_runner.ClickElement(text='Home')194 action_runner.WaitForNavigate()195class WordpressPage(Top7StressPage):196 """ Why: #18 (Alexa global), Picked an interesting post """197 def __init__(self, page_set):198 super(WordpressPage, self).__init__(199 # pylint: disable=line-too-long200 url='http://en.blog.wordpress.com/2012/09/04/freshly-pressed-editors-picks-for-august-2012/',201 page_set=page_set,202 name='Wordpress')203 def RunNavigateSteps(self, action_runner):204 super(WordpressPage, self).RunNavigateSteps(action_runner)205 action_runner.WaitForElement(206 # pylint: disable=line-too-long207 'a[href="http://en.blog.wordpress.com/2012/08/30/new-themes-able-and-sight/"]')208 def RunPageInteractions(self, action_runner):209 with action_runner.CreateGestureInteraction('ScrollAction'):210 action_runner.ScrollPage()211 # Insert 300ms wait to simulate user finger movement,212 # and ensure scheduling of idle tasks.213 action_runner.Wait(0.3)214 action_runner.ClickElement(215 # pylint: disable=line-too-long216 'a[href="http://en.blog.wordpress.com/2012/08/30/new-themes-able-and-sight/"]')217 action_runner.WaitForNavigate()218 with action_runner.CreateGestureInteraction('ScrollAction'):219 action_runner.ScrollPage()220 action_runner.Wait(0.3)221 action_runner.ClickElement(text='Features')222 action_runner.WaitForNavigate()223 with action_runner.CreateGestureInteraction('ScrollAction'):224 action_runner.ScrollPage()225 action_runner.Wait(0.3)226 action_runner.ClickElement(text='News')227 action_runner.WaitForNavigate()228 with action_runner.CreateGestureInteraction('ScrollAction'):229 action_runner.ScrollPage()230class FacebookPage(Top7StressPage):231 """ Why: top social,Public profile """232 def __init__(self, page_set):233 super(FacebookPage, self).__init__(234 url='https://www.facebook.com/barackobama',235 page_set=page_set,236 name='Facebook')237 self.credentials = 'facebook2'238 def RunNavigateSteps(self, action_runner):239 super(FacebookPage, self).RunNavigateSteps(action_runner)240 action_runner.WaitForElement(text='About')241 def RunPageInteractions(self, action_runner):242 # Scroll and wait for the next page to be loaded.243 with action_runner.CreateGestureInteraction('ScrollAction'):244 action_runner.ScrollPage()245 action_runner.WaitForJavaScriptCondition(246 'document.documentElement.scrollHeight - window.innerHeight - '247 'window.pageYOffset > 0')248 # Scroll and wait again.249 with action_runner.CreateGestureInteraction('ScrollAction'):250 action_runner.ScrollPage()251 action_runner.WaitForJavaScriptCondition(252 'document.documentElement.scrollHeight - window.innerHeight - '253 'window.pageYOffset > 0')254class Top7StressPageSet(story.StorySet):255 """ Pages hand-picked for stress testing. """256 def __init__(self):257 super(Top7StressPageSet, self).__init__(258 archive_data_file='data/top_7_stress.json',259 cloud_storage_bucket=story.PARTNER_BUCKET)260 self.AddStory(GoogleWebSearchPage(self))261 self.AddStory(GmailPage(self))262 self.AddStory(GoogleCalendarPage(self))263 self.AddStory(GooglePlusPage(self))264 self.AddStory(BlogspotPage(self))265 self.AddStory(WordpressPage(self))...

Full Screen

Full Screen

test_eval_hook.py

Source:test_eval_hook.py Github

copy

Full Screen

...91 data_loader = DataLoader(test_dataset, batch_size=1)92 eval_hook = EvalHookCls(data_loader, save_best=None)93 with tempfile.TemporaryDirectory() as tmpdir:94 logger = get_logger('test_eval')95 runner = EpochBasedRunner(96 model=model,97 batch_processor=None,98 optimizer=optimizer,99 work_dir=tmpdir,100 logger=logger)101 runner.register_hook(eval_hook)102 runner.run([loader], [('train', 1)], 1)103 assert runner.meta is None or 'best_score' not in runner.meta[104 'hook_msgs']105 assert runner.meta is None or 'best_ckpt' not in runner.meta[106 'hook_msgs']107 # when `save_best` is set to 'auto', first metric will be used.108 loader = DataLoader(EvalDataset(), batch_size=1)109 model = ExampleModel()110 data_loader = DataLoader(EvalDataset(), batch_size=1)111 eval_hook = EvalHookCls(data_loader, interval=1, save_best='auto')112 with tempfile.TemporaryDirectory() as tmpdir:113 logger = get_logger('test_eval')114 runner = EpochBasedRunner(115 model=model,116 batch_processor=None,117 optimizer=optimizer,118 work_dir=tmpdir,119 logger=logger)120 runner.register_checkpoint_hook(dict(interval=1))121 runner.register_hook(eval_hook)122 runner.run([loader], [('train', 1)], 8)123 real_path = osp.join(tmpdir, 'best_mAP_epoch_4.pth')124 assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)125 assert runner.meta['hook_msgs']['best_score'] == 0.7126 loader = DataLoader(EvalDataset(), batch_size=1)127 model = ExampleModel()128 data_loader = DataLoader(EvalDataset(), batch_size=1)129 eval_hook = EvalHookCls(data_loader, interval=1, save_best='mAP')130 with tempfile.TemporaryDirectory() as tmpdir:131 logger = get_logger('test_eval')132 runner = EpochBasedRunner(133 model=model,134 batch_processor=None,135 optimizer=optimizer,136 work_dir=tmpdir,137 logger=logger)138 runner.register_checkpoint_hook(dict(interval=1))139 runner.register_hook(eval_hook)140 runner.run([loader], [('train', 1)], 8)141 real_path = osp.join(tmpdir, 'best_mAP_epoch_4.pth')142 assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)143 assert runner.meta['hook_msgs']['best_score'] == 0.7144 data_loader = DataLoader(EvalDataset(), batch_size=1)145 eval_hook = EvalHookCls(146 data_loader, interval=1, save_best='score', rule='greater')147 with tempfile.TemporaryDirectory() as tmpdir:148 logger = get_logger('test_eval')149 runner = EpochBasedRunner(150 model=model,151 batch_processor=None,152 optimizer=optimizer,153 work_dir=tmpdir,154 logger=logger)155 runner.register_checkpoint_hook(dict(interval=1))156 runner.register_hook(eval_hook)157 runner.run([loader], [('train', 1)], 8)158 real_path = osp.join(tmpdir, 'best_score_epoch_4.pth')159 assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)160 assert runner.meta['hook_msgs']['best_score'] == 0.7161 data_loader = DataLoader(EvalDataset(), batch_size=1)162 eval_hook = EvalHookCls(data_loader, save_best='mAP', rule='less')163 with tempfile.TemporaryDirectory() as tmpdir:164 logger = get_logger('test_eval')165 runner = EpochBasedRunner(166 model=model,167 batch_processor=None,168 optimizer=optimizer,169 work_dir=tmpdir,170 logger=logger)171 runner.register_checkpoint_hook(dict(interval=1))172 runner.register_hook(eval_hook)173 runner.run([loader], [('train', 1)], 8)174 real_path = osp.join(tmpdir, 'best_mAP_epoch_6.pth')175 assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)176 assert runner.meta['hook_msgs']['best_score'] == 0.05177 data_loader = DataLoader(EvalDataset(), batch_size=1)178 eval_hook = EvalHookCls(data_loader, save_best='mAP')179 with tempfile.TemporaryDirectory() as tmpdir:180 logger = get_logger('test_eval')181 runner = EpochBasedRunner(182 model=model,183 batch_processor=None,184 optimizer=optimizer,185 work_dir=tmpdir,186 logger=logger)187 runner.register_checkpoint_hook(dict(interval=1))188 runner.register_hook(eval_hook)189 runner.run([loader], [('train', 1)], 2)190 real_path = osp.join(tmpdir, 'best_mAP_epoch_2.pth')191 assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)192 assert runner.meta['hook_msgs']['best_score'] == 0.4193 resume_from = osp.join(tmpdir, 'latest.pth')194 loader = DataLoader(ExampleDataset(), batch_size=1)195 eval_hook = EvalHookCls(data_loader, save_best='mAP')196 runner = EpochBasedRunner(197 model=model,198 batch_processor=None,199 optimizer=optimizer,200 work_dir=tmpdir,201 logger=logger)202 runner.register_checkpoint_hook(dict(interval=1))203 runner.register_hook(eval_hook)204 runner.resume(resume_from)205 runner.run([loader], [('train', 1)], 8)206 real_path = osp.join(tmpdir, 'best_mAP_epoch_4.pth')207 assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)...

Full Screen

Full Screen

tether_task_runner.py

Source:tether_task_runner.py Github

copy

Full Screen

...108 self.end_headers()109 resp_writer = ipc.FramedWriter(self.wfile)110 resp_writer.write_framed_message(resp_body)111 return TaskRunnerHTTPHandler112class TaskRunner(object):113 """This class ties together the server handling the requests from114 the parent process and the instance of TetherTask which actually115 implements the logic for the mapper and reducer phases116 """117 def __init__(self,task):118 """119 Construct the runner120 Parameters121 ---------------------------------------------------------------122 task - An instance of tether task123 """124 self.log=logging.getLogger("TaskRunner:")125 if not(isinstance(task, avro.tether.tether_task.TetherTask)):126 raise ValueError("task must be an instance of tether task")127 self.task=task128 self.server=None129 self.sthread=None130 def start(self,outputport=None,join=True):131 """132 Start the server133 Parameters134 -------------------------------------------------------------------135 outputport - (optional) The port on which the parent process is listening136 for requests from the task.137 - This will typically be supplied by an environment variable138 we allow it to be supplied as an argument mainly for debugging139 join - (optional) If set to fault then we don't issue a join to block140 until the thread excecuting the server terminates.141 This is mainly for debugging. By setting it to false,142 we can resume execution in this thread so that we can do additional143 testing144 """145 port = avro.tether.util.find_port()146 address=("localhost",port)147 def thread_run(task_runner=None):148 task_runner.server = http_server.HTTPServer(address, HTTPHandlerGen(task_runner))149 task_runner.server.allow_reuse_address = True150 task_runner.server.serve_forever()151 # create a separate thread for the http server152 sthread=threading.Thread(target=thread_run,kwargs={"task_runner":self})153 sthread.start()154 self.sthread=sthread155 # This needs to run in a separat thread b\c serve_forever() blocks156 self.task.open(port,clientPort=outputport)157 # wait for the other thread to finish158 if (join):159 self.task.ready_for_shutdown.wait()160 self.server.shutdown()161 # should we do some kind of check to make sure it exits162 self.log.info("Shutdown the logger")163 # shutdown the logging164 logging.shutdown()165 def close(self):166 """167 Handler for the close message168 """169 self.task.close()170if __name__ == '__main__':171 # TODO::Make the logging level a parameter we can set172 # logging.basicConfig(level=logging.INFO,filename='/tmp/log',filemode='w')173 logging.basicConfig(level=logging.INFO)174 if (len(sys.argv)<=1):175 print("Error: tether_task_runner.__main__: Usage: tether_task_runner task_package.task_module.TaskClass")176 raise ValueError("Usage: tether_task_runner task_package.task_module.TaskClass")177 fullcls=sys.argv[1]178 mod,cname=fullcls.rsplit(".",1)179 logging.info("tether_task_runner.__main__: Task: {0}".format(fullcls))180 modobj=__import__(mod,fromlist=cname)181 taskcls=getattr(modobj,cname)182 task=taskcls()183 runner=TaskRunner(task=task)...

Full Screen

Full Screen

join.py

Source:join.py Github

copy

Full Screen

1from django.core.management.base import BaseCommand2from libs.dump import dump_sql3from apps.runner.models import Book, Publisher, Author4class Command(BaseCommand):5 # manage.pyで動作させた時に引数を受け取れるようにする6 args = '引数'7 def handle(self, *args, **options):8 if 'inner' in args:9 self.inner_join()10 if 'left' in args:11 self.left_join()12 if 'backward' in args:13 self.backward_join()14 if 'multi' in args:15 self.multi_join()16 def inner_join(self):17 # 微妙に違うSQLが出される18 # INNER JOINするけど、SELECT句にはpublisherの列は無い19 b1 = Book.objects.filter(publisher__num_awards=5).values()20 #=> SELECT "runner_book"."id", "runner_book"."name", "runner_book"."pages", "runner_book"."price",21 # "runner_book"."rating", "runner_book"."publisher_id", "runner_book"."pubdate"22 # FROM "runner_book"23 # INNER JOIN "runner_publisher" ON ( "runner_book"."publisher_id" = "runner_publisher"."id" )24 # WHERE "runner_publisher"."num_awards" = %s25 # LIMIT 21 - PARAMS = (5,)26 print(b1)27 dump_sql()28 # INNER JOINし、SELECT句にもpublisherの列がある29 b2 = Book.objects.select_related().all().values()30 #=> SELECT "runner_book"."id", "runner_book"."name", "runner_book"."pages", "runner_book"."price",31 # "runner_book"."rating", "runner_book"."publisher_id", "runner_book"."pubdate",32 # "runner_publisher"."id", "runner_publisher"."name", "runner_publisher"."num_awards"33 # FROM "runner_book"34 # INNER JOIN "runner_publisher" ON ( "runner_book"."publisher_id" = "runner_publisher"."id" )35 # LIMIT 21 - PARAMS = ()36 print(b2)37 dump_sql()38 # INNER JOINとWHEREを使って、全列出す39 b3 = Book.objects.filter(publisher__num_awards=5).select_related().all().values()40 #=> SELECT "runner_book"."id", "runner_book"."name", "runner_book"."pages", "runner_book"."price",41 # "runner_book"."rating", "runner_book"."publisher_id", "runner_book"."pubdate",42 # "runner_publisher"."id", "runner_publisher"."name", "runner_publisher"."num_awards"43 # FROM "runner_book"44 # INNER JOIN "runner_publisher" ON ( "runner_book"."publisher_id" = "runner_publisher"."id" )45 # WHERE "runner_publisher"."num_awards" = %s46 # LIMIT 21 - PARAMS = (5,)47 print(b3)48 dump_sql()49 def left_join(self):50 # id IS NULL51 # p1 = Publisher.objects.filter(book__isnull=False) # これだと、INNER JOIN になる52 p1 = Publisher.objects.filter(book__isnull=True).values()53 #=> SELECT *54 # FROM "runner_publisher"55 # LEFT OUTER JOIN "runner_book" ON ( "runner_publisher"."id" = "runner_book"."publisher_id" )56 # WHERE "runner_book"."id" IS NULL57 print(p1)58 dump_sql()59 # publisher_id IS NULL60 p2 = Publisher.objects.filter(book__publisher__isnull=True).values()61 #=> SELECT *62 # FROM "runner_publisher"63 # LEFT OUTER JOIN "runner_book" ON ( "runner_publisher"."id" = "runner_book"."publisher_id" )64 # WHERE "runner_book"."publisher_id" IS NULL65 print(p2)66 dump_sql()67 def backward_join(self):68 # p = Author.objects.filter(age__gt=5)や69 # p = Author.objects.all() だと逆引きできない70 a = Author.objects.get(pk=1).book_set.all().values()71 #=> SELECT "runner_book"."id", "runner_book"."name", "runner_book"."pages", "runner_book"."price",72 # "runner_book"."rating", "runner_book"."publisher_id", "runner_book"."pubdate"73 # FROM "runner_book"74 # INNER JOIN "runner_book_authors" ON ( "runner_book"."id" = "runner_book_authors"."book_id" )75 # WHERE "runner_book_authors"."author_id" = %s76 # LIMIT 21 - PARAMS = (1,)77 print(a)78 dump_sql()79 def multi_join(self):80 a = Author.objects.filter(book__publisher__name='Pub2').values()81 #=> SELECT "runner_author"."id", "runner_author"."name", "runner_author"."age"82 # FROM "runner_author"83 # INNER JOIN "runner_book_authors" ON ( "runner_author"."id" = "runner_book_authors"."author_id" )84 # INNER JOIN "runner_book" ON ( "runner_book_authors"."book_id" = "runner_book"."id" )85 # INNER JOIN "runner_publisher" ON ( "runner_book"."publisher_id" = "runner_publisher"."id" )86 # WHERE "runner_publisher"."name" = %s87 # LIMIT 21 - PARAMS = ('Pub2',)88 print(a)...

Full Screen

Full Screen

test_add.py

Source:test_add.py Github

copy

Full Screen

...8from mpl_pymanage.utils import shell, file_content9from mpl_pymanage.mpl_pymanage import cli10class TestAdd(unittest.TestCase):11 def test_add_package(self):12 runner = CliRunner()13 with runner.isolated_filesystem():14 add_package('level1.level2.level3')15 self.assertTrue(exists('level1/level2/level3/__init__.py'))16 def test_add_license(self):17 runner = CliRunner()18 with runner.isolated_filesystem():19 shell('touch setup.py')20 cwd = Path.cwd()21 add_license(cwd, 'MIT')22 self.assertTrue(exists(cwd / 'LICENSE'))23 def test_add_license_with_string(self):24 runner = CliRunner()25 with runner.isolated_filesystem():26 shell('touch setup.py')27 add_license('.', 'MIT')28 self.assertTrue(exists(Path.cwd() / 'LICENSE'))29 def test_add_license_no_setup_py(self):30 runner = CliRunner()31 with runner.isolated_filesystem():32 add_license('.', 'MIT')33 self.assertTrue(exists(Path.cwd() / 'LICENSE'))34 def test_add_license_existing(self):35 runner = CliRunner()36 with runner.isolated_filesystem():37 with self.assertRaises(click.BadParameter):38 shell('touch LICENSE')39 add_license('.', 'MIT')40 self.assertTrue(exists(Path.cwd() / 'LICENSE'))41 def test_add_gitignore(self):42 runner = CliRunner()43 with runner.isolated_filesystem():44 runner.invoke(cli, ['add', 'gitignore'])45 cwd = Path.cwd()46 self.assertTrue(exists(cwd / '.gitignore'))47 def _test_add_setup_py(self):48 runner = CliRunner()49 with runner.isolated_filesystem():50 runner.invoke(cli, ['add', 'setup.py', '--name', 'test_project'], input='\n\n\n\n\n')51 cwd = Path.cwd()52 self.assertTrue(exists(cwd / 'setup.py'))53 def _test_add_setup_py_overwrite(self):54 runner = CliRunner()55 with runner.isolated_filesystem():56 shell('touch setup.py')57 cwd = Path.cwd()58 assert getsize(cwd / 'setup.py') == 059 runner.invoke(cli, ['add', 'setup.py', '--name', 'test_project'], input='\n\n\n\n\ny\n')60 self.assertTrue(exists(cwd / 'setup.py'))61 assert getsize(cwd / 'setup.py') > 062 def test_add_docs(self):63 runner = CliRunner()64 with runner.isolated_filesystem():65 shell('touch setup.py')66 cwd = Path.cwd()67 runner.invoke(cli, ['add', 'docs'])68 self.assertTrue(exists(cwd / 'docs' / 'conf.py'))69 def test_add_github_action(self):70 runner = CliRunner()71 with runner.isolated_filesystem():72 cwd = Path.cwd()73 target = cwd / '.github' / 'workflows' / 'check.yml'74 assert not exists(target)75 result = runner.invoke(cli, ['add', 'github-action'], input='abc\nghi\n')76 assert exists(target)77 check_yml = file_content(target)78 assert 'abc' in check_yml79 assert 'ghi' in check_yml80 assert ':PACKAGE:' not in check_yml81 assert ':TEST:' not in check_yml82 def test_add_github_action_overwrite(self):83 runner = CliRunner()84 with runner.isolated_filesystem():85 cwd = Path.cwd()86 os.mkdir(cwd / '.github')87 os.mkdir(cwd / '.github' / 'workflows')88 target = cwd / '.github' / 'workflows' / 'check.yml'89 shell('touch ' + str(target))90 assert exists(target)91 runner.invoke(cli, ['add', 'github-action'], input='abc\nghi\ny\n')92 assert exists(target)93 check_yml = file_content(target)94 assert 'abc' in check_yml95 assert 'ghi' in check_yml96 assert ':PACKAGE:' not in check_yml97 assert ':TEST:' not in check_yml98 def test_add_github_action_no_overwrite(self):99 runner = CliRunner()100 with runner.isolated_filesystem():101 cwd = Path.cwd()102 os.mkdir(cwd / '.github')103 os.mkdir(cwd / '.github' / 'workflows')104 target = cwd / '.github' / 'workflows' / 'check.yml'105 shell('touch ' + str(target))106 assert exists(target)107 runner.invoke(cli, ['add', 'github-action'], input='abc\nghi\nn\n')108 assert exists(target)109 check_yml = file_content(target)110 assert 'abc' not in check_yml111if __name__ == '__main__':...

Full Screen

Full Screen

create_test_runner_script.py

Source:create_test_runner_script.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# Copyright 2015 The Chromium Authors. All rights reserved.4# Use of this source code is governed by a BSD-style license that can be5# found in the LICENSE file.6"""Creates a script to run an android test using build/android/test_runner.py.7"""8import argparse9import os10import sys11from util import build_utils12SCRIPT_TEMPLATE = """\13#!/usr/bin/env python14#15# This file was generated by build/android/gyp/create_test_runner_script.py16import logging17import os18import sys19def main():20 script_directory = os.path.dirname(__file__)21 def ResolvePath(path):22 \"\"\"Returns an absolute filepath given a path relative to this script.23 \"\"\"24 return os.path.abspath(os.path.join(script_directory, path))25 test_runner_path = ResolvePath('{test_runner_path}')26 test_runner_args = {test_runner_args}27 test_runner_path_args = {test_runner_path_args}28 for arg, path in test_runner_path_args.iteritems():29 test_runner_args.extend([arg, ResolvePath(path)])30 test_runner_cmd = ' '.join(31 [test_runner_path] + test_runner_args + sys.argv[1:])32 logging.critical(test_runner_cmd)33 os.system(test_runner_cmd)34if __name__ == '__main__':35 sys.exit(main())36"""37def main():38 parser = argparse.ArgumentParser()39 parser.add_argument('--script-output-path',40 help='Output path for executable script.')41 parser.add_argument('--depfile',42 help='Path to the depfile. This must be specified as '43 "the action's first output.")44 # We need to intercept any test runner path arguments and make all45 # of the paths relative to the output script directory.46 group = parser.add_argument_group('Test runner path arguments.')47 group.add_argument('--output-directory')48 group.add_argument('--isolate-file-path')49 args, test_runner_args = parser.parse_known_args()50 def RelativizePathToScript(path):51 """Returns the path relative to the output script directory."""52 return os.path.relpath(path, os.path.dirname(args.script_output_path))53 test_runner_path = os.path.join(54 os.path.dirname(__file__), os.path.pardir, 'test_runner.py')55 test_runner_path = RelativizePathToScript(test_runner_path)56 test_runner_path_args = {}57 if args.output_directory:58 test_runner_path_args['--output-directory'] = RelativizePathToScript(59 args.output_directory)60 if args.isolate_file_path:61 test_runner_path_args['--isolate-file-path'] = RelativizePathToScript(62 args.isolate_file_path)63 with open(args.script_output_path, 'w') as script:64 script.write(SCRIPT_TEMPLATE.format(65 test_runner_path=str(test_runner_path),66 test_runner_args=str(test_runner_args),67 test_runner_path_args=str(test_runner_path_args)))68 os.chmod(args.script_output_path, 0750)69 if args.depfile:70 build_utils.WriteDepfile(71 args.depfile,72 build_utils.GetPythonDependencies())73if __name__ == '__main__':...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt.js');2var runner = new wpt.Runner();3runner.runTest(options, function(err, data) {4 if (err) {5 console.log("Error: " + err);6 } else {7 console.log("Data: " + data);8 }9});10var wpt = require('wpt.js');11var runner = new wpt.Runner();12runner.runTest(options, function(err, data) {13 if (err) {14 console.log("Error: " + err);15 } else {16 console.log("Data: " + data);17 runner.getTestStatus(data, function(err, data) {18 if (err) {19 console.log("Error: " + err);20 } else {21 console.log("Data: " + data);22 }23 });24 }25});26The test status can be used to check the status of the test using the getTestResults() method. The method takes a test ID as the first parameter and a callback function as the second parameter. The callback function will be called with two parameters: err and data. If an error occurs, the err parameter will contain the error message. Otherwise, the data parameter

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.8fba6d2f2e3d6c8c8a0a6f3c3b1f9e09');3wpt.runTest('www.google.com', { location: 'Dulles:Chrome', connectivity: '3G' }, function(err, data) {4 if (err) {5 console.log('Error: ' + err);6 } else {7 console.log('Test Results: ' + data);8 }9});

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 wpt 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