def test_get_use_sudo(self): """ get(use_sudo=True) works by copying to a temporary path, downloading it and then removing it at the end """ fake_run = Fake( '_run_command', callable=True, expect_call=True).with_matching_args( fudge_arg.startswith('cp -p "/etc/apache2/apache2.conf" "'), True, True, None).next_call().with_matching_args( fudge_arg.startswith('chown username "'), True, True, None, ).next_call().with_matching_args( fudge_arg.startswith('chmod 400 "'), True, True, None, ).next_call().with_matching_args( fudge_arg.startswith('rm -f "'), True, True, None, ) fake_get = Fake('get', callable=True, expect_call=True) with hide('everything'): with patched_context('fabric.operations', '_run_command', fake_run): with patched_context(SFTPClient, 'get', fake_get): retval = get('/etc/apache2/apache2.conf', self.path(), use_sudo=True) # check that the downloaded file has the same name as the one requested assert retval[0].endswith('apache2.conf')
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_put_use_sudo_temp_dir(self): """ put(use_sudo=True, temp_dir='/tmp/') works by uploading a file to /tmp/ and then moving it to a `remote_path` """ # the sha1 hash is the unique filename of the file being downloaded. sha1(<filename>) fake_run = Fake( '_run_command', callable=True, expect_call=True ).with_matching_args( 'mv "/tmp/7c91837ec0b3570264a325df6b7ef949ee22bc56" "/foobar.txt"', True, True, None, ) fake_put = Fake('put', callable=True, expect_call=True).with_args( fudge_arg.any_value(), '/tmp/7c91837ec0b3570264a325df6b7ef949ee22bc56') local_path = self.mkfile('foobar.txt', "baz") with hide('everything'): with patched_context('fabric.operations', '_run_command', fake_run): with patched_context(SFTPClient, 'put', fake_put): retval = put(local_path, "/", use_sudo=True, temp_dir='/tmp/') # check that the downloaded file has the same name as the one requested assert retval[0].endswith('foobar.txt')
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_sync(): bo = Backend.objects assert bo.count() == 0 TEST_CONF_1 = {"alpha": None, "beta": None} TEST_CONF_2 = {"gamma": None} with patched_context(settings, "INSTALLED_BACKENDS", TEST_CONF_1): bo.sync() # ensure that both backends were created, without enforcing the # order (to avoid breaking later -- key order is undefined.) names = bo.values_list("name", flat=True) assert "alpha" in names assert "beta" in names assert bo.count() == 2 # switch to another configuration. with patched_context(settings, "INSTALLED_BACKENDS", TEST_CONF_2): bo.sync() # check that the new backend was spawed, and the previous # backends were left alone. (they should never be deleted.) assert bo.filter(name="gamma") assert bo.count() == 3
def test_passes_RequestContext_to_template_if_provided_to_render(self): title = "some-random-well-%d" % random.randint(100, 200) type = WellType.objects.create(title=title, slug=title) well = Well.objects.create(type=type) story = generate_random_story() node = Node.objects.create(well=well, content_object=story) expected_path = "wells/%s/%s/%s.html" % (story._meta.app_label, story._meta.object_name.lower(), title) random_return = str(random.randint(1000, 2000)) # doesn't really matter what it is, just that its the result of # RequestContext being invoked mock_context_instance = random.randint(1000, 2000) request = fudge.Fake() RequestContext = fudge.Fake(callable=True) RequestContext.with_args(request).returns(mock_context_instance) render_to_string = fudge.Fake(callable=True) context = {"well": well, "object": story} render_to_string.with_args(expected_path, dictionary=context, context_instance=mock_context_instance).returns( random_return ) with fudge.patched_context(models, "render_to_string", render_to_string): with fudge.patched_context(models, "RequestContext", RequestContext): result = well.render(request) self.assertEqual(result, random_return, msg="Returns what was expected")
def test_adds_test_request_to_recurring_if_in_testing_mode(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.first_name, bill_last_name=u"%s" % donation.donor.last_name, total_occurrences=donation.donation_type.repeat, start_date=start_date, test_request=u"TRUE", ).returns({"messages": { "result_code": { "text_": u"Ok" } }}) fake = fudge.Fake().expects_call().returns(recurring_api) backend = backends.AuthorizeNetBackend(testing=True) 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_passes_RequestContext_to_template_if_provided_to_render(self): title = "some-random-well-%d" % random.randint(100, 200) type = WellType.objects.create(title=title, slug=title) well = Well.objects.create(type=type) story = generate_random_story() node = Node.objects.create(well=well, content_object=story) expected_path = "wells/%s/%s/%s.html" % (story._meta.app_label, story._meta.object_name.lower(), title) random_return = str(random.randint(1000, 2000)) # doesn't really matter what it is, just that its the result of # RequestContext being invoked mock_context_instance = random.randint(1000, 2000) request = fudge.Fake() RequestContext = fudge.Fake(callable=True) RequestContext.with_args(request).returns(mock_context_instance) render_to_string = fudge.Fake(callable=True) context = {"well": well, "object": story} render_to_string.with_args(expected_path, dictionary=context, context_instance=mock_context_instance).returns(random_return) with fudge.patched_context(models, "render_to_string", render_to_string): with fudge.patched_context(models, "RequestContext", RequestContext): result = well.render(request) self.assertEqual(result, random_return, msg="Returns what was expected")
def test_it_doesnt_care_if_no_config_file(self): config_util = ConfigUtil() fake_find_config_file = fudge.Fake("find_config_file").expects_call().returns(None) fake_apply_config_file = fudge.Fake("apply_config_file") with fudge.patched_context(config_util, 'find_config_file', fake_find_config_file): with fudge.patched_context(config_util, 'apply_config_file', fake_apply_config_file): config_util.use_config_file()
def test_it_applies_config_file_if_one_is_found(self): config_util = ConfigUtil() config_file = fudge.Fake("config_file") fake_find_config_file = fudge.Fake("find_config_file").expects_call().returns(config_file) fake_apply_config_file = fudge.Fake("apply_config_file").expects_call().with_args(config_file) with fudge.patched_context(config_util, 'find_config_file', fake_find_config_file): with fudge.patched_context(config_util, 'apply_config_file', fake_apply_config_file): config_util.use_config_file()
def test_adds_initial_if_it_is_not_present(self): random_return = random.randint(10000, 20000) fake = fudge.Fake() fake.has_attr(pk=random_return) args, kwargs = random_args_and_kwargs() fake_settings = generate_fake_settings() fake_qs = fudge.Fake() fake_qs.expects("get").with_args(title="articles").returns(fake) fake_type = generate_fake_type(fake_qs) with fudge.patched_context(admin, "RelatedType", fake_type): with fudge.patched_context(admin, "settings", fake_settings): ret = formfield_for_foreignkey_helper({}, self.db_field, *args, **kwargs) returned_kwargs = ret[1] self.assertTrue("initial" in returned_kwargs) self.assertEqual(returned_kwargs["initial"], random_return)
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_adds_test_request_to_kwargs_if_in_testing_mode(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.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, test_request=u"TRUE", ).returns({ "reason_code": u"1", "reason_text": u"Some random Reason" }) get_api = fudge.Fake().expects_call().returns(api) backend = backends.AuthorizeNetBackend(testing=True) with fudge.patched_context(backend, "get_api", get_api): backend.purchase(donation, donation_form) fudge.verify()
def test_multiline_docstring_indented_correctly(self): """ display_command() should properly indent docstr for old style task methods """ def mytask(arg1): """ This is a multi line docstring. For reals. """ try: with patched_context(fabric.state, 'commands', {'mytask': mytask}): display_command('mytask') except SystemExit: # ugh pass eq_( sys.stdout.getvalue(), """Displaying detailed information for task 'mytask': This is a multi line docstring. For reals. Arguments: arg1 """ )
def test_dispatches_group_create(self): fake_create = fudge.Fake() fake_create.is_callable().expects_call().with_args( self.expected_group_model(), **self.expected_group_payload(is_create=True)) with fudge.patched_context(base.GroupBackend, "created", fake_create): Group.objects.create(name="foobar")
def test_dispatches_user_create(self): fake_create = fudge.Fake() fake_create.is_callable().expects_call().with_args( self.expected_user_model(), **self.expected_user_payload(is_create=True)) with fudge.patched_context(base.UserBackend, "created", fake_create): User.objects.create(username="******")
def test_empty_backend_auto_assigns_higher_priority(self): with fudge.patched_context(Backend, '__init__', fake_backend_init): b1 = Backend.objects.create(name='b1', code_path='b1', regex='.*', priority=5) f = self.form(data=dict(url='www.url.com')) f.is_valid() # trigger cleaning self.assertEqual(f.cleaned_data['backend'], b1)
def test_simple_map_reduce(self): fake_collection = fudge.Fake('Collection').has_attr(__collection__='some_collection') def fake_command(command, callback): expected_command = { "mapreduce": "some_collection", "map": 'map_fn', "reduce": 'reduce_fn', "query": {"my_field": "my_value"}, "out": {'inline': 1}, } results = ({ u'results': [ {u'my_key_1': u'my_data_1'}, {u'my_key_2': u'my_data_2'}, {u'my_key_3': u'my_data_3'}, ], u'timeMillis': 123, u'counts': {u'input': 5, u'output': 3, u'emit': 5, u'reduce': 2}, u'ok': 1, },) self.assertEquals(expected_command, command) callback((results, {'error': None})) fake_session = fudge.Fake('Session') fake_session.is_callable().returns_fake().has_attr(command=fake_command) with fudge.patched_context(manager, 'Session', fake_session): manager_obj = manager.Manager(fake_collection) results = yield gen.Task(manager_obj.map_reduce, "map_fn", "reduce_fn", query={"my_field": "my_value"}) self.assertEquals(3, len(results)) self.assertEquals({u'my_key_1': u'my_data_1'}, results[0]) self.assertEquals({u'my_key_2': u'my_data_2'}, results[1]) self.assertEquals({u'my_key_3': u'my_data_3'}, results[2])
def test_can_be_handler_delete(self): handler = server.TorneiraHandler(self.application_fake, self.request_fake) process_request_fake = fudge.Fake(callable=True).with_args('DELETE', "shouldBeArgs", shouldBeNamedParam="value") with fudge.patched_context(handler, "process_request", process_request_fake): handler.delete("shouldBeArgs", shouldBeNamedParam="value")
def test_returns_none_if_config_query_failed(self): fake_filter = fudge.Fake()\ .expects_call()\ .raises(Exception('MyFakeException')) with fudge.patched_context(Query, 'filter', fake_filter): ret = self.sqlite_db.get_config_value('group1', 'key1') self.assertIsNone(ret)
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_adds_table_version_map_to_the_cache(self): class FakeTable(object): def __init__(self, id_, vid): self.id_ = id_ self.vid = vid tables_no_columns = [ FakeTable('1', 'vid1'), FakeTable('2', 'vid2'), FakeTable('3', 'vid3'), FakeTable('3', 'vid4')] dc = DocCache(self.lib) with fudge.patched_context(self.lib, 'tables_no_columns', tables_no_columns): dc.table_version_map() self.assertIn('t/a/table_version_map', dc._cache) self.assertIn('1', dc._cache['t/a/table_version_map']) self.assertIn('2', dc._cache['t/a/table_version_map']) self.assertIn('3', dc._cache['t/a/table_version_map']) self.assertEquals(dc._cache['t/a/table_version_map']['1'], ['vid1']) self.assertEquals(dc._cache['t/a/table_version_map']['2'], ['vid2']) self.assertEquals(dc._cache['t/a/table_version_map']['3'], ['vid3', 'vid4'])
def test_purchase_returns_false_status_if_successful(self): donation, donation_form = self.random_donation_and_form get_api = self.get_api_stub(successful=False) backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "get_api", get_api): response = backend.purchase(donation, donation_form) self.assertFalse(response["status"])
def test_ignores_OperationalError_while_droping(self): self.sqlite_db.drop() fake_drop = fudge.Fake()\ .expects_call()\ .raises(OperationalError('select 1;', [], 'a')) with fudge.patched_context(self.sqlite_db, 'drop', fake_drop): self.sqlite_db.create_tables()
def test_can_be_process_request_render_500_template(self): settings.DEBUG = False mapper_fake = fudge.Fake().expects("match").with_args("shouldBeUri").returns({"controller":"shouldBeController"}) FakeTorneiraDispatcher = fudge.Fake("TorneiraDispatcher").expects("__init__") FakeTorneiraDispatcher.returns_fake().expects("getMapper").returns(mapper_fake).expects("getController").raises(ValueError()) FakeBaseController = fudge.Fake("BaseController").expects("__init__") FakeBaseController.returns_fake().expects("render_to_template").with_args("/500.html").returns("shouldBeTemplate") patches = [ fudge.patch_object(server, "TorneiraDispatcher", FakeTorneiraDispatcher), fudge.patch_object(server, "BaseController", FakeBaseController), ] write_fake = fudge.Fake(callable=True).with_args("shouldBeTemplate") try: handler = server.TorneiraHandler(self.application_fake, self.request_fake) with fudge.patched_context(handler, "write", write_fake): handler.process_request() finally: for p in patches: p.restore() settings.DEBUG = True
def test_incomplete_track(self): selector = self.get_selector() playlist = ChirpBroadcast() track = PlaylistTrack(playlist=playlist, selector=selector, freeform_artist_name="Squarepusher", freeform_track_title="Port Rhombus") track.put() with fudge.patched_context(playlists.tasks, "_fetch_url", stub_fetch_url): resp = self.client.post(reverse('playlists_add_event'), { 'artist': 'Julio Iglesias', 'album': 'Mi Amore' }) # self.assertNoFormErrors(resp) context = resp.context[0] self.assertEqual( context['form'].errors.as_text(), "* song\n * Please enter the song title.\n* label\n * Please enter the label." ) assert 'Please enter the label.' in resp.content tracks = [t for t in context['playlist_events']] self.assertEquals(tracks[0].artist_name, "Squarepusher") self.assertEquals(tracks[0].track_title, "Port Rhombus")
def test_can_communicate_with_real_authorize_backend_for_recurring(self): onetime_purchase = fudge.Fake().is_callable().returns({"status": True}) class TestableApi(arb.Api): def __init__(self, *args, **kwargs): kwargs["is_test"] = True super(TestableApi, self).__init__(*args, **kwargs) def create_subscription(self, **kwargs): kwargs["test_request"] = u"TRUE" return super(TestableApi, self).create_subscription(**kwargs) donation, donation_form = self.random_donation_and_form donation_form.data["card_number"] = u"4222222222222" # Set to test CC donation.donation_type = self.random_monthly_type donation.amount = 1 backend = backends.AuthorizeNetBackend(recurring_api_class=TestableApi, settings=self.test_settings) with fudge.patched_context(backend, "onetime_purchase", onetime_purchase): result = backend.purchase(donation, donation_form) try: self.assertTrue(result["status"]) except AssertionError: # This is a known issue where Authorize.net randomly returns # a bad response in test mode. Yup, you read that correctly. # A system designed to process your money can't actually figure # out how to run a test server in a reliable wayself. self.assertEqual(result["reason"], u"(TESTMODE) The credit card number is invalid.", msg="Authorize.net really has failed us")
def test_delete_known_track(self): resp = self.client.get(reverse('playlists_landing_page')) context = resp.context[0] tracks = [t for t in context['playlist_events']] self.assertEquals(tracks[0].artist_name, "Steely Dan") def inspect_request(r): self.assertEqual(r.get_full_url(), 'http://testapi/playlist/delete/%s' % self.track.key()) self.assertEqual(r.http_method, 'DELETE') 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.get(reverse('playlists_delete_event', args=[self.track.key()])) self.assertRedirects(resp, reverse('playlists_landing_page')) # simulate the redirect: resp = self.client.get(reverse('playlists_landing_page')) context = resp.context[0] tracks = [t for t in context['playlist_events']] self.assertEquals(tracks, [])
def test_choose_backend_skips_non_matching_regex(self): e = Embed(url=self.url) with fudge.patched_context(Backend, '__init__', fake_backend_init): Backend.objects.create( name='b1', code_path='b1', regex='thiswontmatch', priority=5) self.assertEqual(e.choose_backend(), self.backend)
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_cannot_delete_someone_elses_track(self): other_user = User(email="*****@*****.**") other_user.roles.append(auth.roles.DJ) other_user.put() time.sleep(0.4) other_track = PlaylistTrack( playlist=self.playlist, selector=other_user, freeform_artist_name="Peaches", freeform_track_title="Rock Show",) other_track.put() with fudge.patched_context(playlists.tasks, "_fetch_url", stub_fetch_url): resp = self.client.get(reverse('playlists_delete_event', args=[other_track.key()])) self.assertRedirects(resp, reverse('playlists_landing_page')) # simulate the redirect: resp = self.client.get(reverse('playlists_landing_page')) # should be no change: context = resp.context[0] tracks = [t.artist_name for t in context['playlist_events']] self.assertEquals(tracks, ["Peaches", "Steely Dan"])
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_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 setUp(self): from gevent import monkey with fudge.patched_context( monkey, 'patch_all', fudge.Fake().expects_call()): import womack.namespace self.env = {'socketio': fudge.Fake().has_attr(session={})} self.ns = womack.namespace.Namespace(self.env, 'fake')
def test_geo_near(self): fake_collection = fudge.Fake().has_attr(__collection__='some_collection')\ .expects('create').with_args({'key': 'value'}).returns('should_be_instance') def fake_command(command, callback): expected_command = { 'geoNear': 'some_collection', 'near': 'near_value', 'query': {'tag': 'some_tag'}, 'num': 10, 'maxDistance': 100, 'uniqueDocs': True, 'spherical': False } self.assertEqual(expected_command, command) callback((({'ok': 1, 'results':[{'obj':{'key':'value'}}]},), None)) fake_session = fudge.Fake() fake_session.is_callable().returns_fake().has_attr(command=fake_command) with fudge.patched_context(manager, 'Session', fake_session): manager_object = manager.Manager(fake_collection) manager_object.geo_near('near_value', max_distance=100, unique_docs=True, spherical=False, num=10, query={'tag': 'some_tag'}, callback=self.stop) result = self.wait() self.assertEquals(['should_be_instance'], result)
def test_put_use_sudo(self): """ put(use_sudo=True) works by uploading a the `local_path` to a temporary path and then moving it to a `remote_path` """ fake_run = Fake('_run_command', callable=True, expect_call=True).with_matching_args( fudge_arg.startswith('mv "'), True, True, None, ) fake_put = Fake('put', callable=True, expect_call=True) local_path = self.mkfile('foobar.txt', "baz") with hide('everything'): with patched_context('fabric.operations', '_run_command', fake_run): with patched_context(SFTPClient, 'put', fake_put): retval = put(local_path, "/", use_sudo=True) # check that the downloaded file has the same name as the one requested assert retval[0].endswith('foobar.txt')
def setUp(self): from gevent import monkey with fudge.patched_context( monkey, 'patch_all', fudge.Fake().expects_call()): import womack.server self.srv = womack.server bottle.request.environ = {}
def test_should_look_up_task_name(self): """ should also be able to handle task name strings """ name = 'task1' commands = {name: Fake(callable=True, expect_call=True)} with patched_context(fabric.state, 'commands', commands): execute(name)
def test_from_api(self): data = {'id': 123, 'name': 'Western'} obj = fudge.Fake() mock_set_direct = fudge.Fake().expects_call().with_args(obj, data) with fudge.patched_context(self.translator, 'set_direct_values', mock_set_direct): self.translator.from_api(obj, data)
def test_post_save_name_creation(self): speaker = mommy.prepare(Speaker) mock_update_speaker_name = fudge.Fake( 'Speaker.update_speaker_name_on_creation').expects_call( ).with_args(Speaker, speaker, True) with fudge.patched_context(Speaker, 'update_speaker_name_on_creation', mock_update_speaker_name): speaker.save()
def test_should_look_up_task_name(self): """ should also be able to handle task name strings """ name = 'task1' commands = {name: fake_factory()} with patched_context(fabric.state, 'commands', commands): execute(name)
def test_mark_donation_as_processed(self): donation, donation_form = self.random_donation_and_form self.assertFalse(donation.processed, msg="sanity check") backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "get_api", self.get_api_stub()): backend.purchase(donation, donation_form) self.assertTrue(donation.processed)
def test_returned_dict_contains_response_reason_text_as_reason(self): random_text = "Some Random Text (%d)" % random.randint(1000, 2000) donation, donation_form = self.random_donation_and_form get_api = self.get_api_stub(reason_text=random_text) backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "get_api", get_api): result = backend.purchase(donation, donation_form) self.assertTrue("reason" in result, msg="sanity check") self.assertEqual(result["reason"], random_text)
def test_prompts_for_password_without_good_authentication(): # Fake client whose connect() raises an AuthenticationException on first # call, mimicing behavior when auth is bad or doesn't exist yet f = (Fake('SSHClient').provides('__init__').provides('connect').raises( paramiko.AuthenticationException).next_call().returns(True).provides( 'load_system_host_keys').provides('set_missing_host_key_policy')) with patched_context('paramiko', 'SSHClient', f): # Fake builtin getpass() method which expects to be called once f2 = Fake('getpass', expect_call=True).times_called(1).returns('passwd') with patched_context('getpass', 'getpass', f2): try: # Connect attempt will result in getpass() being called cache = HostConnectionCache() cache['localhost'] verify() finally: clear_expectations()
def test_html_returns_plain_list_if_not_configured_with_profiles(self): bob, alice = generate_random_staff_users() expected = "%s and %s" % (bob.get_full_name(), alice.get_full_name()) article = random_authored_model(SimpleAuthoredModel, bob, alice) settings = fudge.Fake() settings.has_attr(AUTH_PROFILE_MODULE=None) with fudge.patched_context(authors, 'settings', settings): self.assertEqual(article.authors.html(), expected)
def test_process_spawn(self): with fudge.patched_context( subprocess, 'Popen', (fudge.Fake('Popen').is_callable().with_args( self._args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).returns(FakePopen()))): ZombieProxyServer(socket='/tmp/zombie.sock', wait=False)
def test_is_test_is_false_for_recurring_api_class_api_by_default(self): recurring_api_class = fudge.Fake().expects_call().with_args( arg.any(), arg.any(), is_test=False) backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "recurring_api_class", recurring_api_class): backend.get_recurring_api() fudge.verify()
def test_saves_donation_field_once_processed(self): donation, donation_form = self.random_donation_and_form self.assertFalse(donation.processed, msg="sanity check") backend = backends.AuthorizeNetBackend() with fudge.patched_context(backend, "get_api", self.get_api_stub()): backend.purchase(donation, donation_form) d = models.Donation.objects.get(pk=donation.pk) self.assertTrue(d.processed)
def test_raises_error_when_stream_reaise_ioerror(self): """[ConnectionTestCase] - Raises IOError when stream throw error""" fake_stream = fudge.Fake() fake_stream.expects('write').raises(IOError()) with fudge.patched_context(self.conn, '_stream', fake_stream): self.conn.send_message.when.called_with((0, ''), callback=None) \ .throw(IOError)
def test_adds_is_test_to_recurring_api_class_api_if_in_testing_mode(self): recurring_api_class = fudge.Fake().expects_call().with_args( arg.any(), arg.any(), is_test=True) backend = backends.AuthorizeNetBackend(testing=True) with fudge.patched_context(backend, "recurring_api_class", recurring_api_class): backend.get_recurring_api() fudge.verify()
def test_should_set_env_command_to_string_arg(self): """ should set env.command to any string arg, if given """ name = "foo" def command(): eq_(env.command, name) task = Fake(callable=True, expect_call=True).calls(command) with patched_context(fabric.state, 'commands', {name: task}): execute(name)
def test_fastprint_calls_puts(): """ fastprint() is just an alias to puts() """ text = "Some output" fake_puts = Fake('puts', expect_call=True).with_args( text=text, show_prefix=False, end="", flush=True ) with patched_context(utils, 'puts', fake_puts): fastprint(text)