def test_inline_stub(self): #Stub()创建free stub inline_stub_free = Stub() #使用when()设置方法参数和返回值 when(inline_stub_free).foo(1).returns("I am inline free stub") assert_that(inline_stub_free.foo(1), is_("I am inline free stub")) #Stub(Collaborator)创建stub inline_stub = Stub(bs.bodyService) # 使用when()设置方法参数和返回值 when(inline_stub).get_height().returns("188cm") assert_that(inline_stub.get_height(), is_("188cm"))
def test_validate(self): route = Route('GET', '/test/<int:uderId>', lambda ignore: 'Test Done') route.compile() with Stub() as dispatcher: dispatcher.url = '/test/102' self.assertEqual(route.validate(dispatcher), route) with Stub() as dispatcher: dispatcher.url = '/test' self.assertEqual(route.validate(dispatcher), None)
def test_returning_type_hint(self): class MyClass: def get_name(self) -> str: return 'a name' with Stub(MyClass) as my_class: my_class.get_name().returns('another name')
def test_task_running(self): with Stub() as cmd: cmd.is_running().returns(True) cmd.brief().returns('STUB') c = self.assert_that(cmd, prego.running()) c.eval()
def test_task_running_fail(self): with Stub() as cmd: cmd.is_running().returns(False) cmd.brief().returns('STUB') c = self.assert_that(cmd, prego.running()) with self.assertRaises(prego.PregoAssertionFailed): c.eval()
def dw_instances(monkeypatch): import datadotworld with Spy(DataDotWorld) as dw, Spy(DataDotWorld) as dw_alternative: dw.api_client = dw_alternative.api_client = Stub(RestApiClient) monkeypatch.setattr( datadotworld, '_get_instance', lambda profile: dw if profile == 'default' else dw_alternative) return {'default': dw, 'alternative': dw_alternative}
def test_account_creation__report_message(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Alice'])
def test_asks_the_recorder_to_stop_recording_when_no_information_received_from_sensor(self): sensor = Stub(Sensor) recorder = Spy(Recorder) controller = Controller(sensor, recorder) controller.record_movement() assert_that(recorder.stop_recording, called())
def test_check_the_sensor_once_per_second(self): sensor = Stub(Sensor) recorder = Spy(Recorder) controller = Controller(sensor, recorder) # medir aqui la hora controller.record_movement(3) # volver a medir aquí la hora assert_that(recorder.stop_recording, called().times(3))
def test_any_arg_matches_property(self): prop_stub = Spy(CollaboratorWithProperty) when(prop_stub).prop.returns(5) with Stub(Collaborator) as stub: stub.method_accepting_property(prop=anything()).returns(2) assert_that(stub.method_accepting_property(prop_stub.prop), is_(2)) assert prop_stub.prop == 5
def test_stops_the_recording_if_sensor_raises_an_exception(self): with Stub(Sensor) as sensor: sensor.is_detecting_movement().raises(ValueError) recorder = Spy(Recorder) controller = Controller(sensor, recorder) controller.record_movement() assert_that(recorder.stop_recording, called())
def discovery_conn(table_spec_cursor, column_specs_cursor, pk_specs_cursor): with Stub() as conn: cursors_iter = iter( [table_spec_cursor, column_specs_cursor, pk_specs_cursor]) conn.cursor = lambda: next(cursors_iter) conn.get_dsn_parameters().returns({'dbname': 'test-db'}) return conn
def test_account_creation__free_stub(self): with Stub() as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called())
def config(tmpdir): with Stub(Config) as cfg: cfg.auth_token = 'token' cfg.tmp_dir = path.join(str(tmpdir), 'tmp') if not path.isdir(path.dirname(cfg.tmp_dir)): os.makedirs(path.dirname(cfg.tmp_dir)) cfg.cache_dir = path.join(str(tmpdir), 'cache') if not path.isdir(path.dirname(cfg.cache_dir)): os.makedirs(path.dirname(cfg.cache_dir)) return cfg
def test_account_creation__restricted_stub(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called())
def test__call__(self): controller = Collaborator() route = controller.callback.route route.compile() with Stub() as dispatcher: dispatcher.url = '/test/102/10.1/test' r = route.validate(dispatcher) self.assertEqual(r(controller, None), 'User 102 10.1 test')
def test_account_creation__3_accounts(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called().times(3)) assert_that(store.save, called().times(greater_than(2)))
def test_account_already_exists(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') with ProxySpy(AccountStore()) as store: store.has_user('John').returns(True) service = AccountService(store, password_service) with self.assertRaises(AlreadyExists): service.create_user('John')
def get_commons(self): with Stub() as app: app.name = 'Testing App' app.language = 'en_EN' app.description = 'Test Description' app.log_file = 'application.log' with Stub() as controllers: controllers.get_controllers().returns({}) with Stub() as styles: styles.get_styles().returns({}) with Stub() as scripts: scripts.get_scripts().returns({}) app.managers = { 'controller': controllers, } return app
def test_stub_delegates_list(self): with Stub(PasswordService) as password_service: password_service.generate().delegates( ["12345", "mypass", "nothing"]) store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called().with_args('John', '12345')) assert_that(store.save, called().with_args('Peter', 'mypass')) assert_that(store.save, called().with_args('Alice', 'nothing'))
def test_stub_delegates(self): def get_pass(): return "12345" with Stub(PasswordService) as password_service: password_service.generate().delegates(get_pass) store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called().with_args('John', '12345'))
def test_account_creation__argument_values(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called().with_args('John', 'some')) assert_that(store.save, called().with_args('John', ANY_ARG)) assert_that(store.save, never(called().with_args('Alice', anything()))) assert_that(store.save, called().with_args(contains_string('oh'), ANY_ARG))
def test_account_behaviour_with_mock(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') with Mock(AccountStore) as store: store.has_user('John') store.save('John', 'some') store.has_user('Peter') store.save('Peter', 'some') service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter']) assert_that(store, verify())
def test_processors_rings(self): # given P0 = ProcessorI() P1 = Spy() P2 = Spy() collector = Stub() A0 = M1(1) B0 = M1(5) # when P0.init(1, 1, P2, P1, 2, collector) P0.injectFirst(A0, 0) P0.injectSecond(B0, 0) # then assert_that(P1.injectFirst, called(). async (1).with_args(A0, 1, ANY_ARG)) assert_that(P2.injectSecond, called(). async (1).with_args(B0, 1, ANY_ARG))
from mamba import description, context, it, before from expects import expect, equal from doublex import Stub, Spy, ANY_ARG from doublex_expects import have_been_called_with, have_been_called from amadeus import Client, Request from amadeus.client.access_token import AccessToken with description('AccessToken') as self: with context('.bearer_token'): with before.each: request = Stub(Request) request.result = {'access_token': 'abc', 'expires_in': 1799} with Spy(Client) as client: client._unauthenticated_request(ANY_ARG).returns(request) client.client_id = '123' client.client_secret = '234' self.client = client with it('should make a new API call if no token has been loaded yet'): access_token = AccessToken(self.client) expect(access_token._bearer_token()).to(equal('Bearer abc')) expect(self.client._unauthenticated_request).to( have_been_called_with( 'POST', '/v1/security/oauth2/token', { 'grant_type': 'client_credentials', 'client_id': '123', 'client_secret': '234' }))
from expects import expect, equal, have_len from doublex import Stub from specs.helpers.test_message_queue import TestMessageQueue from specs.helpers.mamba_keywords import description, it from src.actions.create_auction import CreateAuction with description('Create Auction'): #TODO: use the aggregate in the action with it('raises an auction created event'): with Stub() as id_generator: id_generator.new_id().delegates(['an_auction_id']) message_queue = TestMessageQueue() create_auction = CreateAuction(message_queue, id_generator) create_auction.execute({ 'auctioner': 'an_auctioner_id', 'item': 'an_item_id', 'period': 'anything', 'selling_price': 600 }) raised_events = message_queue.events expect(raised_events).to(have_len(1)) expect(message_queue.events[0]).to(equal({ 'type': 'AUCTION_CREATED', 'auction_id': 'an_auction_id', 'auctioner': 'an_auctioner_id', 'item': 'an_item_id',
from tests.builders import (create_basket_created_event, create_add_item_command, create_item_added_event, create_checkout_command) with description('BasketConsumer'): with it('disregards non related events'): event = { 'sequence': 1, 'ts': 'a_timestamp', 'kind': 'irrelevant_event', } consumer = BasketConsumer(events_repository=Stub(), items_repository={}) next_events = consumer.process(event) expect(next_events).to(be_empty) with context('When processing an add_item command'): with it('generates an item_added event'): basket_id = 'a_basket_id' item_id = 'an_item_id' add_item_command = create_add_item_command(basket_id, item_id) items_repository = { item_id: { 'price': 9.99,
from mamba import description, it, context, before from apartments import get_apartments def check_apartments(subject): expect(subject).to(be_a(list)) expect(subject).to(have_len(2)) for rec in subject: expect(rec).to(have_keys('area', 'lat', 'lon', 'rooms')) with description("Apartments Spec"): with context("When no data"): with it("returns empty list"): with Stub() as db: db.execute_query(ANY_ARG).returns([]) expect( get_apartments(db=db, longitude=1, latitude=1, side=1, rooms=1, area=1)).to(equal([])) expect(get_apartments(db=db)).to(equal([])) with context("When there is data"): with before.each: self.apartments = [{ "area": "irrelevant_area", "lat": "irrelevant_lat",
def setUp(self): with Stub() as self.config: self.config.get_workspaces(ANY_ARG).returns([])
from doublex import Stub, ANY_ARG class Collaborator: def except_method(self): pass def add_method(self, a, b): pass with Stub(Collaborator) as stub: stub.except_method().raises(KeyError) stub.add_method(ANY_ARG).returns(4) print(stub.add_method(2, 3)) try: stub.except_method() except KeyError: print("key error!") from doublex import Stub with Stub() as stub: stub.example('test').returns(10) # when result = stub.example('test') print(result)
a_package_name) expect(http_client.get).to(have_been_called_with(expected_url)) with context('when we make an http call FOOOOO'): with it('retrieve a json with the info BARRRRR'): a_package_name = 'a_package_name' http_client = Spy() sut = PypiPackageVersionRetriever(http_client) result = sut.retrieve_version(a_package_name) expected_result = 42 expect(result).to(equal(expected_url)) #################### PROPUESTA ################## with context('when the http query is done'): with it('a package version is retrieved'): a_package_name = 'a name' a_version = '42' url = 'https://pypi.python.org/pypi/{}/json'.format(a_package_name) http_client = Stub(Http_client) when(http_client.get(url)).returns(a_version) sut = PypiPackageVersionRetriever(http_client) result = sut.retrieve_version(a_package_name) expected_result = a_version expect(result).to(equal(expected_result))