def test_commit_raises_session_commit_exception(self): self.sqlite_db._session.commit = fudge.Fake().expects_call().raises(ValueError) with self.assertRaises(ValueError): self.sqlite_db.commit() fudge.verify()
def test_create_not_latin_chars(self): def inspect_request(r): # NOTE: due to URL fetching, you can only raise # AssertionError here self.assertEqual(r.get_full_url(), 'http://__dummylive365service__/cgi-bin/add_song.cgi') qs = dict(cgi.parse_qsl(r.data)) self.assertEqual(qs['member_name'], "dummy_member") self.assertEqual(qs['password'], "dummy_password") self.assertEqual(qs['seconds'], '30') # c should be replaced because latin-1 can't encode that and Live365 likes latin-1 self.assertEqual(qs['title'], 'Ivan Krsti song') self.assertEqual(qs['album'], 'Ivan Krsti album') self.assertEqual(qs['artist'], 'Ivan Krsti') return True fake_urlopen = (fudge.Fake('urlopen', expect_call=True) .with_args(arg.passes_test(inspect_request))) fake_response = (fake_urlopen .returns_fake() .has_attr(code='200') .provides('read') .returns("<service response>")) with fudge.patched_context(playlists.tasks.urllib2, "urlopen", fake_urlopen): resp = self.client.post(reverse('playlists.send_track_to_live365'), { 'id': self.track.key() }) fudge.verify()
def test_expectations_with_multiple_return_values(self): db = Fake("db").expects("get_id").returns(1).expects("set_id").next_call(for_method="get_id").returns(2) eq_(db.get_id(), 1) eq_(db.set_id(), None) eq_(db.get_id(), 2) fudge.verify()
def test_dispatches_to_authorize_to_create_transaction(self): donation, donation_form = self.random_donation_and_form api = fudge.Fake("api") api.expects("transaction").with_args( amount=donation.amount, card_num=donation_form.cleaned_data["card_number"], card_code=donation_form.cleaned_data["ccv_code"], exp_date=u"%02d-%04d" % ( int(donation_form.cleaned_data["expiration_month"]), int(donation_form.cleaned_data["expiration_year"])), description=u"Donation: $%d" % donation.amount, first_name=unicode(donation.donor.name.split(" ")[0]), last_name=unicode(donation.donor.name.split(" ", 1)[-1]), address=donation.donor.address.address, city=donation.donor.address.city, state=donation.donor.address.state, zip=donation.donor.address.zipcode, ).returns({"reason_code": u"1", "reason_text": u"Some random Reason"}) get_api = fudge.Fake().expects_call().returns(api) backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "get_api", get_api): backend.purchase(donation, donation_form) fudge.verify()
def test_dont_include_repeats_suffix_if_one_time(self): donation, donation_form = self.random_donation_and_form donation.donation_type = self.random_monthly_type donation.donation_type.repeat = 0 api = fudge.Fake("api") api.expects("transaction").with_args( amount=donation.amount, card_num=donation_form.cleaned_data["card_number"], card_code=donation_form.cleaned_data["ccv_code"], exp_date=u"%02d-%04d" % ( int(donation_form.cleaned_data["expiration_month"]), int(donation_form.cleaned_data["expiration_year"])), description=u"Membership: %s" % donation.donation_type.name, first_name=unicode(donation.donor.first_name), last_name=unicode(donation.donor.last_name), address=donation.donor.address.address, city=donation.donor.address.city, state=donation.donor.address.state, zip=donation.donor.address.zipcode, ).returns({"reason_code": u"1", "reason_text": u"Some random Reason"}) get_api = fudge.Fake().expects_call().returns(api) backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "get_api", get_api): backend.purchase(donation, donation_form) fudge.verify()
def test_calls_to_recurring_donation_if_donation_is_recurring(self): donation, donation_form = self.random_donation_and_form donation.donation_type = self.random_monthly_type today = datetime.date.today() start_date = u"%s" % ((today + datetime.timedelta(days=30)) .strftime("%Y-%m-%d")) recurring_api = fudge.Fake() expiration_date = u"%(expiration_year)s-%(expiration_month)s" % ( donation_form.cleaned_data) recurring_api.expects("create_subscription").with_args( amount=donation.amount, interval_unit=arb.MONTHS_INTERVAL, interval_length=u"1", card_number=donation_form.cleaned_data["card_number"], card_code=donation_form.cleaned_data["ccv_code"], expiration_date=expiration_date, bill_first_name=u"%s" % donation.donor.name.split(" ")[0], bill_last_name=u"%s" % donation.donor.name.split(" ", 1)[-1], total_occurrences=donation.donation_type.repeat, start_date=start_date, ).returns({"messages": {"result_code": {"text_": u"Ok"}}}) fake = fudge.Fake().expects_call().returns(recurring_api) backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "get_api", self.get_api_stub()): with fudge.patched_context(backend, "get_recurring_api", fake): backend.purchase(donation, donation_form) fudge.verify()
def test_raises_exception_if_dir_does_not_exists_after_creation_attempt(self): # first assert signatures of the functions we are going to mock did not change. assert_spec(os.makedirs, ['name', 'mode']) assert_spec(os.path.exists, ['path']) # prepare state fake_makedirs = fudge.Fake('makedirs')\ .expects_call() fake_exists = fudge.Fake('exists')\ .expects_call()\ .returns(False)\ .next_call()\ .returns(False) library_db_file = os.path.join(self.test_temp_dir, 'no-such-dir', 'test_database1.db') # test with fudge.patched_context(os, 'makedirs', fake_makedirs): with fudge.patched_context(os.path, 'exists', fake_exists): try: db = LibraryDb(driver='sqlite', dbname=library_db_file) db._create_path() except Exception as exc: self.assertIn('Couldn\'t create directory', exc.message) fudge.verify()
def test_add_document_to_writer_for_each_given_identifier(self): # prepare state # TODO: It is so complicated. Find another way to mock indexer. fake_writer = fudge.Fake()\ .expects('add_document')\ .expects('commit') class FakeSearcher(object): pass FakeSearcher.documents = fudge.Fake()\ .expects_call()\ .returns([]) search = Search(self.lib) search._identifier_index = fudge.Fake('Index')\ .provides('writer')\ .returns(fake_writer)\ .provides('searcher')\ .returns(FakeSearcher()) # testing identifiers = [ {'identifier': 'ident1', 'type': 'type1', 'name': 'name1'}, {'identifier': 'ident2', 'type': 'type2', 'name': 'name2'}] search.index_identifiers(identifiers) fudge.verify()
def registry(num): try: try: fudge.clear_calls() fudge.clear_expectations() exp_order = ExpectedCallOrder(self.fake) reg.remember_expected_call_order(exp_order) eq_(len(reg.get_expected_call_order().keys()), 1) # registered first time on __init__ : exp = ExpectedCall(self.fake, "callMe", call_order=exp_order) reg.expect_call(exp) reg.expect_call(exp) reg.expect_call(exp) eq_(len(reg.get_expected_calls()), 4) # actual calls: exp() exp() exp() exp() fudge.verify() fudge.clear_expectations() except Exception, er: thread_run.errors.append(er) raise finally: thread_run.waiting -= 1
def test_with_too_many_non_matching_positional_args(self): # this may be unintuitve but specifying too many # arguments constitutes as non-matching. Why? # Because how else is it possible to implement, by index? db = self.fake db.expects('transaction').with_matching_args('update') db.transaction("update", "delete", isolation_level="lock") fudge.verify()
def test_closes_session_and_connection(self): db = LibraryDb(driver='sqlite') db.session.close = fudge.Fake('session.close').expects_call() db.connection.close = fudge.Fake('connection.close').expects_call() db.close() fudge.verify() self.assertIsNone(db._session) self.assertIsNone(db._connection)
def __exit__(self, exc_type, exc_val, exc_tb): try: if not exc_type: fudge.verify() finally: for p in self.patches: p.restore() fudge.clear_expectations()
def test_is_test_is_false_for_api_class_api_by_default(self): api_class = fudge.Fake().expects_call().with_args(arg.any(), arg.any(), delimiter=arg.any(), is_test=False) backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "api_class", api_class): backend.get_api() fudge.verify()
def test_adds_is_test_to_api_class_api_if_in_testing_mode(self): api_class = fudge.Fake().expects_call().with_args(arg.any(), arg.any(), delimiter=arg.any(), is_test=True) backend = backends.AuthorizeNetBackend(testing=True) with fudge.patched_context(backend, "api_class", api_class): backend.get_api() fudge.verify()
def inner(self, *args, **kwargs): request = fudge.Fake(HttpRequest) request.has_attr(COOKIES={}) result = func(self, request, *args, **kwargs) fudge.verify() fudge.clear_expectations() return result
def test_chained_fakes_honor_order(self): Thing = Fake("thing").remember_order().expects("__init__") holder = Thing.expects("get_holder").returns_fake() holder = holder.expects("init") thing = Thing() holder = thing.get_holder() # missing thing.init() fudge.verify()
def test_returns_false_if_database_exists(self): # first assert signatures of the functions we are going to mock did not change. assert_spec(self.sqlite_db.exists, ['self']) # prepare state self.sqlite_db.exists = fudge.Fake('exists').expects_call().returns(True) ret = self.sqlite_db.create() self.assertFalse(ret) fudge.verify()
def test_variable_resolution_for_list(self): random_list_name = "list_%d" % random.randint(100, 200) rln = RenderListNode(Variable(random_list_name), "'debug'") with stub_render_to_string(): try: rln.render(Context({random_list_name: [generate_random_model()]})) except VariableDoesNotExist: self.fail("should have found variable in context") fudge.verify()
def test_contains_list(self): db = Fake("db").expects("execute_statements").with_args( arg.contains("select * from foo")) db.execute_statements([ "update foo", "select * from foo", "drop table foo" ]) fudge.verify()
def test_updates_config(self): # first assert signatures of the functions we are going to mock did not change. assert_spec(self.sqlite_db.set_config_value, ['self', 'group', 'key', 'value']) self.sqlite_db.set_config_value = fudge.Fake('set_config_value')\ .expects_call()\ .with_args('activity', 'change', arg.any()) self.sqlite_db._mark_update() fudge.verify()
def test_task_will_invoke_provided_class(): def foo(): pass fake = Fake() fake.expects("__init__").with_args(foo) fudge.clear_calls() fudge.clear_expectations() foo = decorators.task(foo, task_class=fake) fudge.verify()
def test_global_verify(self): exp = ExpectedCall(self.fake, "callMe") exp() eq_(exp.was_called, True) eq_(len(self.reg.get_expected_calls()), 1) fudge.verify() eq_(exp.was_called, False, "call was not reset by verify()") eq_(len(self.reg.get_expected_calls()), 1, "verify() should not reset expectations")
def test_extracts_view_out_of_templatetag_call(self): random_view_name = 'hello_world_%d' % random.randint(100, 200) token = fudge.Fake() token.expects('split_contents').returns(('esi', random_view_name)) fudge.clear_calls() result = esi(Parser([]), token) self.assertEquals(str(result.view_name), random_view_name) fudge.verify()
def test_finds_new_templates_for_each_model(self): rln = RenderListNode(Variable('list'), "'debug'") num_models = random.randint(5, 10) with stub_render_to_string(): try: rln.render(Context({'list': [generate_random_model() for i in range(num_models)]})) except VariableDoesNotExist: self.fail("should have found variable in context") fudge.verify()
def test_handle_Multiword(self): bridge = fudge.Fake("bridge").provides("get_group").calls(lambda: {"1":{"name":"Bedroom"}, "2":{"name":"LivingRoom"}}) bridge.expects("set_group") light_action = hue._handle(bridge, "Turn the living room lights on") group_id = light_action.light_group action = light_action.action self.assertEqual(group_id, "2") self.assertEqual(action, "on") fudge.verify()
def test_multiple_returns_affect_order(self): db = Fake("db")\ .remember_order()\ .expects("get_id").returns(1)\ .expects("set_id")\ .next_call(for_method="get_id").returns(2) eq_(db.get_id(), 1) eq_(db.set_id(), None) eq_(db.get_id(), 2) fudge.verify()
def test_embed_dispatches_kwargs_to_backend(self): kwargs = dict( [("key-%d" % a, a) for a in range(random.randint(1, 10))]) backend = fudge.Fake() backend.provides("prepare") video = EmbeddedVideo("foo/bar", backend=backend) backend.expects("embed").with_args(video, **kwargs) fudge.clear_calls() video.embed(**kwargs) fudge.verify()
def test_dispatches_to_configured_backend(self): m = Donation() random_card = "some-random-card-%d" % random.randint(1000, 2000) fake_backend = fudge.Fake() fake_backend.expects("purchase").with_args(m, random_card) fake_get_backend = fudge.Fake() fake_get_backend.is_callable().returns(fake_backend) with fudge.patched_context(backends, "get_backend", fake_get_backend): m.purchase(random_card) fudge.verify()
def test_task_passes_args_to_the_task_class(): random_vars = ("some text", random.randint(100, 200)) def foo(): pass fake = Fake() fake.expects("__init__").with_args(foo, *random_vars) fudge.clear_calls() fudge.clear_expectations() foo = decorators.task(foo, task_class=fake, *random_vars) fudge.verify()
def test_embed_dispatches_to_backend_and_returns_result(self): random_return = random.randint(1000, 2000) backend = fudge.Fake() backend.provides("prepare") video = EmbeddedVideo("foo/bar", backend=backend) backend.expects("embed").with_args(video).returns(random_return) fudge.clear_calls() result = video.embed() self.assertEqual(result, random_return) fudge.verify()
def test_fires_donation_complete_on_successful_charge(self): donation, form = self.random_donation_and_form result = { "status": True, "random": random.randint(100, 200), } onetime_purchase = (fudge.Fake().is_callable().returns(result)) backend = backends.AuthorizeNetBackend() signal = (fudge.Fake().expects_call().with_args(sender=backend, donation=donation, signal=arg.any(), form=form, result=result)) signals.successful_purchase.connect(signal) with stub_onetime_purchase(backend, onetime_purchase): backend.purchase(donation, form) fudge.verify() signals.successful_purchase.disconnect(signal)
def test_post_passes_kwargs_to_form_is_valid(self): r = lambda: random.randint(100, 200) random_kwargs = { "slug%d" % r(): "foo-%d" % r(), } donation_form = fudge.Fake() donation_form.provides("is_valid").returns(True) get_donation_form = fudge.Fake() get_donation_form.is_callable().returns(donation_form) form_is_valid = fudge.Fake() form_is_valid.expects_call().with_args(donation_form=donation_form, **random_kwargs) view = self.post_view with fudge.patched_context(view, "get_donation_form", get_donation_form): with fudge.patched_context(view, "form_is_valid", form_is_valid): view.post({}, **random_kwargs) fudge.verify()
def test_create_ascii_chars(self): self.playlist = ChirpBroadcast() selector = self.get_selector() self.track = PlaylistTrack( playlist=self.playlist, selector=selector, freeform_artist_name=u'artist', freeform_album_title=u'album', freeform_track_title=u'song') self.track.put() def inspect_request(r): # NOTE: due to URL fetching, you can only raise # AssertionError here self.assertEqual(r.get_full_url(), 'http://__dummylive365service__/cgi-bin/add_song.cgi') qs = dict(cgi.parse_qsl(r.data)) self.assertEqual(qs['member_name'], "dummy_member") self.assertEqual(qs['password'], "dummy_password") self.assertEqual(qs['seconds'], '30') # c should be replaced because latin-1 can't encode that and Live365 likes latin-1 self.assertEqual(qs['title'], 'song') self.assertEqual(qs['album'], 'album') self.assertEqual(qs['artist'], 'artist') return True fake_urlopen = (fudge.Fake('urlopen', expect_call=True) .with_args(arg.passes_test(inspect_request))) fake_response = (fake_urlopen .returns_fake() .has_attr(code='200') .provides('read') .returns("<service response>")) with fudge.patched_context(playlists.tasks.urllib2, "urlopen", fake_urlopen): resp = self.client.post(reverse('playlists.send_track_to_live365'), { 'id': self.track.key() }) fudge.verify()
def check_connection_calls(host_strings, num_calls): # Clear Fudge call stack clear_calls() # Patch connect() with Fake obj set to expect num_calls calls patched_connect = patch_object( 'fabric.network', 'connect', Fake('connect', expect_call=True).times_called(num_calls)) try: # Make new cache object cache = HostConnectionCache() # Connect to all connection strings for host_string in host_strings: # Obtain connection from cache, potentially calling connect() cache[host_string] # Verify expected calls matches up with actual calls verify() finally: # Restore connect() patched_connect.restore() # Clear expectation stack clear_expectations()
def test_form_is_valid_passes_kwargs_to_purchase_failed(self): donation, donation_form = self.random_donation_and_form r = lambda: random.randint(100, 200) random_kwargs = { "slug%d" % r(): "foo-%d" % r(), } view = self.post_view view.confirm = False backends = self.get_backend_stub(successful=False) backend_response = backends.get_backend().purchase() purchase_failed = fudge.Fake() purchase_failed.expects_call().with_args(backend_response, **random_kwargs) with fudge.patched_context(views, "backends", backends): with fudge.patched_context(view, "purchase_failed", purchase_failed): view.form_is_valid(donation_form, **random_kwargs) fudge.verify()
def test_api_instantiates_api_class_with_configured_settings(self): random_login = "******" % random.randint(100, 200) random_key = "some random key %d" % random.randint(100, 200) random_return = "some random return %d" % random.randint(100, 200) settings = fudge.Fake() settings.has_attr(AUTHORIZE={ "LOGIN": random_login, "KEY": random_key, }) api_class = fudge.Fake() # Note that delimiter is included here because authorize's code # can't even keep track of what deliminter it wants to use! (api_class.expects_call().with_args( random_login, random_key, delimiter=arg.any(), is_test=arg.any()).returns(random_return)) fudge.clear_calls() backend = backends.AuthorizeNetBackend(api_class=api_class, settings=settings) result = backend.get_api() self.assertEqual(result, random_return) fudge.verify()
def test_missing_matching_positional_args_is_not_ok(self): # this is awkward to implement so I think it should not be supported db = self.fake db.expects('transaction').with_matching_args("update") db.transaction() fudge.verify()
def test_missing_matching_keyword_args_is_ok(self): db = self.fake db.expects('transaction').with_matching_args(isolation_level="read") db.transaction() fudge.verify()
def test_next_call_then_times_called_is_error(self): self.fake = fudge.Fake().expects("hi").returns( "goodday").next_call().times_called(4) self.fake.hi() self.fake.hi() fudge.verify()
def tearDown(self): fudge.verify() super(TestCase, self).tearDown()
def test_expects_call_shortcut_ok(self): remove = Fake("os.remove").expects_call() remove() fudge.verify() assert isinstance(remove, Fake)
def test_with_non_matching_positional_args(self): db = self.fake db.expects('transaction').with_matching_args('update') db.transaction("insert", isolation_level="lock") fudge.verify()
def test_contains_str(self): db = Fake("db").expects("execute").with_args(arg.contains("table foo")) db.execute("select into table foo;") db.execute("select * from table foo where bar = 1") fudge.verify()
def test_expected_callable(self): login = fudge.Fake('login', expect_call=True).times_called(2) login() fudge.verify()
def test_callable_expectation_with_args(self): fake_setup = (fudge.Fake('setup', expect_call=True).with_args('<db>')) fake_setup('<db>') # was called so verification should pass: fudge.verify()
def test_callable_expectation(self): fake_setup = fudge.Fake('setup', expect_call=True) fake_setup() # was called so verification should pass: fudge.verify()
def test_when_provided_ok(self): self.fake = fudge.Fake().provides("something").times_called(2) self.fake.something() self.fake.something() fudge.verify()
def test_with_non_matching_keyword_args(self): db = self.fake db.expects('transaction').with_matching_args(isolation_level="read") db.transaction("insert", isolation_level="lock") fudge.verify()
def test_contains_fail(self): db = Fake("db").expects("execute").with_args(arg.contains("table foo")) db.execute("select into table notyourmama;") fudge.verify()
def decorated_function(*args, **kwargs): try: result = f(*args, **kwargs) finally: fudge.verify() return result
def test_infinite_path_expectation_is_verified(self): f = fudge.Fake().is_a_stub() f.foo.bar().expects('barfoo').with_args(foo='bar') f.foo.bar().barfoo() fudge.verify()
def test_when_expected_raises_on_too_many_calls(self): self.fake = fudge.Fake().expects("something").times_called(2) self.fake.something() self.fake.something() self.fake.something() # too many fudge.verify()
def test_out_of_order(self): fake = fudge.Fake().remember_order().expects("one").expects("two") fake.two() fake.one() fudge.verify()
def test_when_provided(self): self.fake = fudge.Fake().provides("something").times_called(2) # this should not raise an error because the call was provided not expected fudge.verify()
def test_contains_list(self): db = Fake("db").expects("execute_statements").with_args( arg.contains("select * from foo")) db.execute_statements( ["update foo", "select * from foo", "drop table foo"]) fudge.verify()
def test_callable(self): fake = fudge.Fake().is_callable() fake() # allow the call fudge.verify() # no error
def test_times_called_then_next_call_is_error(self): self.fake = fudge.Fake().expects("hi").times_called(4).next_call() self.fake.hi() self.fake.hi() fudge.verify()
def test_when_expected_ok(self): self.fake = fudge.Fake().expects("something").times_called(2) self.fake.something() self.fake.something() fudge.verify()
def test_callable_ok(self): self.fake = fudge.Fake(callable=True).times_called(2) self.fake() self.fake() fudge.verify()
def test_nocall(self): fake = fudge.Fake() exp = fake.expects('something') fudge.verify()