def tearDown(self): super(SecurityGroupDeleteTest, self).tearDown() (sec_mod.SecurityGroupInstanceAssociation. find_by) = self.original_find_by (sec_mod.SecurityGroupInstanceAssociation. delete) = self.original_delete unstub()
def tearDown(self): super(FreshInstanceTasksTest, self).tearDown() os.remove(self.cloudinit) os.remove(self.guestconfig) InstanceServiceStatus.find_by = self.orig_ISS_find_by DBInstance.find_by = self.orig_DBI_find_by unstub()
def testUnstubInstance(self): rex = Dog() when(rex).bark('Miau').thenReturn('Wuff') unstub() assert rex.bark('Miau') == 'Miau!'
def testBuildWithNestedBundles(self): import __builtin__, pickle from mockito import when, unstub b = os.path.join('/', 'b.js') when(__builtin__).open(b).thenReturn(StrIO('b')) @worker def content(files, bundle): for a in files: assert a == 'a.js' yield 'a' @worker def store(contents, bundle): for content in contents: assert content == 'ab' yield 'ab.js' env = ets.Environment(mode='development', map_from='/') nested_bundle = ets.Bundle(assets=['a.js'], env=env, development=[content]) #keep in mind that build() expects a relative path at the end of the pipe bundle = ets.Bundle(assets=[nested_bundle, 'b.js'], env=env, development=[ets.f.read, ets.f.merge, store]) assert bundle.build() == [os.path.join('/', 'ab.js')] unstub()
def tearDown(self): super(RedisGuestAgentManagerTest, self).tearDown() redis_service.RedisAppStatus = self.origin_RedisAppStatus redis_service.RedisApp.stop_db = self.origin_stop_redis redis_service.RedisApp.start_redis = self.origin_start_redis redis_service.RedisApp._install_redis = self.origin_install_redis unstub()
def setup_soledad(self): unstub() # making sure all mocks from other tests are reset # making sure soledad test folder is not there if (os.path.isdir(soledad_test_folder)): shutil.rmtree(soledad_test_folder) self.soledad = initialize_soledad(tempdir=soledad_test_folder) self.mail_address = "*****@*****.**" # resetting soledad querier SoledadQuerier.reset() SoledadQuerier.get_instance(soledad=self.soledad) # setup app PixelatedMail.from_email_address = self.mail_address self.app = pixelated.user_agent.app.test_client() self.account = FakeAccount() self.pixelated_mailboxes = PixelatedMailBoxes(self.account) self.mail_sender = mock() self.tag_index = TagIndex(os.path.join(soledad_test_folder, 'tag_index')) self.tag_service = TagService(self.tag_index) self.draft_service = DraftService(self.pixelated_mailboxes) self.mail_service = MailService(self.pixelated_mailboxes, self.mail_sender, self.tag_service) SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index' self.search_engine = SearchEngine() self.search_engine.index_mails(self.mail_service.all_mails()) pixelated.user_agent.mail_service = self.mail_service pixelated.user_agent.draft_service = self.draft_service pixelated.user_agent.tag_service = self.tag_service pixelated.user_agent.search_engine = self.search_engine
def testUnstubMockedInstanceDoesNotHideTheClass(self): when(Dog).waggle().thenReturn('Nope!') rex = Dog() when(rex).waggle().thenReturn('Sure!') assert rex.waggle() == 'Sure!' unstub() assert rex.waggle() == 'Wuff!'
def testAddNewMethodOnInstanceInLooseMode(self): rex = Dog() when(rex, strict=False).walk() rex.walk() unstub() with pytest.raises(AttributeError): rex.walk
def test_select_by_default_no_match(self): manager = WindowManager() browser = self._make_mock_browser( {'name': 'win1', 'title': "Title 1", 'url': 'http://localhost/page1.html'}, {'name': 'win2', 'title': "Title 2", 'url': 'http://localhost/page2.html'}, {'name': 'win3', 'title': "Title 3", 'url': 'http://localhost/page3.html'}) self.assertRaises(ValueError, manager.select, browser, "win-1") unstub()
def tearDown(self): super(GuestAgentCouchbaseManagerTest, self).tearDown() couch_service.CouchbaseAppStatus = self.origin_CouchbaseAppStatus volume.VolumeDevice.format = self.origin_format volume.VolumeDevice.mount = self.origin_mount couch_service.CouchbaseApp.stop_db = self.origin_stop_db couch_service.CouchbaseApp.start_db = self.origin_start_db unstub()
def test_path(self): """Test get relative data path.""" test_path = "/a/b/Packages" when(os.path).exists(test_path + "/ColorHighlighter/" + COLOR_HIGHLIGHTER_SETTINGS_NAME).thenReturn(True) when(sublime).packages_path().thenReturn(test_path) self.assertEqual("Packages/User/ColorHighlighter", path.data_path(path.RELATIVE)) unstub(sublime) unstub(os.path)
def test_create_enable_gutter_icons_st2(self): # pylint: disable=invalid-name """Test gutter icons can't be enabled in ST2.""" when(st_helper).is_st3().thenReturn(False) settings = GutterIconsColorHighlighterSettings({ "enabled": True, }) self.assertFalse(settings.enabled) unstub(st_helper)
def test_path_package(self): """Test get relative icons path with a package installation.""" test_path = "/a/b/Packages" when(os.path).exists(test_path + "/ColorHighlighter/" + COLOR_HIGHLIGHTER_SETTINGS_NAME).thenReturn(False) when(sublime).packages_path().thenReturn(test_path) self.assertEqual("Packages/User/Color Highlighter/icons", path.icons_path(path.RELATIVE)) unstub(sublime) unstub(os.path)
def test_absolute_path(self): """Test get absolute icons path.""" test_path = "/a/b/Packages" when(os.path).exists(test_path + "/ColorHighlighter/" + COLOR_HIGHLIGHTER_SETTINGS_NAME).thenReturn(True) when(sublime).packages_path().thenReturn(test_path) self.assertEqual(test_path + "/User/ColorHighlighter/icons", path.icons_path(path.ABSOLUTE)) unstub(sublime) unstub(os.path)
def test_window_info_values_are_strings(self): manager = WindowManager() driver = mock() self.mock_window_info(driver, 'id', 'name', 'title', 'url') driver.current_window_handle = HANDLE info = manager._get_current_window_info(driver) self.assertEqual(info, (HANDLE, 'id', 'name', 'title', 'url')) unstub()
def test_window_id_is_web_element(self): manager = WindowManager() driver = mock() elem = mock() self.mock_window_info(driver, *[elem, '', '', '']) driver.current_window_handle = HANDLE info = manager._get_current_window_info(driver) self.assertEqual(info[1], elem) unstub()
def testUnstubClassMethod(self): original_method = Dog.waggle when(Dog).waggle().thenReturn('Nope!') unstub() rex = Dog() self.assertEqual('Wuff!', rex.waggle()) self.assertEqual(original_method, Dog.waggle)
def test_should_raise_exception_when_repository_directory_does_not_exist(self): service = RepoConfigService() when(service).getStaticRepoDir(any_value()).thenReturn("path/to/repository") when(yum_repo_server.api.services.repoConfigService.os.path).exists(any_value()).thenReturn(False) self.assertRaises(Exception, service.determine_static_repository_path, ()) unstub()
def test_create_webdriver_speed(self): ctx = mock() ctx.speed = 0.0 browser = mock() when(webdriver).Chrome().thenReturn(browser) bm = BrowserManagementKeywords(ctx) bm.open_browser('http://robotframework.org/', 'chrome') verify(browser, times=0).__call__('_speed') unstub()
def test_parse_complex_capabilities_string(self): ctx = mock() bm = BrowserManagementKeywords(ctx) expected_caps = "proxyType:manual,httpProxy:IP:port" capabilities = bm._parse_capabilities_string(expected_caps) self.assertTrue("manual", capabilities["proxyType"]) self.assertTrue("IP:port", capabilities["httpProxy"]) self.assertTrue(2, len(capabilities)) unstub()
def test_open_browser_speed(self): ctx = mock() ctx.speed = 5.0 browser = mock() when(webdriver).Chrome().thenReturn(browser) bm = BrowserManagementKeywords(ctx) bm.open_browser('http://robotframework.org/', 'chrome') self.assertEqual(browser._speed, 5.0) unstub()
def test_st3(self): """In ST3 get_binary_resource_size just calls sublime.load_binary_resource.""" when(st_helper).is_st3().thenReturn(True) test_path = "test/path" content = "content" when(sublime).load_binary_resource(test_path).thenReturn(content) self.assertEqual(len(content), get_binary_resource_size(test_path)) verify(sublime).load_binary_resource(test_path) unstub(sublime)
def test_parse_capabilities_string(self): ctx = mock() bm = BrowserManagementKeywords(ctx) expected_caps = "key1:val1,key2:val2" capabilities = bm._parse_capabilities_string(expected_caps) self.assertTrue("val1", capabilities["key1"]) self.assertTrue("val2", capabilities["key2"]) self.assertTrue(2, len(capabilities)) unstub()
def testStubsTwiceAndUnstubs(self): when(os.path).exists("test").thenReturn(False) when(os.path).exists("test").thenReturn(True) self.assertEqual(True, os.path.exists("test")) unstub() self.assertEqual(False, os.path.exists("test"))
def testPreservesClassArgumentAfterUnstub(self): self.assertEqual("Cat foo", Cat.meow("foo")) when(Cat).meow("foo").thenReturn("bar") self.assertEqual("bar", Cat.meow("foo")) unstub() self.assertEqual("Cat foo", Cat.meow("foo"))
def test_should_pick_directory_name_for_project_name_when_name_is_not_given(self): try: when(os.path).basename("/imaginary").thenReturn("imaginary") project = Project(basedir="/imaginary") self.assertEquals("imaginary", project.name) verify(os.path).basename("/imaginary") finally: unstub()
def test_select_by_url_sloppy_match(self): manager = WindowManager() browser = self._make_mock_browser( {'name': 'win1', 'title': "Title 1", 'url': 'http://localhost/page1.html'}, {'name': 'win2', 'title': "Title 2", 'url': 'http://localhost/page2.html'}, {'name': 'win3', 'title': "Title 3", 'url': 'http://localhost/page3.html'}) manager.select(browser, "url= http://LOCALHOST/page2.html ") self.assertEqual(browser.current_window.name, 'win2') unstub()
def test_select_by_name_with_bad_case(self): manager = WindowManager() browser = self._make_mock_browser( {'name': 'win1', 'title': "Title 1", 'url': 'http://localhost/page1.html'}, {'name': 'win2', 'title': "Title 2", 'url': 'http://localhost/page2.html'}, {'name': 'win3', 'title': "Title 3", 'url': 'http://localhost/page3.html'}) manager.select(browser, "name=Win2") self.assertEqual(browser.current_window.name, 'win2') unstub()
def test_select_by_title_with_multiple_matches(self): manager = WindowManager() browser = self._make_mock_browser( {'name': 'win1', 'title': "Title 1", 'url': 'http://localhost/page1.html'}, {'name': 'win2a', 'title': "Title 2", 'url': 'http://localhost/page2a.html'}, {'name': 'win2b', 'title': "Title 2", 'url': 'http://localhost/page2b.html'}) manager.select(browser, "title=Title 2") self.assertEqual(browser.current_window.name, 'win2a') unstub()
def test_asynchronosly_update_color_scheme_st2(self): # pylint: disable=invalid-name """Test asynchronosly updating color scheme can't be enabled in ST2.""" when(st_helper).is_st3().thenReturn(False) settings = Settings({ "experimental": { "asynchronosly_update_color_scheme": True } }) self.assertFalse(settings.experimental.asynchronosly_update_color_scheme) unstub(st_helper)
def testUnStubWorksOnClassAndSuperClass(self): self.assertEqual("stick", Retriever.retrieve("stick")) self.assertEqual("stick", TrickDog.retrieve("stick")) when(Retriever).retrieve("stick").thenReturn("ball") self.assertEqual("ball", Retriever.retrieve("stick")) self.assertEqual("ball", TrickDog.retrieve("stick")) when(TrickDog).retrieve("stick").thenReturn("cat") self.assertEqual("ball", Retriever.retrieve("stick")) self.assertEqual("cat", TrickDog.retrieve("stick")) unstub(TrickDog) self.assertEqual("ball", Retriever.retrieve("stick")) self.assertEqual("ball", TrickDog.retrieve("stick")) unstub(Retriever) self.assertEqual("stick", Retriever.retrieve("stick")) self.assertEqual("stick", TrickDog.retrieve("stick"))
def test_create_webdriver(self): ctx = mock() bm = BrowserManagementKeywords(ctx) FakeWebDriver = mock() driver = mock() when(FakeWebDriver).__call__(some_arg=1).thenReturn(driver) when(FakeWebDriver).__call__(some_arg=2).thenReturn(driver) when(ctx).register_browser(driver, 'fake1').thenReturn(0) webdriver.FakeWebDriver = FakeWebDriver try: index = bm.create_webdriver('FakeWebDriver', 'fake1', some_arg=1) verify(ctx).register_browser(driver, 'fake1') self.assertEqual(index, 0) my_kwargs = {'some_arg': 2} bm.create_webdriver('FakeWebDriver', 'fake2', kwargs=my_kwargs) verify(ctx).register_browser(driver, 'fake2') finally: del webdriver.FakeWebDriver unstub()
def test_order_request_exceeds_allowed_hour( self, client, normal_user, menu, ): """ Tests that an http400 response is returned if the user is trying to make an order past the maximum allowed hour (11 AM), then checks if the user can order within the allowed hour range receiving an http201 """ request_url = reverse('meal_api:order-list', args=()) payload = { 'employee': normal_user.pk, 'selected_option': 1, 'customizations': 'TEST', 'menu': menu.uuid, } client.force_login(user=normal_user) when(datetime_utils).get_time_now(...).thenReturn(time(hour=15)) exceeded_hour_response = client.post( request_url, payload, ) unstub() when(datetime_utils).get_time_now(...).thenReturn(time(hour=10)) accepted_hour_response = client.post( request_url, payload, ) unstub() assert ( exceeded_hour_response.status_code == status.HTTP_400_BAD_REQUEST ) assert ( accepted_hour_response.status_code == status.HTTP_201_CREATED )
def test_ignore_errors_hooks(monkeypatch, hook_type, per_project): """ Test that ignore errors property overrides failed hook. """ def mock_get_repos(*args, **kwargs): return [mock(spec=GitRepository)] spy2(opengrok_tools.utils.mirror.process_hook) project_name = "foo" hook_dir = "/befelemepeseveze" hook_name = "nonexistent" if per_project: config = { HOOKDIR_PROPERTY: hook_dir, PROJECTS_PROPERTY: { project_name: {IGNORE_ERR_PROPERTY: True, HOOKS_PROPERTY: {hook_type: hook_name}} } } else: config = { IGNORE_ERR_PROPERTY: True, HOOKDIR_PROPERTY: hook_dir, PROJECTS_PROPERTY: { project_name: {HOOKS_PROPERTY: {hook_type: hook_name}} } } with monkeypatch.context() as m: mock_get_repos.called = False m.setattr("opengrok_tools.utils.mirror.get_repos_for_project", mock_get_repos) src_root = "srcroot" assert mirror_project(config, project_name, False, None, src_root) == SUCCESS_EXITVAL verify(opengrok_tools.utils.mirror).\ process_hook(hook_type, os.path.join(hook_dir, hook_name), src_root, project_name, None, None) # Necessary to disable the process_hook spy otherwise mockito will # complain about recursive invocation. unstub()
def test_retrieve_events_more(): missing_event = "more_event.json" def get_hours_back(): h_hours_ago = datetime.now() - timedelta(hours=6) return int(time.mktime(h_hours_ago.timetuple())) with open(os.path.join(CWD, missing_event)) as f: event_response = mock(json.load(f)) when(stripe.Event).list( limit=100, types=CFG.PAYMENT_EVENT_LIST, created={"gt": get_hours_back()}, starting_after="evt_001", ).thenReturn(event_response) event_check = EventCheck(6) event_check.get_events_with_last_event("evt_001") unstub()
def test_pv_simulator_should_consider_0_for_nonexistent_times_in_power_data( self): # GIVEN mocked_log = mock(logging, strict=False) TEN_O_CLOCK_PRODUCTION = 50 ELEVEN_O_CLOCK_PRODUCTION = 50 power_data = { '10:00': TEN_O_CLOCK_PRODUCTION, '11:00': ELEVEN_O_CLOCK_PRODUCTION } pv = pv_simulator(mocked_log, power_data) test_date = datetime.datetime(2017, 11, 4, 12, 00) # WHEN generated_value = pv.generate(test_date) # THEN self.assertEqual(0, generated_value) unstub()
def test_insert_registrant_carol_benjamin(): # Setting up the mocks db_mock = mock() # mock cursor_mock = mock() # mock # Rehearsing when(db_mock).cursor().thenReturn(cursor_mock) when(cursor_mock).execute("INSERT INTO REGISTRANT VALUES " "(\'Carol\', \'Benjamin\', 22, \'New York\')") \ .thenRaise(Exception("Unable to connect to database")) registration_service = RegistrationService(db_mock) registrant = Registrant("Carol", "Benjamin", 22, "New York") # dummy registration_service.insert(registrant) verify(db_mock).rollback() verify(db_mock).close() unstub(db_mock, cursor_mock)
def test_pv_simulator_should_use_injected_dict_as_source_for_generation( self): # GIVEN mocked_log = mock(logging, strict=False) TEN_O_CLOCK_PRODUCTION = 50 ELEVEN_O_CLOCK_PRODUCTION = 50 power_data = { '10:00': TEN_O_CLOCK_PRODUCTION, '11:00': ELEVEN_O_CLOCK_PRODUCTION } pv = pv_simulator(mocked_log, power_data) test_date = datetime.datetime(2017, 11, 4, 10, 00) # WHEN generated_value = pv.generate(test_date) # THEN self.assertEqual(TEN_O_CLOCK_PRODUCTION, generated_value) unstub()
def test_perform_add_action(): fake_payload["text"] = ["add vab 2019-01-01"] fake_payload["user_name"] = "fake username" action = Action(fake_payload, fake_config) action.user_id = "fake_userid" action.date_start = "2019-01-01" action.date_end = "2019-01-01" when(action).send_response(message="").thenReturn() when(requests).get( url=f"{fake_config['backend_url']}/event/users/{action.user_id}", params={ "startDate": action.date_start, "endDate": action.date_end, }).thenReturn(mock({ "status_code": 200, "text": '[{"lock": false}]' })) assert action.perform_action() == "" unstub()
def test_when_submitting_jobs_ensure_results_returned(self): for job_num in range(10): # Produce and run Jobs Locally job_mock, val1, val2 = mock_helper.generate_mock_job() expected_result = job_mock.result # Configure Mock Worker worker_mock = mock(Worker) worker_mock.name = "My Super Amazing Ultra Cool I am Running Out Of Adjectives Mock" worker_mock.job = job_mock when(worker).Worker(ANY, ANY).thenReturn(worker_mock) when(worker_mock).run().thenReturn(None) # Configure Mock Job if job_mock.name == "SumJob": when(sum_job).SumJob(ANY, ANY).thenReturn(job_mock) if job_mock.name == "LongJob": when(long_job).LongJob().thenReturn(job_mock) # Now Run It Remotely request = testing.DummyRequest() request.matchdict = {'job_type': job_mock.name} request.params['val1'] = val1 request.params['val2'] = val2 # Execute Job controller = WorkerController(request) result = controller.run_job() # Assert Some Stuff print("\n --------------- Result ---------------") print(str(result)) self.assertEquals(expected_result, result.json['result']) # Verify Mocks because we are nit picky bastards verify(worker_mock, times=1).run() verify(worker, times=1).Worker(ANY, ANY) verify(job_mock, times=0).execute() # The worker was mocked so the job should have never been executed # Reset Mocks because we are good also because if I don't do this my colleagues will flog me unstub()
def test_download_new_episodes( name: str, includes: List[str], excludes: List[str], videos: List[Video], after_filtered: List[Video], has_downloaded: Set[str], downloaded_path: Optional[Path], rendered: Optional[bool], repo: DownloadNewEpisodesRepo, ): print(name) config.general.max_days_back = 10 when(repo).get_latest_videos(...).thenReturn(videos) # Default has_downloaded to false if not specified otherwise if len(videos) > len(has_downloaded): when(repo).has_downloaded(...).thenReturn(False) for video in has_downloaded: when(repo).has_downloaded(video).thenReturn(True) if downloaded_path is not False: for video in after_filtered: when(repo).download(video).thenReturn(downloaded_path) when(repo).get_next_episode_number(...).thenReturn(1) if rendered is not None: when(repo).render(...).thenReturn(rendered) if rendered is True: when(repo).set_as_downloaded(...) case = DownloadNewEpisodes(repo) channels: List[Channel] = [Channel(includes=includes, excludes=excludes)] case.execute(channels) verifyStubbedInvocationsAreUsed() unstub()
def test_stripe_hub_customer_subscription_updated_cancel(mocker): data = { "event_id": "evt_00000000000000", "eventId": "evt_00000000000000", "event_type": "customer.subscription.updated", "customer_id": "cus_00000000000000", "subscription_id": "sub_00000000000000", "subscriptionId": "sub_00000000000000", "plan_amount": 500, "canceled_at": 1519680008, "cancel_at": 1521854209, "cancel_at_period_end": True, "nickname": "subhub", "messageCreatedAt": int(time.time()), "invoice_id": "in_test123", "uid": "user123", } customer_response = mock( { "id": "cus_00000000000000", "object": "customer", "account_balance": 0, "created": 1563287210, "currency": "usd", "metadata": { "userid": "user123" }, }, spec=stripe.Customer, ) when(stripe.Customer).retrieve( id="cus_00000000000000").thenReturn(customer_response) basket_url = CFG.SALESFORCE_BASKET_URI + CFG.BASKET_API_KEY response = mock({"status_code": 200, "text": "Ok"}, spec=requests.Response) when(boto3).client("sns", region_name=CFG.AWS_REGION).thenReturn(MockSnsClient) when(requests).post(basket_url, json=data).thenReturn(response) filename = "customer/customer-subscription-updated.json" run_customer(mocker, data, filename) unstub()
def test_select_by_title_sloppy_match(self): manager = WindowManager() browser = self._make_mock_browser( { 'name': 'win1', 'title': "Title 1", 'url': 'http://localhost/page1.html' }, { 'name': 'win2', 'title': "Title 2", 'url': 'http://localhost/page2.html' }, { 'name': 'win3', 'title': "Title 3", 'url': 'http://localhost/page3.html' }) manager.select(browser, "title= tItLe 2 ") self.assertEqual(browser.current_window.name, 'win2') unstub()
def test_running_pv_consumer_should_call_rabbit_consumer_initialize_queue_and_start_consuming( self): # GIVEN ADDRESS = '127.0.0.1' PATH = '/' mocked_log = mock(logging, strict=False) factory = mock(pv_simulator_factory(mocked_log, PATH), strict=False) outputter = mock(file_outputter(PATH), strict=False) mocked_rabbit_consumer = mock(rabbit_consumer(ADDRESS, factory, outputter), strict=False) consumer = pv_consumer(mocked_log, mocked_rabbit_consumer) # WHEN consumer.start() # THEN verify(mocked_rabbit_consumer).initialize_queue() verify(mocked_rabbit_consumer).start_consuming() unstub()
def test_get_window_titles(self): manager = WindowManager() browser = self._make_mock_browser( { 'name': 'win1', 'title': "Title 1", 'url': 'http://localhost/page1.html' }, { 'name': 'win2', 'title': "Title 2", 'url': 'http://localhost/page2.html' }, { 'name': 'win3', 'title': "Title 3", 'url': 'http://localhost/page3.html' }) self.assertEqual(manager.get_window_titles(browser), ['Title 1', 'Title 2', 'Title 3']) unstub()
def test_retrieve_stripe_subscriptions_fail(): cancel_response = mock( { "id": "cus_tester3", "object": "customer", "subscriptions": {"data": []}, "sources": {"data": [{"id": "src_123"}]}, }, spec=stripe.Customer, ) delete_response = mock( {"id": "cus_tester3", "object": "customer", "sources": []}, spec=stripe.Customer ) when(stripe.Customer).delete_source("cus_tester3", "src_123").thenReturn( delete_response ) test_fail = payments.retrieve_stripe_subscriptions(cancel_response) logger.info("test fail", test_fail=test_fail) assert test_fail == [] unstub()
def test_generate_consumption_should_be_between_ranges(self): # GIVEN a meter with initial_consumption of 0 and max of 10000 lower_boundary = 0 upper_boundary = 10 how_many_iterations = 100000 ameter = meter(lower_boundary, upper_boundary) # WHEN consumption is generated a lot of times (lot == 10000) # each consumption value should be within the defined boundaries for i in range(how_many_iterations): consumption = ameter.generate_consumption() if consumption < lower_boundary or consumption > upper_boundary: self.assertFalse( 'Found consumption of {}. Should be between {} and {}'. format(consumption, lower_boundary, upper_boundary)) # THEN self.assertTrue( 'Ran {} iterations without non-conformances in meter.generate_consumption()' ) unstub()
def test_with_mock(self): #region do mocking from mockito import when from mockito import unstub #from src.util2 import another_module; when(another_module).another_module_method().thenReturn(333) #NOTE mocking this way will not work when run together with other test methods; run it alone is fine from src.util2 import demo_mock2 when(demo_mock2).another_module_method().thenReturn( 333 ) #NOTE this works all the time; number1thumb rule is to mock with module-path in where the method is imported, NOT the method definition #endregion # testee code from src.util2.demo_mock2 import longlong_time_to_run v = longlong_time_to_run(s='sss') # will take VERY LONG to finish assert v == 's=sss s2=333' # MUST reset mock when ending unstub()
def test_set_selenium_timeout_only_affects_open_browsers(self): ctx = mock() ctx._timeout_in_secs = 5.0 _browsers = mock() ctx._browsers = _browsers first_browser, second_browser = mock(), mock() when(_browsers).get_open_browsers().thenReturn( [first_browser, second_browser] ) bm = BrowserManagementKeywords(ctx) bm.set_selenium_timeout("10 seconds") verify(first_browser).set_script_timeout(10.0) verify(second_browser).set_script_timeout(10.0) when(_browsers).get_open_browsers().thenReturn( [] ) bm.set_selenium_timeout("20 seconds") verifyNoMoreInteractions(first_browser) verifyNoMoreInteractions(second_browser) unstub()
def test_select_by_title_with_multiple_matches(self): manager = WindowManager() browser = self._make_mock_browser( { 'name': 'win1', 'title': "Title 1", 'url': 'http://localhost/page1.html' }, { 'name': 'win2a', 'title': "Title 2", 'url': 'http://localhost/page2a.html' }, { 'name': 'win2b', 'title': "Title 2", 'url': 'http://localhost/page2b.html' }) manager.select(browser, "title=Title 2") self.assertEqual(browser.current_window.name, 'win2a') unstub()
def test_stripe_payment_intent_succeeded(mocker): invoice_response = mock( { "id": "in_000000", "object": "customer", "account_balance": 0, "created": 1563287210, "currency": "usd", "subscription": "sub_000000", "period_start": 1563287210, "period_end": 1563287210, }, spec=stripe.Invoice, ) when(stripe.Invoice).retrieve(id="in_000000").thenReturn(invoice_response) data = { "event_id": "evt_00000000000000", "event_type": "payment_intent.succeeded", "brand": "Visa", "last4": "4242", "exp_month": 6, "exp_year": 2020, "charge_id": "ch_000000", "invoice_id": "in_000000", "customer_id": "cus_000000", "amount_paid": 1000, "created": 1559568879, "subscription_id": "sub_000000", "period_start": 1563287210, "period_end": 1563287210, "currency": "usd", } basket_url = CFG.SALESFORCE_BASKET_URI + CFG.BASKET_API_KEY response = mockito.mock({"status_code": 200, "text": "Ok"}, spec=requests.Response) mockito.when(boto3).client("sqs", region_name=CFG.AWS_REGION).thenReturn( MockSqsClient ) mockito.when(requests).post(basket_url, json=data).thenReturn(response) filename = "payment/payment-intent-succeeded.json" run_customer(mocker, data, filename) unstub()
def test_set_mod_loader_by_majority(mock_repo): install = Install(mock_repo) installed_mods = [ Mod("", "", mod_loader=ModLoaders.fabric), Mod("", "", mod_loader=ModLoaders.fabric), Mod("", "", mod_loader=ModLoaders.forge), Mod("", "", mod_loader=ModLoaders.unknown), Mod("", "", mod_loader=ModLoaders.unknown), Mod("", "", mod_loader=ModLoaders.unknown), ] input = ModArg("") expected_mod = [Mod("", "", mod_loader=ModLoaders.fabric)] when(mock_repo).is_installed(...).thenReturn(False) when(mock_repo).get_all_mods(...).thenReturn(installed_mods) when(install).find_download_and_install(expected_mod) install.execute([input]) verifyStubbedInvocationsAreUsed() unstub()
def test_create_underlined_squiggly_highlight_style_invalid_st2(self): # pylint: disable=invalid-name """ Test creating color highlighting settings with invaid highlighting style. underlined_squiggly highlighting style is invalid in ST2. """ when(st_helper).is_st3().thenReturn(False) self.assertRaises(AssertionError, lambda: Settings({ "search_colors_in": { "selection": { "enabled": True, "color_highlighters": { "color_scheme": { "enabled": True, "highlight_style": "underlined_squiggly" }, } } } })) unstub(st_helper)
def test_controller_view(mocker): data = { "event_id": "evt_00000000000000", "type": "payment_intent.succeeded", "brand": "Visa", "last4": "4242", "exp_month": 6, "exp_year": 2020, "charge_id": "ch_000000", "invoice_id": "in_000000", "customer_id": "cus_000000", "amount_paid": 1000, "created": 1559568879, "subscription_id": "sub_000000", "period_start": 1563287210, "period_end": 1563287210, "currency": "usd", } webhook = run_webhook(mocker, data) assert isinstance(webhook, Response) unstub()
def test_process_image(self): (issuer, repository, exam, exam_status, procedure, procedure_status, modality_type, sop_class, image_metadata, image, image_status) = self.create_image_stack() (when(BPMBusiness).process_image(...).thenReturn(({}, {}, None))) res = self.wf.process_image(image.uid, COMPUTATION_REQUEST) image_status = self.em.get_image_status('image_uid', image.uid) self.assertEqual(image_status.status, ImageStatusEnum.Processed.value) (when(BPMBusiness).process_image( ...).thenRaise(BPMProcessingInvalidException)) res = self.wf.process_image(image.uid, COMPUTATION_REQUEST) unstub() image_status = self.em.get_image_status('image_uid', image.uid) self.assertEqual(image_status.status, ImageStatusEnum.Invalid.value) when(BPMBusiness).process_image(...).thenRaise(BPMProcessingException) res = self.wf.process_image(image.uid, COMPUTATION_REQUEST) unstub() image_status = self.em.get_image_status('image_uid', image.uid) self.assertEqual(image_status.status, ImageStatusEnum.Error.value)
def test_slack_client_responder_failure(): fake_url = "http://fake_slack_url.com" fake_data = { "channel": "fake", "text": "From timereport", "attachments": "fake" } fake_headers = { "Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer fake", } when(requests).post(url=fake_url, json=fake_data, headers=fake_headers).thenReturn( mock({"status_code": 500})) test_result = slack_client_responder(token="fake", user_id="fake", attachment="fake", url=fake_url) assert test_result.status_code != 200 unstub()
def test_transaction(self): @transaction(Core.logger, Contexts.em) def test_commit(): self.em._session_.add(RepositoryORM(None, 'test', '127.0.0.1')) wrapper = ResultWrapper() wrapper2 = ResultWrapper() wrapper.EXPECTED_RESPONSE = 'Commit' wrapper2.EXPECTED_RESPONSE = 'Close session' when(self.em._session_).commit().thenAnswer(wrapper.exec) when(self.em._session_).close().thenAnswer(wrapper2.exec) test_commit() self.assertEqual(wrapper.RESPONSE, wrapper.EXPECTED_RESPONSE) self.assertEqual(wrapper2.RESPONSE, wrapper2.EXPECTED_RESPONSE) unstub(self.em._session_) @transaction(Core.logger, Contexts.em) def test_rollback(): raise Exception('Rollback') wrapper = ResultWrapper() wrapper.EXPECTED_RESPONSE = 'Rollback' when(self.em._session_).rollback().thenAnswer(wrapper.exec) when(Core.logger()).warning(...).thenReturn(None) with self.assertRaises(Exception): test_rollback() self.assertEqual(wrapper.RESPONSE, wrapper.EXPECTED_RESPONSE) unstub(self.em._session_) unstub(Core.logger())
def test_running_meter_reader_should_call_meter_generate_consumption_and_rabbit_publisher_publish( self): # GIVEN mocked_log = mock(logging) mocked_meter = mock(meter, strict=False) mocked_rabbit_publisher = mock(rabbit_publisher, strict=False) SHORT_INTERVAL = 1 DEFAULT_INTERVAL = 2 DEFAULT_CONSUMPTION = 100 when(mocked_meter).generate_consumption().thenReturn( DEFAULT_CONSUMPTION) ameter_reader = meter_reader(mocked_log, mocked_meter, DEFAULT_INTERVAL, mocked_rabbit_publisher) # WHEN ameter_reader.start() time.sleep(SHORT_INTERVAL) # THEN verify(mocked_rabbit_publisher).publish_meter(DEFAULT_CONSUMPTION) verify(mocked_meter).generate_consumption() unstub()
def test_remind_user_with_lock(): when(requests).get(url=f"{fake_config['backend_url']}/users", **kwargs).thenReturn( mock({ "status_code": 200, "text": json.dumps(dict(testuser="******")) })) lock_evt = dict(event_date=last_month(), user_id="testuser") when(requests).get( url=f"{fake_config['backend_url']}/users/testuser/locks", **kwargs, ).thenReturn(mock({ "status_code": 200, "text": json.dumps([lock_evt]) })) with expect(requests, times=0).post(...): remind_users(Slack(fake_config["bot_access_token"]), fake_config["backend_url"]) unstub()
def _global_tear_down(tmpdir, monkeypatch): """ Maintains a sane environment between tests """ try: monkeypatch.delenv('APPVEYOR') except KeyError: pass current_dir = os.getcwd() folder = Path(tmpdir).absolute() os.chdir(folder) yield unstub() # noinspection PyProtectedMember from elib_config._setup import ELIBConfig ELIBConfig.setup( app_version='not_set', app_name='not_set', config_file_path='not_set', config_sep_str='not_set' ) os.chdir(current_dir)