def test_callback_and_subscription_wont_be_removed_if_does_not_exist(self): expect(self.client, times=0).unsubscribe("my_topic") expect(self.client, times=0).message_callback_remove("my_topic") self.service.subscriptions = {} self.service.unsubscribe("my_topic") verify(self.client, times=0).unsubscribe("my_topic") verify(self.client, times=0).message_callback_remove("my_topic")
def test_service_does_not_disconnect_or_stop_loop_if_not_running(self): expect(self.client, times=0).loop_stop() expect(self.client, times=0).disconnect() self.service.running = False self.service.stop() verify(self.client, times=0).loop_start() verify(self.client, times=0).connect()
def testReconfigureStrictMock(self): when(Dog).bark() # important first call, inits theMock when(Dog, strict=False).waggle().thenReturn('Sure') expect(Dog, strict=False).weggle().thenReturn('Sure') with pytest.raises(InvocationError): when(Dog).wuggle() with pytest.raises(InvocationError): when(Dog).woggle() rex = Dog() assert rex.waggle() == 'Sure' assert rex.weggle() == 'Sure' # For documentation; the inital strict value of the mock will be used # here. So the above when(..., strict=False) just assures we can # actually *add* an attribute to the mocked object with pytest.raises(InvocationError): rex.waggle(1) verify(Dog).waggle() verify(Dog).weggle()
def testNoUnwantedInteractionsWorks(self, verification): rex = Dog() expect(rex, **verification).bark('Miau').thenReturn('Wuff') rex.bark('Miau') rex.bark('Miau') verifyNoUnwantedInteractions(rex)
def test_init_memory(self): model = Sequential() when(model).compile(loss='mean_squared_error', optimizer='Adam').thenReturn() environment = mock( { 'observation_space': Discrete(8), 'action_space': Discrete(3) }, FL) when(environment).reset().thenReturn(0) #when(environment).step(...).thenReturn((1, 10, True)) expect(environment, times=2).step(...).thenReturn((1, 10, True)) configuration = mock( { 'model': model, 'memory_size': 2, 'nb_iterations': 0, 'training_params': [], 'plot_training': False }, Configuration) test_Agent = DQN(environment, configuration) verify(environment, times=2).step(...)
def testExpectWitoutVerification(self): rex = Dog() expect(rex).bark('Miau').thenReturn('Wuff') verifyNoMoreInteractions(rex) rex.bark('Miau') with pytest.raises(VerificationError): verifyNoMoreInteractions(rex)
def test_mqtt_client_connects_when_starting_service(self): expect(self.client, times=1).connect(host=Config.MQTT.BROKER, port=Config.MQTT.PORT, keepalive=Config.MQTT.KEEP_ALIVE) self.service.start() verify(self.client, times=1).connect(host=Config.MQTT.BROKER, port=Config.MQTT.PORT, keepalive=Config.MQTT.KEEP_ALIVE)
def testFailImmediatelyIfWantedCountExceeds(self, verification): rex = Dog() expect(rex, **verification).bark('Miau').thenReturn('Wuff') rex.bark('Miau') rex.bark('Miau') with pytest.raises(InvocationError): rex.bark('Miau')
def test_subscribes_to_sensor_topic(self): expect(self.mock_mqtt_service, times=1).subscribe( topic="sensor/moisture/#", handler=self.service._handle_moisture_reading) self.service.start() verify(self.mock_mqtt_service, times=1).subscribe( topic="sensor/moisture/#", handler=self.service._handle_moisture_reading)
def test_logs_exception_when_unreadable_mqtt_message_payload(self): payload = "this is invalid json {}" msg = mock({"payload": payload}) expect(self.service.logger, times=1).exception("Error reading moisture reading") self.service._handle_moisture_reading(None, None, msg) verify(self.service.logger, times=1).exception("Error reading moisture reading")
def test_subscribes_to_topic_and_adds_callback(self): mock_callback = mock() expect(self.client, times=1).subscribe("my_topic") expect(self.client, times=1).message_callback_add("my_topic", any) self.service.subscribe("my_topic", mock_callback) verify(self.client, times=1).subscribe("my_topic") verify(self.client, times=1).message_callback_add("my_topic", any) assert self.service.subscriptions == {"my_topic": mock_callback}
def test_unsubscribes_to_topic_and_removes_callback(self): expect(self.client, times=1).unsubscribe("my_topic") expect(self.client, times=1).message_callback_remove("my_topic") self.service.subscriptions = {"my_topic": mock()} self.service.unsubscribe("my_topic") verify(self.client, times=1).unsubscribe("my_topic") verify(self.client, times=1).message_callback_remove("my_topic") assert self.service.subscriptions == {}
def testUseWhenAndExpectTogetherVerifyNoUnwatedInteractions(self): rex = Dog() when(rex).waggle() expect(rex, times=1).bark('Miau') rex.waggle() rex.bark('Miau') verifyNoUnwantedInteractions()
def test_get_log_weight_from_canform(): """ Test that the _update_covform function is called before returning the log-weight parameter. """ gaussian_a = Gaussian(prec=2.0, h_vec=1.0, g_val=0.0, var_names=["a"]) expect(Gaussian, times=1)._update_covform() gaussian_a.get_log_weight() verifyNoUnwantedInteractions() unstub()
def test_callback_and_subscription_wont_be_added_if_already_exists(self): mock_callback = mock() expect(self.client, times=0).subscribe("my_topic") expect(self.client, times=0).message_callback_add("my_topic", mock_callback) self.service.subscriptions = {"my_topic": mock()} self.service.subscribe("my_topic", mock_callback) verify(self.client, times=0).subscribe("my_topic") verify(self.client, times=0).message_callback_add("my_topic", mock_callback)
def test_when_moisture_reading_above_threshold_no_watering_event_created( self): payload = json.dumps({ "moisture_level": 50.0, "measured_at": "2020-08-20T13:33:22.539073" }) msg = mock({"payload": payload}) expect(self.mock_mqtt_service, times=0).publish("event/water_plant") self.service._handle_moisture_reading(None, None, msg) verify(self.mock_mqtt_service, times=0).publish("event/water_plant")
def testNoUnwantedInteractionsForAllRegisteredObjects(self): rex = Dog() mox = Dog() expect(rex, times=1).bark('Miau') expect(mox, times=1).bark('Miau') rex.bark('Miau') mox.bark('Miau') verifyNoUnwantedInteractions()
def test_service_does_not_connect_or_loop_if_already_running(self): expect(self.client, times=0).loop_start() expect(self.client, times=0).connect(host=Config.MQTT.BROKER, port=Config.MQTT.PORT, keepalive=Config.MQTT.KEEP_ALIVE) self.service.running = True self.service.start() verify(self.client, times=0).loop_start() verify(self.client, times=0).connect(host=Config.MQTT.BROKER, port=Config.MQTT.PORT, keepalive=Config.MQTT.KEEP_ALIVE)
def test_from_icao(): test_icao = 'UGTB' metar_string = 'metar string' expect(weather.Weather)._set_station_name() expect(weather.Weather).fill_from_metar_data() when(avwx.metar).fetch(test_icao).thenReturn(metar_string) when(avwx.metar).parse(test_icao, metar_string).thenReturn( ('metar data', 'metar_units')) wx = weather.Weather(test_icao) assert wx.source == test_icao assert wx.station_icao == test_icao assert wx.source_type == 'ICAO'
def test_get_g_from_covform(): """ Test that the _update_canform function is called before returning the g parameter. """ gaussian_a = Gaussian(cov=2.0, mean=1.0, log_weight=0.0, var_names=["a"]) expect(Gaussian, times=1)._update_canform() gaussian_a.get_g() verifyNoUnwantedInteractions() unstub()
def test_from_metar_string(): test_string = 'some string' test_icao = 'UGTB' expect(weather.Weather)._set_station_name() expect(weather.Weather).fill_from_metar_data() when(utils).extract_station_from_metar_str(test_string).thenReturn( test_icao) when(avwx.metar).parse(test_icao, test_string).thenReturn( ('metar data', 'metar_units')) wx = weather.Weather(test_string) assert wx.source == test_string assert wx.station_icao == test_icao assert wx.source_type == 'METAR'
def test_press_go(self): # configure the mock browser library expect(LibraryLoader.get_instance().bl).click( selector=locator['groups_page']['go_button']).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) groups_page = GroupsPage() # method under test gets called groups_page.press_go() # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def test_go_to_admin_main_page(self): # configure the mock selenium library for go_to_admin_main_page()'s calls expect(LibraryLoader.get_instance().sl).go_to( expected_admin_main_page_url).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) admin_main_page = AdminMainPage() # method under test gets called admin_main_page.go_to_admin_main_page() # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def test_sends_alert_when_reading_is_unreasonably_high(self): payload = json.dumps({ "moisture_level": 100.0, "measured_at": "2020-08-20T13:33:22.539073" }) msg = mock({"payload": payload}) expect(self.mock_mqtt_service, times=1).publish("alert/email", "Unexpected moisture level 100% detected") self.service._handle_moisture_reading(None, None, msg) verify(self.mock_mqtt_service, times=1).publish("alert/email", "Unexpected moisture level 100% detected")
def test_select_delete_selected_groups_dropdown(self): # configure the mock selenium library for select_delete_selected_groups_dropdown()'s calls expect(LibraryLoader.get_instance().sl).click_element( locator=locator['groups_page']['delete_selected_groups_option'] ).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) groups_page = GroupsPage() # method under test gets called groups_page.select_delete_selected_groups_dropdown() # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def do_test_select_checkbox_for_group(group_name): # configure the mock selenium library for select_checkbox_for_group()'s calls group_element_checkbox_locator = locator['groups_page']['generic_group_element_checkbox'] % group_name expect(LibraryLoader.get_instance().sl).click_element(locator=group_element_checkbox_locator).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) groups_page = GroupsPage() # method under test gets called groups_page.select_checkbox_for_group(group_name) # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def test_click_on_save_button(self): # configure the mock browser library for click_on_save_button()'s calls expect(LibraryLoader.get_instance().bl).click( selector=locator['add_group_page']['save_button']).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) add_group_page = AddGroupPage() # method under test gets called add_group_page.click_on_save_button() # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def test_clear_available_permissions_filter(self): # configure the mock browser library for clear_available_permissions_filter()'s calls expect(LibraryLoader.get_instance().bl).clear_text( selector=locator['add_group_page'] ['input_permission_field']).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) add_group_page = AddGroupPage() # method under test gets called add_group_page.clear_available_permissions_filter() # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def test_press_confirm_button(self): # configure the mock selenium library for press_confirm_button()'s calls expect(LibraryLoader.get_instance().sl).click_element( locator=locator['confirm_groups_deletions_page'] ['confirm_deletion_button']).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) confirm_group_deletions_page = ConfirmGroupsDeletionsPage() # method under test gets called confirm_group_deletions_page.press_confirm_button() # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def test_enter_name_for_new_group(self): # configure the mock browser library for enter_name_for_new_group()'s calls group_name = 'blog_editors' expect(LibraryLoader.get_instance().bl).fill_text( selector=locator['add_group_page']['input_name_field'], txt=group_name).thenReturn(None) # CUT gets magically the mock instances (i.e. _loader & sl) add_group_page = AddGroupPage() # method under test gets called add_group_page.enter_name_for_new_group(group_name=group_name) # Verifies that expectations set via expect are met # all registered objects will be checked. verifyNoUnwantedInteractions()
def test_callback_inserts_sensor_reading_to_db(self): payload = json.dumps({ "moisture_level": 13.0, "measured_at": "2020-08-20T13:33:22.539073" }) msg = mock({"payload": payload}) expect(self.mock_db_cursor, times=1).execute( "INSERT INTO moisture_reading VALUES (13.0, '2020-08-20T13:33:22.539073')" ) expect(self.mock_db_connection, times=1).commit() self.service._handle_moisture_reading(None, None, msg) verify(self.mock_db_cursor, times=1).execute( "INSERT INTO moisture_reading VALUES (13.0, '2020-08-20T13:33:22.539073')" ) verify(self.mock_db_connection, times=1).commit()
def testReconfigureLooseMock(self): when(Dog, strict=False).bark() # important first call, inits theMock when(Dog, strict=False).waggle().thenReturn('Sure') expect(Dog, strict=False).weggle().thenReturn('Sure') with pytest.raises(InvocationError): when(Dog).wuggle() with pytest.raises(InvocationError): when(Dog).woggle() rex = Dog() assert rex.waggle() == 'Sure' assert rex.weggle() == 'Sure' # For documentation; see test above. strict is inherited from the # initial mock. So we return `None` assert rex.waggle(1) is None verify(Dog).waggle() verify(Dog).weggle()
def testPassIfImplicitlyVerified(self, verification): dog = mock() expect(dog, **verification).waggle().thenReturn('Sure') verifyStubbedInvocationsAreUsed(dog)
def testNoUnwantedInteractionsBarksIfUnsatisfied(self, verification): rex = Dog() expect(rex, **verification).bark('Miau').thenReturn('Wuff') with pytest.raises(VerificationError): verifyNoUnwantedInteractions(rex)
def testExpect(self): expecting = expect(Dog) assert expecting.__dict__ == {}
def testEnsureMultipleExpectsArentConfused(self): rex = Dog() expect(rex, times=1).bark('Miau').thenReturn('Wuff') expect(rex, times=1).waggle().thenReturn('Wuff') rex.bark('Miau') rex.waggle()