def test_fail_with_invalid_reply_to(self): httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json') # manually confirm r = self.client.post('/[email protected]', headers = {'Referer': 'http://carlitos.net/'}, data={'name': 'carlitos'} ) f = Form.query.first() f.confirm_sent = True f.confirmed = True DB.session.add(f) DB.session.commit() # fail with an invalid '_replyto' httpretty.reset() r = self.client.post('/[email protected]', headers = {'Referer': 'http://carlitos.net/'}, data={'name': 'Real Stock', '_replyto': 'The best offers.'} ) self.assertEqual(False, httpretty.has_request()) self.assertEqual(400, r.status_code) self.assertEqual(0, Form.query.first().counter) # fail with an invalid 'email' httpretty.reset() r = self.client.post('/[email protected]', headers = {'Referer': 'http://carlitos.net/'}, data={'name': 'Real Stock', 'email': 'The best offers.'} ) self.assertEqual(False, httpretty.has_request()) self.assertEqual(400, r.status_code) self.assertEqual(0, Form.query.first().counter)
def test_has_request(): ("httpretty.has_request() correctly detects " "whether or not a request has been made") httpretty.reset() httpretty.has_request().should.be.false with patch('httpretty.httpretty.last_request', return_value=HTTPrettyRequest('')): httpretty.has_request().should.be.true
def test_form_creation_with_a_registered_email(self): httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json') # register user r = self.client.post('/register', data={'email': '*****@*****.**', 'password': '******'} ) # upgrade user manually user = User.query.filter_by(email='*****@*****.**').first() user.upgraded = True DB.session.add(user) DB.session.commit() httpretty.reset() httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json') # create form without providing an url should not send verification email r = self.client.post('/forms', headers={'Accept': 'application/json', 'Content-type': 'application/json'}, data=json.dumps({'email': '*****@*****.**'}) ) self.assertEqual(httpretty.has_request(), False) # create form without a confirmed email should send a verification email r = self.client.post('/forms', headers={'Accept': 'application/json', 'Content-type': 'application/json'}, data=json.dumps({'email': '*****@*****.**', 'url': 'https://www.testsite.com/contact.html'}) ) resp = json.loads(r.data) self.assertEqual(resp['confirmed'], False) self.assertEqual(httpretty.has_request(), True) self.assertIn('Confirm+email', httpretty.last_request().body) self.assertIn('www.testsite.com%2Fcontact.html', httpretty.last_request().body) # manually verify an email email = Email() email.address = '*****@*****.**' email.owner_id = user.id DB.session.add(email) DB.session.commit() # create a form with the verified email address r = self.client.post('/forms', headers={'Accept': 'application/json', 'Content-type': 'application/json'}, data=json.dumps({'email': '*****@*****.**', 'url': 'https://www.testsite.com/about.html'}) ) resp = json.loads(r.data) self.assertEqual(resp['confirmed'], True) self.assertIn('www.testsite.com%2Fcontact.html', httpretty.last_request().body) # same as the last, means no new request was made # should have three created forms in the end self.assertEqual(Form.query.count(), 3)
def test_languages_cache(self): machine = self.get_machine(ApertiumAPYTranslation, True) self.register_apertium_urls() self.assert_translate(machine, 'es') self.assert_translate(machine, 'es', word='Zkouška') self.assertTrue(httpretty.has_request()) httpretty.reset() # New instance should use cached languages machine = ApertiumAPYTranslation() self.assert_translate(machine, 'es') self.assertFalse(httpretty.has_request())
def test_2_loads_response_from_cache(self): """ """ resp = get("http://a.com", cache=self._cache) cached = self._cache["http://a.com"] self.assertFalse(httpretty.has_request()) self.assertEquals(cached.text, "a" * 5) resp = post("http://b.com", data={"b": 2}, cache=self._cache) cached = self._cache[("http://b.com", {}, {"b": 2})] self.assertFalse(httpretty.has_request()) self.assertEquals(cached.text, "b" * 5)
def test_cache(self): machine = self.get_machine(DeepLTranslation, True) httpretty.register_uri( httpretty.POST, 'https://api.deepl.com/v1/translate', body=DEEPL_RESPONSE, ) # Fetch from service self.assert_translate(machine, lang='de', word='Hello') self.assertTrue(httpretty.has_request()) httpretty.reset() # Fetch from cache self.assert_translate(machine, lang='de', word='Hello') self.assertFalse(httpretty.has_request())
def test_add_log_drain(): httpretty.register_uri(httpretty.POST, 'https://api.gigalixir.com/api/apps/fake-app-name/drains', body='{}', content_type='application/json', status=201) runner = CliRunner() result = runner.invoke(gigalixir.cli, ['add_log_drain', '-a', 'fake-app-name', 'fake-url']) assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body.decode()).to.equal('{"url": "fake-url"}')
def test_delete_log_drain(): httpretty.register_uri(httpretty.DELETE, 'https://api.gigalixir.com/api/apps/fake-app-name/drains', body='{}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['delete_log_drain', '-a', 'fake-app-name', "10"]) assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body.decode()).to.equal('{"drain_id": "10"}')
def test_get_releases(): httpretty.register_uri(httpretty.GET, 'https://api.gigalixir.com/api/apps/fake-app-name/releases', body='{"data":[{"sha":"another-fake-sha","version":1,"created_at":"2017-03-29T17:28:29.000+00:00","summary":"fake summary"},{"sha":"fake-sha","version":2,"created_at":"2017-03-29T17:28:28.000+00:00","summary":"fake summary"}]}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['releases', '-a', 'fake-app-name']) assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true assert result.output == """[
def test_reset_password(): httpretty.register_uri(httpretty.POST, 'https://api.gigalixir.com/api/users/reset_password', body='{}', content_type='application/json', status=200) runner = CliRunner() result = runner.invoke(gigalixir.cli, ['set_password', '--token=fake-token'], input="password\n") assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body.decode()).to.equal('{"token": "fake-token", "password": "******"}')
def test_gather_stage(self, mock_super_delete): # prepare harvester = JSONZipBaseHarvester() source_id = 'xyz' source_url = 'http://test.de/ckan.zip' harvest_job = create_harvest_job(self, source_id, source_url) httpretty.HTTPretty.allow_net_connect = False org_id = '1234567890' package1 = { 'id': 'abc', 'name': 'package-1', 'owner_org': org_id} package2 = { 'id': 'efg', 'name': 'package-2', 'owner_org': org_id} # Fake ZIP-File in_memory_zip = StringIO.StringIO() with zipfile.ZipFile(in_memory_zip, 'w') as myzip: myzip.writestr('package1.json', json.dumps(package1, encoding='ascii')) myzip.writestr('package2.json', json.dumps(package2, encoding='ascii')) myzip.writestr('eggs.txt', "Hello world!") response = in_memory_zip.getvalue() httpretty.register_uri(httpretty.GET, source_url, status=200, body=response) # execute harvester.gather_stage(harvest_job) # verify self.assertTrue(httpretty.has_request()) remote_packages = [package1, package2] mock_super_delete.assert_called_once_with(remote_packages, harvest_job)
def step_impl(context): """ :type context: behave.runner.Context """ context.not_found_payload = { "message": "Not Found", "documentation_url": "https://developer.github.com/v3" } context.download_url = '/'.join([ GITHUB_API_URL, 'repos', context.owner_name, context.repo_name, 'contents', context.source_path ]) httpretty.register_uri(httpretty.GET, context.download_url, body=json.dumps(context.not_found_payload), status=404) try: context.res = context.isa_adapter.retrieve( context.source_path, destination=context.destination_path, owner=context.owner_name, repository=context.repo_name) except HTTPError: pass expect(httpretty.has_request()).to.be.true
def test_account_destroy(): httpretty.register_uri(httpretty.DELETE, 'https://api.gigalixir.com/api/users/destroy', body='{}', content_type='application/json', status=200) runner = CliRunner() with runner.isolated_filesystem(): os.environ['HOME'] = '.' with open(netrc_name(), 'w') as f: f.write("""machine api.gigalixir.com \tlogin [email protected] \tpassword fake-api-key machine git.gigalixir.com \tlogin [email protected] \tpassword fake-api-key """) os.chmod(netrc_name(), 0o600) result = runner.invoke( gigalixir.cli, ['account:destroy', '-y', '[email protected]'], input="password\n") assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().parsed_body).to.equal({ "current_password": "******", "email": "*****@*****.**" }) expect(httpretty.last_request().headers.get('Authorization')).to.equal( 'Basic Zm9vQGdpZ2FsaXhpci5jb206ZmFrZS1hcGkta2V5')
def test_execute_error_status(self): httpretty.HTTPretty.allow_net_connect = False httpretty.register_uri( httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/browse.php?cat=131')), status=500, body='<error>Backend Error</error>', match_querystring=True) self.plugin.tracker.setup(helper.real_uid, helper.real_pass, helper.real_usess) self.plugin._execute_login = Mock(return_value=True) self._add_topic("http://www.lostfilm.tv/browse.php?cat=131", u'Подпольная Империя / Broadwalk Empire', 'Broadwalk Empire', '720p', 1, 12) # noinspection PyTypeChecker self.plugin.execute(self.plugin.get_topics(None), EngineMock()) topic1 = self.plugin.get_topic(1) self.assertEqual(topic1['season'], 1) self.assertEqual(topic1['episode'], 12) self.assertEqual(topic1['status'], Status.Error) self.assertTrue(httpretty.has_request())
def test_execute_5(self): httpretty.HTTPretty.allow_net_connect = False httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/browse.php?cat=58')), body=self.read_httpretty_content('browse.php_cat-58(Miracles).html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/nrdr2.php?c=58&s=1&e=13')), body=self.read_httpretty_content('nrd.php_c=58&s=1&e=13.html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://retre.org/?c=58&s=1&e=13') + u"&u=\d+&h=[a-z0-9]+"), body=self.read_httpretty_content('reTre.org_c=58&s=1&e=13.html', encoding='utf-8'), match_querystring=True) self.plugin.tracker.setup(helper.real_uid, helper.real_pass, helper.real_usess) self.plugin._execute_login = Mock(return_value=True) self._add_topic("http://www.lostfilm.tv/browse.php?cat=58", u'Святой Дозо / Miracles', 'Miracles', '720p', 1, 12) # noinspection PyTypeChecker self.plugin.execute(self.plugin.get_topics(None), EngineMock()) topic1 = self.plugin.get_topic(1) self.assertEqual(topic1['season'], 1) self.assertEqual(topic1['episode'], 12) self.assertTrue(httpretty.has_request())
def test_execute_4(self): httpretty.HTTPretty.allow_net_connect = False httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/browse.php?cat=245')), body=self.read_httpretty_content('browse.php_cat-245(Mr. Robot).html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/browse.php?cat=251')), body=self.read_httpretty_content('browse.php_cat-251(Scream).html', encoding='utf-8'), match_querystring=True) self.plugin.tracker.setup(helper.real_uid, helper.real_pass, helper.real_usess) self.plugin._execute_login = Mock(return_value=True) self._add_topic("http://www.lostfilm.tv/browse.php?cat=245", u'Мистер Робот / Mr. Robot', 'Mr. Robot', '720p', 1, 10) self._add_topic("http://www.lostfilm.tv/browse.php?cat=251", u'Крик / Scream', 'Scream', '720p', 1, 10) # noinspection PyTypeChecker self.plugin.execute(self.plugin.get_topics(None), EngineMock()) topic1 = self.plugin.get_topic(1) topic2 = self.plugin.get_topic(2) self.assertEqual(topic1['season'], 1) self.assertEqual(topic1['episode'], 10) self.assertEqual(topic2['season'], 1) self.assertEqual(topic2['episode'], 10) self.assertTrue(httpretty.has_request())
def test_execute(self): httpretty.HTTPretty.allow_net_connect = False file_name = 'Hell.On.Wheels.S05E02.720p.WEB.rus.LostFilm.TV.mp4.torrent' torrent_body = self.read_httpretty_content(file_name, 'rb') # Mr. Robot series httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/browse.php?cat=245')), body=self.read_httpretty_content('browse.php_cat-245(Mr. Robot).html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/nrdr2.php?c=245&s=1&e=09')), body=self.read_httpretty_content('nrd.php_c=245&s=1&e=09.html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/nrdr2.php?c=245&s=1&e=10')), body=self.read_httpretty_content('nrd.php_c=245&s=1&e=10.html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://retre.org/?c=245&s=1&e=09') + u"&u=\d+&h=[a-z0-9]+"), body=self.read_httpretty_content('reTre.org_c=245&s=1&e=09.html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://retre.org/?c=245&s=1&e=10') + u"&u=\d+&h=[a-z0-9]+"), body=self.read_httpretty_content('reTre.org_c=245&s=1&e=10.html', encoding='utf-8'), match_querystring=True) # Scream series httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/browse.php?cat=251')), body=self.read_httpretty_content('browse.php_cat-251(Scream).html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://www.lostfilm.tv/nrdr2.php?c=251&s=1&e=10')), body=self.read_httpretty_content('nrd.php_c=251&s=1&e=10.html', encoding='utf-8'), match_querystring=True) httpretty.register_uri(httpretty.GET, re.compile(re.escape('http://retre.org/?c=251&s=1&e=10') + u"&u=\d+&h=[a-z0-9]+"), body=self.read_httpretty_content('reTre.org_c=251&s=1&e=10.html', encoding='utf-8'), match_querystring=True) # tracktor.in download all files httpretty.register_uri(httpretty.GET, 'http://tracktor.in/td.php', body=torrent_body, adding_headers={'content-disposition': 'attachment; filename=' + file_name}) self.plugin.tracker.setup(helper.real_uid, helper.real_pass, helper.real_usess) self.plugin._execute_login = Mock(return_value=True) self._add_topic("http://www.lostfilm.tv/browse.php?cat=245", u'Мистер Робот / Mr. Robot', 'Mr. Robot', '720p', 1, 8) self._add_topic("http://www.lostfilm.tv/browse.php?cat=251", u'Крик / Scream', 'Scream', '720p', 1, 9) # noinspection PyTypeChecker self.plugin.execute(self.plugin.get_topics(None), EngineMock()) topic1 = self.plugin.get_topic(1) topic2 = self.plugin.get_topic(2) self.assertEqual(topic1['season'], 1) self.assertEqual(topic1['episode'], 10) self.assertEqual(topic2['season'], 1) self.assertEqual(topic2['episode'], 10) self.assertTrue(httpretty.has_request())
def test_create_user_cvc_leading_zero(): httpretty.register_uri(httpretty.GET, 'https://api.gigalixir.com/api/validate_email', body='{}', content_type='application/json') httpretty.register_uri(httpretty.POST, 'https://api.stripe.com/v1/tokens', body='{"id":"fake-stripe-token"}', content_type='application/json') httpretty.register_uri(httpretty.POST, 'https://api.gigalixir.com/api/users', body='{}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, [ 'signup', '[email protected]', '--card_number=4111111111111111', '--card_exp_month=12', '--card_exp_year=34', '-y' ], input="password\n023\n") assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.httpretty.latest_requests[1].body).to.equal( 'card%5Bnumber%5D=4111111111111111&card%5Bexp_year%5D=34&card%5Bcvc%5D=023&card%5Bexp_month%5D=12' ) expect(httpretty.httpretty.latest_requests[2].body).to.equal( '{"stripe_token": "fake-stripe-token", "password": "******", "email": "*****@*****.**"}' )
def test_account(): httpretty.register_uri(httpretty.GET, 'https://api.gigalixir.com/api/users', body='{"data":{}}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['account']) assert result.output == "{}\n\n" assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true
def test_get_apps(): httpretty.register_uri(httpretty.GET, 'https://api.gigalixir.com/api/apps', body='{"data":[{"unique_name":"one","size":0.5,"replicas":1},{"unique_name":"two","size":0.5,"replicas":1},{"unique_name":"three","size":0.5,"replicas":1},{"unique_name":"four","size":0.5,"replicas":1},{"unique_name":"five","size":0.5,"replicas":1}]}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['apps']) assert result.output == """[ { "replicas": 1, "size": 0.5, "unique_name": "one" }, { "replicas": 1, "size": 0.5, "unique_name": "two" }, { "replicas": 1, "size": 0.5, "unique_name": "three" }, { "replicas": 1, "size": 0.5, "unique_name": "four" }, { "replicas": 1, "size": 0.5, "unique_name": "five" } ] """ assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true
def step_impl(context): """ :type context: behave.runner.Context """ file_name = context.source_path.split('/')[-1].replace('.py', '.json') fixture_file_name = '_'.join([context.owner_name, context.repo_name, file_name]).replace('/', '_') encoded_file_url = '/'.join([GITHUB_API_URL, 'repos', context.owner_name, context.repo_name, 'contents', context.source_path]) fixture_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'fixtures', fixture_file_name)) print('Encoded file URL: ', encoded_file_url) with open(fixture_file_path) as json_file: context.text_encoded = json.load(json_file) httpretty.register_uri(httpretty.GET, encoded_file_url, body=json.dumps(context.text_encoded), content_type='text/plain') fixture_file_frags = context.source_path.split('/') fixture_file_path_raw = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', *fixture_file_frags)) download_url = context.text_encoded['download_url'] with open(fixture_file_path_raw) as text_file: context.text_file = text_file.read() httpretty.register_uri(httpretty.GET, download_url, body=context.text_file, content_type='text/plain') branch = context.branch_name if hasattr(context, 'branch_name') else 'master' context.res = context.isa_adapter.retrieve(context.source_path, destination=context.destination_path, owner=context.owner_name, repository=context.repo_name, ref=branch) expect(httpretty.has_request()).to.be.true
def test_delete_permission(): httpretty.register_uri(httpretty.DELETE, 'https://api.gigalixir.com/api/apps/fake-app-name/permissions', body='{}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['delete_permission', 'fake-app-name', '*****@*****.**']) assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body).to.equal('{"email": "*****@*****.**"}')
def test_restart(): httpretty.register_uri(httpretty.PUT, 'https://api.gigalixir.com/api/apps/fake-app-name/restart', body='{"data": "restarted"}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['restart', '-a', 'fake-app-name']) assert result.output == '"restarted"\n\n' assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true
def test_gather_stage(self, mock_super_config): # prepare harvester = JSONDumpBaseCKANHarvester() source_id = 'xyz' source_url = 'http://test.de/ckan-dump' harvest_job = create_harvest_job(self, source_id, source_url) harvester.config = harvest_job.source.config # needed in self._get_content httpretty.HTTPretty.allow_net_connect = False org_id = '1234567890' package1 = { 'id': 'abc', 'name': 'package-1', 'owner_org': org_id} package2 = { 'id': 'efg', 'name': 'package-2', 'owner_org': org_id} response = json.dumps([package1, package2]) httpretty.register_uri(httpretty.GET, source_url, status=200, body=response) harvester.delete_deprecated_datasets = Mock() # execute result = harvester.gather_stage(harvest_job) # verify self.assertEqual(result, [SQL_PACKAGE_ID, SQL_PACKAGE_ID]) mock_super_config.assert_called_once_with(harvester.config) self.assertTrue(httpretty.has_request()) remote_packages = [package1, package2] harvester.delete_deprecated_datasets.assert_called_once_with(remote_packages, harvest_job)
def test_create_config(): httpretty.register_uri(httpretty.POST, 'https://api.gigalixir.com/api/apps/fake-app-name/configs', body='{}', content_type='application/json', status=201) runner = CliRunner() result = runner.invoke(gigalixir.cli, ['set_config', '-a', 'fake-app-name', 'FOO', 'bar']) assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body.decode()).to.equal('{"value": "bar", "key": "FOO"}')
def test_create_free_database(): httpretty.register_uri(httpretty.POST, 'https://api.gigalixir.com/api/apps/fake-app-name/free_databases', body=""" { "data": { "username": "******", "url": "REDACTED", "state": "DELETED", "port": 5432, "password": "******", "id": "REDACTED", "host": "REDACTED", "database": "REDACTED", "app_name": "REDACTED" } } """, content_type='application/json', status=201) runner = CliRunner() result = runner.invoke(gigalixir.cli, ['create_free_database', '-a', 'fake-app-name']) # mind the trailing spaces!! assert result.output == """{ "app_name": "REDACTED", "database": "REDACTED", "host": "REDACTED", "id": "REDACTED", "password": "******", "port": 5432, "state": "DELETED", "url": "REDACTED", "username": "******" } """ assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true
def step_impl(context): """ :type context: behave.runner.Context """ # build up the path to the fixture file (for the encoded data) fixture_file_name = '_'.join([context.owner_name, context.repo_name, context.source_path]).replace('/', '_')\ .replace(' ', '_').replace('.zip', '.json') destination_name = context.source_path.split('/')[-1] fixture_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'fixtures', fixture_file_name)) download_url = '/'.join([GITHUB_API_URL, REPOS, context.owner_name, context.repo_name, CONTENTS, context.source_path]) # get the encoded description with open(fixture_file_path) as json_file: context.zipped_dataset_encoded = json.load(json_file) httpretty.register_uri(httpretty.GET, download_url, body=json.dumps(context.zipped_dataset_encoded)) fixture_file_path_raw = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'fixtures', destination_name)) download_url = context.zipped_dataset_encoded['download_url'] # get the raw zipped file with open(fixture_file_path_raw, 'rb') as zip_file: context.zip_content = zip_file.read() httpretty.register_uri(httpretty.GET, download_url, body=context.zip_content, content_type='application/zip') branch = context.branch_name if hasattr(context, 'branch_name') else 'master' context.res = context.isa_adapter.retrieve(context.source_path, destination=context.destination_path, owner=context.owner_name, repository=context.repo_name, ref=branch) expect(context.res).to.be.true expect(httpretty.has_request()).to.be.true
def test_rollback(): httpretty.register_uri(httpretty.POST, 'https://api.gigalixir.com/api/apps/fake-app-name/releases/1/rollback', body='', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['rollback', '-a', 'fake-app-name', '-r', '1']) assert result.output == '' assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true
def test_delete_config(): httpretty.register_uri(httpretty.DELETE, 'https://api.gigalixir.com/api/apps/fake-app-name/configs', body='{"data": "deleted"}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['delete_config', '-a', 'fake-app-name', 'FOO']) assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body.decode()).to.equal('{"key": "FOO"}')
def test_update_user(): httpretty.register_uri(httpretty.PATCH, 'https://api.gigalixir.com/api/users', body='{}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['change_password', '[email protected]'], input="current_password\nnew_password\n") assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body.decode()).to.equal('{"new_password": "******"}')
def test_create_api_key(): httpretty.register_uri( httpretty.POST, 'https://api.gigalixir.com/api/api_keys', body= '{"data":{"key":"another-fake-api-key","expires_at":"2017-04-28T16:47:09"}}', content_type='application/json', status=201) runner = CliRunner() # Make sure this test does not modify the user's netrc file. with runner.isolated_filesystem(): os.environ['HOME'] = '.' result = runner.invoke(gigalixir.cli, ['reset_api_key', '[email protected]'], input="password\ny\n") assert result.exit_code == 0 with open('.netrc') as f: assert f.read() == """machine api.gigalixir.com \tlogin [email protected] \tpassword another-fake-api-key machine git.gigalixir.com \tlogin [email protected] \tpassword another-fake-api-key machine localhost \tlogin [email protected] \tpassword another-fake-api-key """ expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().headers.headers).to.contain( 'Authorization: Basic Zm9vQGdpZ2FsaXhpci5jb206cGFzc3dvcmQ=\r\n')
def test_update_payment_method_cvc_leading_zero(): httpretty.register_uri(httpretty.POST, 'https://api.stripe.com/v1/tokens', body='{"id":"fake-stripe-token"}', content_type='application/json') httpretty.register_uri(httpretty.PUT, 'https://api.gigalixir.com/api/payment_methods', body='{}', content_type='application/json', status=200) runner = CliRunner() result = runner.invoke(gigalixir.cli, [ 'set_payment_method', '--card_number=4111111111111111', '--card_exp_month=12', '--card_exp_year=34', '--card_cvc=023' ]) assert result.output == '' assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.httpretty.latest_requests[0].parsed_body).to.equal({ 'card[cvc]': ['023'], 'card[exp_month]': ['12'], 'card[exp_year]': ['34'], 'card[number]': ['4111111111111111'] }) # expect(httpretty.httpretty.latest_requests[0].body).to.equal(b'card%5Bnumber%5D=4111111111111111&card%5Bexp_year%5D=34&card%5Bcvc%5D=023&card%5Bexp_month%5D=12') expect(httpretty.last_request().body.decode()).to.equal( '{"stripe_token": "fake-stripe-token"}')
def test_login_escaping(): httpretty.register_uri(httpretty.GET, 'https://api.gigalixir.com/api/login', body='{"data":{"key": "fake-api-key"}}', content_type='application/json') runner = CliRunner() # Make sure this test does not modify the user's netrc file. with runner.isolated_filesystem(): os.environ['HOME'] = '.' result = runner.invoke(gigalixir.cli, ['login', '[email protected]'], input="p:assword\ny\n") assert result.exit_code == 0 with open('.netrc') as f: assert f.read() == """machine api.gigalixir.com \tlogin [email protected] \tpassword fake-api-key machine git.gigalixir.com \tlogin [email protected] \tpassword fake-api-key machine localhost \tlogin [email protected] \tpassword fake-api-key """ expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().headers.headers).to.contain( 'Authorization: Basic Zm9vJTQwZ2lnYWxpeGlyLmNvbTpwJTNBYXNzd29yZA==\r\n' )
def test_get_log_drains(): httpretty.register_uri( httpretty.GET, 'https://api.gigalixir.com/api/apps/fake-app-name/drains', body= '{"data":[{"url":"syslog+tls://foo.papertrailapp.com:12345","token":"fake-token1","id":1},{"url":"https://*****:*****@logs.timber.io/frames","token":"fake-token2","id":2}]}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['log_drains', 'fake-app-name']) print(result.output) assert result.output == """[ { "id": 1, "token": "fake-token1", "url": "syslog+tls://foo.papertrailapp.com:12345" }, { "id": 2, "token": "fake-token2", "url": "https://*****:*****@logs.timber.io/frames" } ] """ assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true
def test_bar_chart_push(): httpretty.register_uri(httpretty.POST, req_ex.DEST_URL, body="OK") gecko_job_bar_chart = GeckoboardService(LeRestResponse(resp_ex.FULL_GROUP_RESP), req_ex.SERVICE_API_KEY, conf_ex.GECKO_BAR_CHART_CONFIG) gecko_job_bar_chart.push({}) assert httpretty.has_request()
def test__number_stat_push(): httpretty.register_uri(httpretty.POST, req_ex.DEST_URL, body="OK") gecko_job_number_stat = GeckoboardService(LeRestResponse(resp_ex.FULL_GROUP_RESP), req_ex.SERVICE_API_KEY, conf_ex.GECKO_NUMBER_STAT_CONFIG) gecko_job_number_stat.push({}) assert httpretty.has_request()
def test_packages_table(self): packages = '[{ "resources": [{"name": "defibrillatoren-in-moers"}]}]' httpretty.register_uri( httpretty.POST, "https://offenedaten.de/api/action/organization_list", body='{"success": true, "result": ["sd"]}', content_type="application/json") httpretty.register_uri( httpretty.POST, "https://offenedaten.de/api/action/organization_show?id=sd", body= '{"success": true, "result": {"display_name": "SD", "created": "", "package_count": 0, "packages": [{ "name": "defibrillatoren-in-moers"}], "extras": [{"key": "city_type", "value": "Stadt"}]}}', content_type="application/json") httpretty.register_uri( httpretty.POST, "https://offenedaten.de/api/action/package_show?id=defibrillatoren-in-moers", body= '{"success": true, "result": {"isopen": true, "resources": [{"format": "xls", "created": "2013-04-19T17:41:57.186024"}, {"format": "xls", "created": "2013-04-19T17:41:57.186024"}, {"format": "XML", "created": "2017-04-19T17:41:57.186024"}]}}', content_type="application/json") od = orgs.OffeneDaten() table = od.create_org_table() od.compute_ranks() od.orgs_table.print_table(max_columns=None) assert table.rows[0]["format_count"] == 2 assert (httpretty.has_request())
def test_get_databases(): httpretty.register_uri(httpretty.GET, 'https://api.gigalixir.com/api/apps/fake-app-name/databases', body=""" { "data": [ { "username": "******", "state": "DELETED", "size": 0.6, "port": 5432, "password": "******", "id": "REDACTED", "host": "REDACTED", "database": "REDACTED", "app_name": "REDACTED" }, { "username": "******", "state": "AVAILABLE", "size": 0.6, "port": 5432, "password": "******", "id": "REDACTED", "host": "REDACTED", "database": "REDACTED", "app_name": "REDACTED" } ] } """, content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['databases', 'fake-app-name']) print result.output assert result.output == """[ { "app_name": "REDACTED", "database": "REDACTED", "host": "REDACTED", "id": "REDACTED", "password": "******", "port": 5432, "size": 0.6, "state": "DELETED", "username": "******" }, { "app_name": "REDACTED", "database": "REDACTED", "host": "REDACTED", "id": "REDACTED", "password": "******", "port": 5432, "size": 0.6, "state": "AVAILABLE", "username": "******" } ] """ assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true
def test_push(): data = "data_to_push" service_obj = DummyService(data, req_ex.SERVICE_API_KEY, {"push_url": req_ex.DEST_URL}) httpretty.register_uri(httpretty.PUT, req_ex.DEST_URL) service_obj.push(data) assert httpretty.has_request() assert httpretty.last_request().body == data
def test_check_url_statistik_sachsen(self): httpretty.HTTPretty.allow_net_connect = False url = 'http://statistik.sachsen.de/dataset/1' httpretty.register_uri(httpretty.HEAD, url, status=200) expectation = 200 assert self.link_checker.validate(url) == expectation self.assertTrue(httpretty.has_request())
def test_scale_database(): httpretty.register_uri(httpretty.PUT, 'https://api.gigalixir.com/api/apps/fake-app-name/databases/fake-database-id', body='{}', content_type='application/json') runner = CliRunner() result = runner.invoke(gigalixir.cli, ['scale_database', '-a', 'fake-app-name', 'fake-database-id', '--size=8']) assert result.output == '' assert result.exit_code == 0 expect(httpretty.has_request()).to.be.true expect(httpretty.last_request().body.decode()).to.equal('{"size": 8.0}')
def test_check_url_404(self): httpretty.HTTPretty.allow_net_connect = False url = 'http://example.com/dataset/1' httpretty.register_uri(httpretty.HEAD, url, status=404) expectation = 404 assert self.link_checker.validate(url) == expectation self.assertTrue(httpretty.has_request())
def test_push(): hosted_graphite_job = HostedGraphiteService(LeRestResponse(resp_ex.FULL_TIMESERIES_RESP), req_ex.SERVICE_API_KEY, conf_ex.SEARCH_HOSTED_GRAPHITE) httpretty.register_uri(httpretty.PUT, req_ex.DEST_URL, body="OK") hosted_graphite_job.push("payload") assert httpretty.has_request()
def test_access_token(self): """ Verify the property retrieves, and caches, an access token from the OAuth 2.0 provider. """ token = self.mock_access_token_response() self.assertEqual(self.site.siteconfiguration.access_token, token) self.assertTrue(httpretty.has_request()) # Verify the value is cached httpretty.disable() self.assertEqual(self.site.siteconfiguration.access_token, token)
def test_line_chart_push(): httpretty.register_uri(httpretty.POST, req_ex.DEST_URL, body="OK") gecko_job_line_chart = GeckoboardService(resp_ex.FULL_TIMESERIES_RESP, req_ex.SERVICE_API_KEY, conf_ex.GECKO_LINE_CHART_CONFIG) gecko_job_line_chart._push({}) assert httpretty.has_request()
def test_list_fields(self): httpretty.register_uri( httpretty.GET, self.url + "/field/bug", content_type="application/json", body=json.dumps(fixtures.fields) ) api = rest.API(self.url) fields = api.list_fields() assert len(fields) > 0 assert httpretty.has_request()
def test_initialization(self): if os.path.isfile(self.localFileAbsPath): os.remove(self.localFileAbsPath) httpretty.register_uri(httpretty.GET, self.remoteURL, body=self.body) sc = ScriptCache.ScriptCache(remoteURL=self.remoteURL,localFile=self.localFile,directory=self.tmpdir) self.assertIsInstance(sc,ScriptCache.ScriptCache) self.assertTrue(httpretty.has_request()) self.assertTrue(os.path.isfile(self.localFileAbsPath)) with open(self.localFileAbsPath) as fd: self.assertEquals(fd.read(),self.body)
def step_impl(context): """ :type context: behave.runner.Context """ httpretty.register_uri(httpretty.GET, auth_url, body=json.dumps([]), content_type='application/json') httpretty.register_uri(httpretty.POST, auth_url, body=json.dumps(auth_res_body), content_type='application/json', status=201) context.isa_adapter = IsaGitHubStorageAdapter(context.username, context.password) expect(httpretty.has_request()).to.be.true
def test_check_url_301(self): httpretty.HTTPretty.allow_net_connect = False url = 'http://example.com/dataset/1' target = 'http://www.example.com/dataset/1' httpretty.register_uri(httpretty.HEAD, target, status=200) httpretty.register_uri(httpretty.HEAD, url, status=301, location=target) expectation = 200 assert self.link_checker.validate(url) == expectation self.assertTrue(httpretty.has_request())
def test_fail_form_without_header(self): httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json') httpretty.reset() no_referer = ajax_headers.copy() del no_referer['Referer'] r = self.client.post('/[email protected]', headers = no_referer, data={'name': 'bob'} ) self.assertEqual(False, httpretty.has_request()) self.assertNotEqual(200, r.status_code)
def test_creation_with_fresh_banner(self): tmpdir = unicode(tempfile.mkdtemp()) tmpfile = '{0}/banner_123.jpg'.format(tmpdir) shutil.copyfile('tests/image1.jpg',tmpfile) tvShow = tvShowSchedule.tvShowSchedule(seriesid=123,bannerDir=tmpdir,autoComplete=True,verbosity=DEBUG_TVSHOWSCHEDULE) tvShow.set(season=1,episode=1,status=0,nextUpdate=datetime.datetime.now(),info={'seriesname':'Lost'}) self.assertIsInstance(tvShow,tvShowSchedule.tvShowSchedule) self.assertTrue(tvShow['info']['banner']) self.assertTrue(os.path.isfile(tmpfile)) self.assertEqual(LogTestCase.md5(tmpfile),LogTestCase.md5('tests/image1.jpg')) self.assertFalse(httpretty.has_request()) os.remove(tmpfile) shutil.rmtree(tmpdir)
def test_existingFile(self): httpretty.register_uri(httpretty.GET, self.remoteURL, body=self.body) with open(self.localFileAbsPath,'w') as fd: fd.write(self.body) time.sleep(1) lastModif = os.path.getmtime(self.localFileAbsPath) sc = ScriptCache.ScriptCache(remoteURL=self.remoteURL,localFile=self.localFile,directory=self.tmpdir) self.assertIsInstance(sc,ScriptCache.ScriptCache) self.assertFalse(httpretty.has_request()) self.assertTrue(os.path.isfile(self.localFileAbsPath)) with open(self.localFileAbsPath) as fd: self.assertEquals(fd.read(),self.body) self.assertEquals(lastModif,os.path.getmtime(self.localFileAbsPath))
def test_creation_with_new_banner_dl(self,mock_getmtime): mock_getmtime.return_value=time.mktime((datetime.datetime.now() - datetime.timedelta(days=45)).timetuple()) tmpdir = unicode(tempfile.mkdtemp()) tmpfile = '{0}/banner_123.jpg'.format(tmpdir) tvShow = tvShowSchedule.tvShowSchedule(seriesid=123,bannerDir=tmpdir,autoComplete=True,verbosity=DEBUG_TVSHOWSCHEDULE) tvShow.set(season=1,episode=1,status=0,nextUpdate=datetime.datetime.now(),info={'seriesname':'Lost'}) self.assertIsInstance(tvShow,tvShowSchedule.tvShowSchedule) self.assertTrue(tvShow['info']['banner']) self.assertTrue(os.path.isfile(tmpfile)) self.assertEqual(LogTestCase.md5(tmpfile),LogTestCase.md5('tests/image.jpg')) self.assertTrue(httpretty.has_request()) os.remove(tmpfile) shutil.rmtree(tmpdir)
def test_outdatedFile(self): httpretty.register_uri(httpretty.GET, self.remoteURL, body=self.body) v45DaysAgo = time.mktime((datetime.datetime.now() - datetime.timedelta(days=45)).timetuple()) getmtimeBackup = os.path.getmtime open(self.localFileAbsPath,'w').close() time.sleep(1) lastModif = os.path.getmtime(self.localFileAbsPath) os.path.getmtime = mock.MagicMock(return_value=v45DaysAgo) sc = ScriptCache.ScriptCache(remoteURL=self.remoteURL,localFile=self.localFile,directory=self.tmpdir) os.path.getmtime = getmtimeBackup self.assertIsInstance(sc,ScriptCache.ScriptCache) self.assertTrue(httpretty.has_request()) self.assertTrue(os.path.isfile(self.localFileAbsPath)) with open(self.localFileAbsPath) as fd: self.assertEquals(fd.read(),self.body)
def step_impl(context): """ :type context: behave.runner.Context """ context.not_found_payload = { "message": "Not Found", "documentation_url": "https://developer.github.com/v3" } context.download_url = '/'.join([GITHUB_API_URL, 'repos', context.owner_name, context.repo_name, 'contents', context.source_path]) httpretty.register_uri(httpretty.GET, context.download_url, body=json.dumps(context.not_found_payload), status=404) try: context.res = context.isa_adapter.retrieve(context.source_path, destination=context.destination_path, owner=context.owner_name, repository=context.repo_name) except HTTPError: pass expect(httpretty.has_request()).to.be.true