class TestGithubPR(unittest.TestCase): def setUp(self): self.github = github3.GitHub() self.session = self.github._session self.configure_session(self.session) self.recorder = Betamax(self.session) with self.recorder.use_cassette('github-pr-initialization'): self.ghpr = GitHubPR(AUTH_TOKEN, 'servo/servo', '', github=self.github) def configure_session(self, session): """Configure a requests session for testing.""" session.headers.update({'Accept-Encoding': 'identity'}) def test_upstream_repo_missing(self): self.ghpr.upstream_user = "******" self.ghpr.repo_name = "arepowhichdoesntexist" with self.recorder.use_cassette('github-pr-upstream-no-repo'): with self.assertRaises(Exception) as context: self.ghpr.upstream_repo() self.assertTrue( b'failed to find github repo' in str(context.exception)) def test_upstream_repo_exists(self): with self.recorder.use_cassette('github-pr-upstream-repo'): upstream = self.ghpr.upstream_repo() assert upstream.full_name == 'servo/servo'
def _set_up_recorder(session, request, cassette_name): recorder = Betamax(session) recorder.use_cassette(cassette_name) recorder.start() request.addfinalizer(recorder.stop) return recorder
class TestBetamax(TestCase): @property def cassette_name(self): cls = getattr(self, '__class__') test = self._testMethodName return '{0}.{1}'.format(cls.__name__, test) def setUp(self): # use self.env.set('var', 'value') and with self.env: ... to use custom envvars self.env = EnvironmentVarGuard() self.client = Client(url=TEST_URL) if TEST_TOKEN: self.client.login(token=TEST_TOKEN) self.recorder = Betamax(session=self.client.session) self.recorder.use_cassette(self.cassette_name) self.recorder.start() self.project = self.client.scope(TEST_SCOPE_NAME) def tearDown(self): self.recorder.stop() def assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs): if six.PY2: return self.assertRaisesRegexp(expected_exception, expected_regex, *args, **kwargs) else: return super(__class__, self).assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)
def tl_searcher(request): tl_searcher = Tracker() session = tl_searcher.session betamax = Betamax(session, cassette_library_dir=config.cassette_library_dir) betamax.use_cassette(request.function.__name__) betamax.start() request.addfinalizer(betamax.stop) return tl_searcher
def wrap_google_with_betamax(): recorder = Betamax(app.config['user_oauth']) # add record='all' to record new session recorder.use_cassette("client_authorized_fail") recorder.start() @app.after_request def unwrap(response): recorder.stop() return response
class TestBetamax(unittest.TestCase): def setUp(self): self.session = Session() self.vcr = Betamax(self.session) def test_initialization_does_alter_the_session(self): for v in self.session.adapters.values(): assert not isinstance(v, BetamaxAdapter) assert isinstance(v, HTTPAdapter) def test_entering_context_alters_adapters(self): with self.vcr: for v in self.session.adapters.values(): assert isinstance(v, BetamaxAdapter) def test_exiting_resets_the_adapters(self): with self.vcr: pass for v in self.session.adapters.values(): assert not isinstance(v, BetamaxAdapter) def test_current_cassette(self): assert self.vcr.current_cassette is None self.vcr.use_cassette('test') assert isinstance(self.vcr.current_cassette, Cassette) def test_use_cassette_returns_cassette_object(self): assert self.vcr.use_cassette('test') is self.vcr def test_register_request_matcher(self): class FakeMatcher(object): name = 'fake' Betamax.register_request_matcher(FakeMatcher) assert 'fake' in matchers.matcher_registry assert isinstance(matchers.matcher_registry['fake'], FakeMatcher) def test_stores_the_session_instance(self): assert self.session is self.vcr.session def test_replaces_all_adapters(self): mount_point = 'fake_protocol://' s = Session() s.mount(mount_point, HTTPAdapter()) with Betamax(s): adapter = s.adapters.get(mount_point) assert adapter is not None assert isinstance(adapter, BetamaxAdapter)
def test_creates_new_cassettes(self): recorder = Betamax(self.session) opts = {'record': 'new_episodes'} cassette_name = 'test_record_new_makes_new_cassettes' with recorder.use_cassette(cassette_name, **opts) as betamax: self.cassette_path = betamax.current_cassette.cassette_path self.session.get('https://httpbin.org/get')
def test_add_host(client): """ There are two ways to add a host, one by specifying the exact IP for the host to use, two by specifying the subnet for the host to be on and allowing DDI to find a free IP on the subnet and assigning it to the host. """ recorder = Betamax(client) with recorder.use_cassette('ddi_add_host'): ip_result = add_host(building='TEST', department='TEST', contact='Test User', ip='172.23.23.4', phone='555-1212', name=ddi_host, session=client, url=ddi_url, comment='Test Comment') subnet_result = add_host(building='TEST', department='TEST', contact='Test User', subnet='172.23.23.0', phone='555-1212', name=ddi_host2, session=client, url=ddi_url, comment='Test Comment') assert isinstance(ip_result, dict) assert jsend.is_success(ip_result) assert isinstance(subnet_result, dict) assert jsend.is_success(subnet_result)
def test_delete_cname(client): recorder = Betamax(client) with recorder.use_cassette('ddi_delete_cname'): result = delete_cname(cname=ddi_cname, session=client, url=ddi_url) assert isinstance(result, dict) assert jsend.is_success(result)
def test_creates_new_cassettes(self): recorder = Betamax(self.session) opts = {"record": "new_episodes"} cassette_name = "test_record_new_makes_new_cassettes" with recorder.use_cassette(cassette_name, **opts) as betamax: self.cassette_path = betamax.current_cassette.cassette_path self.session.get("https://httpbin.org/get")
def test_cname_add(client): runner = CliRunner() result = runner.invoke(cname, ['info', '--help']) assert result.exit_code == 0 assert 'Usage:' in result.output recorder = Betamax(client) obj = {'session': client, 'url': ddi_url, 'json': False} jobj = {'session': client, 'url': ddi_url, 'json': True} with recorder.use_cassette('cli_cname_add'): cli_result = runner.invoke(cname, ['add', ddi_host, ddi_cname], obj=obj) cli_json_result = runner.invoke(cname, ['add', ddi_host, ddi_cname], obj=jobj) failed_cli_result = runner.invoke( cname, ['add', errant_ddi_host, errant_ddi_cname], obj=obj) failed_json_cli_result = runner.invoke( cname, ['add', errant_ddi_host, errant_ddi_cname], obj=jobj) assert cli_result.exit_code == 0 assert f'CNAME: {ddi_cname}' in cli_result.stdout assert cli_json_result.exit_code == 0 assert '"data"' in cli_json_result.stdout assert failed_cli_result.exit_code == 1 assert 'fail' in failed_json_cli_result.stdout
def test_ipv4_info(client): runner = CliRunner() result = runner.invoke(ipv4, ['info', '--help']) assert result.exit_code == 0 assert 'Usage:' in result.output recorder = Betamax(client) obj = {'session': client, 'url': ddi_url, 'json': False} jobj = {'session': client, 'url': ddi_url, 'json': True} with recorder.use_cassette('cli_ipv4_info'): cli_result = runner.invoke(ipv4, ['info', ipv4_address], obj=obj) cli_json_result = runner.invoke(ipv4, ['info', ipv4_address], obj=jobj) failed_cli_result = runner.invoke(ipv4, ['info', errant_ipv4_address], obj=obj) failed_json_cli_result = runner.invoke(ipv4, ['info', errant_ipv4_address], obj=jobj) assert cli_result.exit_code == 0 assert f'Hostname: {ddi_host}' in cli_result.stdout assert cli_json_result.exit_code == 0 assert '"data"' in cli_json_result.stdout assert failed_cli_result.exit_code == 1 assert 'failed' in failed_cli_result.stdout
def test_host_add_ip(client): """ There are two ways to add a host, one by specifying the exact IP for the host to use, two by specifying the subnet for the host to be on and allowing DDI to find a free IP on the subnet and assigning it to the host. """ runner = CliRunner() result = runner.invoke(host, ['info', '--help']) assert result.exit_code == 0 assert 'Usage:' in result.output recorder = Betamax(client) obj = {'session': client, 'url': ddi_url, 'json': False} jobj = {'session': client, 'url': ddi_url, 'json': True} with recorder.use_cassette('cli_host_add_ip'): cli_result = runner.invoke(host, [ 'add', ddi_host, '-b', 'TEST', '-d TEST', '-c', 'Test User', '-i', '172.23.23.4', '-p', '555-1212', '--comment', 'Test Comment"' ], obj=obj) cli_json_result = runner.invoke(host, [ 'add', ddi_host, '-b', 'TEST', '-d TEST', '-c', 'Test User', '-i', '172.23.23.4', '-p', '555-1212', '--comment', 'Test Comment"' ], obj=jobj) assert cli_result.exit_code == 0 assert f'Host: {ddi_host} added' in cli_result.stdout assert cli_json_result.exit_code == 0 assert '"data"' in cli_json_result.stdout
def test_host_delete(client): """ Test the deletion of a host object via the CLI. The keen observer will notice that this test is not in alphabetical order, this is needed due to the fact that you can't get a hosts' information after the host has been deleted :). """ runner = CliRunner() result = runner.invoke(host, ['info', '--help']) assert result.exit_code == 0 assert 'Usage:' in result.output recorder = Betamax(client) obj = {'session': client, 'url': ddi_url, 'json': False} jobj = {'session': client, 'url': ddi_url, 'json': True} with recorder.use_cassette('cli_host_delete'): cli_result = runner.invoke(host, ['delete', ddi_host, '--yes'], obj=obj) cli_json_result = runner.invoke(host, ['delete', ddi_host, '--yes'], obj=jobj) failed_result = runner.invoke(host, ['delete', errant_ddi_host, '--yes'], obj=obj) assert cli_result.exit_code == 0 assert f'Host: {ddi_host} deleted.' in cli_result.stdout assert cli_json_result.exit_code == 0 assert '"data"' in cli_json_result.stdout assert failed_result.exit_code == 1 assert f'Deletion of host: {errant_ddi_host} failed.' in failed_result.stdout
def blueprint(request): token = {"access_token": HEROKU_ACCESS_TOKEN} # avoid "Cannot get OAuth token without an associated user" error _blueprint.session.token = token # wrap session with Betamax recorder = Betamax(_blueprint.session) with recorder.use_cassette(request.node.name): yield _blueprint
def test_get_cname(client): recorder = Betamax(client) with recorder.use_cassette('ddi_get_cname'): result = get_cname_info(cname=ddi_cname, session=client, url=ddi_url) assert isinstance(result, dict) assert jsend.is_success(result) assert result['data']['results'][0]['name'] == ddi_host
class IntegrationTest: """Base class for PRAW integration tests.""" logger = logging.getLogger(__name__) def setup(self): """Setup runs before all test cases.""" self.setup_reddit() self.setup_betamax() def setup_betamax(self): """Configure betamax instance based off of the reddit instance.""" http = self.reddit._core._requestor._http self.recorder = Betamax(http) # Disable response compression in order to see the response bodies in # the betamax cassettes. http.headers["Accept-Encoding"] = "identity" # Require tests to explicitly disable read_only mode. self.reddit.read_only = True def setup_reddit(self): self._session = requests.Session() self.reddit = Reddit( requestor_kwargs={"session": self._session}, client_id=pytest.placeholders.client_id, client_secret=pytest.placeholders.client_secret, password=pytest.placeholders.password, user_agent=pytest.placeholders.user_agent, username=pytest.placeholders.username, ) def use_cassette(self, cassette_name=None, **kwargs): """Use a cassette. The cassette name is dynamically generated. :param cassette_name: (Deprecated) The name to use for the cassette. All names that are not equal to the dynamically generated name will be logged. :param kwargs: All keyword arguments for the main function (``Betamax.use_cassette``). """ dynamic_name = self.get_cassette_name() if cassette_name: self.logger.debug( f"Static cassette name provided by {dynamic_name}. The following name " f"was provided: {cassette_name}") if cassette_name != dynamic_name: self.logger.warning( f"Dynamic cassette name for function {dynamic_name} does not match" f" the provided cassette name: {cassette_name}") return self.recorder.use_cassette(cassette_name or dynamic_name, **kwargs) def get_cassette_name(self) -> str: function_name = inspect.currentframe().f_back.f_back.f_code.co_name return f"{type(self).__name__}.{function_name}"
def test_renew_failure(bad_api_client): recorder = Betamax(bad_api_client.session) with recorder.use_cassette('ComodoAPI_renew_failure', serialize_with='prettyjson'): result = bad_api_client.renew(cert_id=655944) assert isinstance(result, dict) assert 'status' in result assert 'fail' in result['status']
def test_delete_host(client): recorder = Betamax(client) with recorder.use_cassette('ddi_delete_host'): result = delete_host(fqdn=ddi_host, session=client, url=ddi_url) assert isinstance(result, dict) assert jsend.is_success(result) assert 'ret_oid' in result['data']['results'][0]
def test_get_cert_types_failure(self, bad_api_client): recorder = Betamax(bad_api_client.session) with recorder.use_cassette('ComodoAPI_get_cert_types_failure', serialize_with='prettyjson'): result = bad_api_client.get_cert_types() assert isinstance(result, dict) assert 'status' in result assert 'fail' in result['status']
def test_amazon_scrape_avail_false(): session = Session() recorder = Betamax(session, cassette_library_dir="tests/cassettes") with recorder.use_cassette("amazon_scrape_false"): scraper = Amazon() scraper.set_url(AMZ_URLS["invalid"]) scraper.update() assert scraper.get_avail() == False
def test_collect_failure(self, bad_api_client): recorder = Betamax(bad_api_client.session) with recorder.use_cassette('ComodoAPI_collect_failure', serialize_with='prettyjson'): result = bad_api_client.collect(cert_id=123456, format_type='X509 PEM Bundle') assert isinstance(result, dict) assert 'status' in result assert 'fail' in result['status']
def test_revoke(self, api_client): recorder = Betamax(api_client.session) with recorder.use_cassette('ComodoAPI_revoke', serialize_with='prettyjson'): result = api_client.revoke(cert_id=655674, reason='Revoked for testing') assert isinstance(result, dict) assert 'status' in result assert 'success' in result['status']
def test_revoke_failure(self, bad_api_client): recorder = Betamax(bad_api_client.session) with recorder.use_cassette('ComodoAPI_revoke_failure', serialize_with='prettyjson'): result = bad_api_client.revoke(cert_id=123456, reason='Revoked for testing') assert isinstance(result, dict) assert 'status' in result assert 'error' in result['status']
def test_kabum_scrape_avail_true(): session = Session() recorder = Betamax(session, cassette_library_dir="tests/cassettes") with recorder.use_cassette("kabum_scrape_true"): scraper = Kabum() scraper.set_url(KBM_URLS["valid"]) scraper.update() assert scraper.get_avail() == True
def test_amazon_scrape_price(): session = Session() recorder = Betamax(session, cassette_library_dir="tests/cassettes") with recorder.use_cassette("amazon_scrape_price"): scraper = Amazon() scraper.set_url(AMZ_URLS["valid"]) scraper.update() assert isinstance(scraper.get_price(), Decimal)
def test_renew(api_client): recorder = Betamax(api_client.session) with recorder.use_cassette('ComodoAPI_renew', serialize_with='prettyjson'): result = api_client.renew(cert_id=655944) assert isinstance(result, dict) assert 'status' in result assert 'success' in result['status'] assert 'data' in result assert 'certificate_id' in result['data']
def helium_recorder(request): """Generate and start a recorder using a helium.Client.""" cassette_name = '' if request.module is not None: cassette_name += request.module.__name__ + '.' if request.cls is not None: cassette_name += request.cls.__name__ + '.' cassette_name += request.function.__name__ session = helium_commander.Client(base_url=API_URL) session.token_auth(API_TOKEN) recorder = Betamax(session) recorder.use_cassette(cassette_name) recorder.start() request.addfinalizer(recorder.stop) return recorder
def test_get_cert_types(self, api_client): recorder = Betamax(api_client.session) with recorder.use_cassette('ComodoAPI_get_cert_types', serialize_with='prettyjson'): result = api_client.get_cert_types() assert isinstance(result, dict) assert 'status' in result assert 'success' in result['status'] assert 'data' in result assert 'types' in result['data'] assert isinstance(result['data']['types'], list)
def test_submit_failure(self, bad_api_client): recorder = Betamax(bad_api_client.session) with recorder.use_cassette('ComodoAPI_submit_failure', serialize_with='prettyjson'): result = bad_api_client.submit( cert_type_name='Comodo Unified Communications Certificate', csr=csr, term=365, subject_alt_names='test2.colorado.edu') assert isinstance(result, dict) assert 'status' in result assert 'fail' in result['status']
def test_get_subnet_info(client): recorder = Betamax(client) with recorder.use_cassette('ddi_get_subnet'): result = get_subnet_info(subnet=subnet, session=client, url=ddi_url) failed_result = get_subnet_info(subnet=errant_subnet, session=client, url=ddi_url) assert isinstance(result, dict) assert jsend.is_success(result) assert 'subnet_id' in result['data']['results'][0] assert isinstance(failed_result, dict) assert jsend.is_fail(failed_result)
def test_collect(self, api_client): recorder = Betamax(api_client.session) with recorder.use_cassette('ComodoAPI_collect', serialize_with='prettyjson'): result = api_client.collect(cert_id=655043, format_type='X509CO') assert isinstance(result, dict) assert 'status' in result assert 'success' in result['status'] assert 'data' in result assert 'certificate' in result['data'] assert 'certificate_id' in result['data'] assert 'certificate_status' in result['data']
class TestContentService(): def setup(self): session = Session() self.betamax = Betamax(session) self.cs = ContentService(url=URL, apikey=APIKEY, session=session) def test_checkassets(self): # curl -X POST -H "Authorization: deconst ${APIKEY}" \ # http://dockerdev:9000/assets \ # -F aaa=@test/fixtures/assets/foo/aaa.jpg \ # -F bbb=@test/fixtures/assets/bar/bbb.gif with self.betamax.use_cassette('checkassets'): response = self.cs.checkassets({ 'foo/aaa.jpg': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'bar/bbb.gif': '8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225', 'baz/missing.css': 'ffa63583dfa6706b87d284b86b0d693a161e4840aad2c5cf6b5d27c3b9621f7d' }) assert_equal(response, { 'foo/aaa.jpg': '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg', 'bar/bbb.gif': None, 'baz/missing.css': None }) def test_bulkasset(self): with self.betamax.use_cassette('bulkasset'): tarball = io.BytesIO() tf = tarfile.open(fileobj=tarball, mode='w:gz') add_tar_entry(tf, 'bar/bbb.gif') add_tar_entry(tf, 'foo/aaa.jpg') tf.close() response = self.cs.bulkasset(tarball.getvalue()) assert_equal(response, { 'bar/bbb.gif': '/__local_asset__/bbb-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.gif', 'foo/aaa.jpg': '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg' }) def test_checkcontent(self): # curl -X PUT -H "Authorization: deconst ${APIKEY}" \ # -H 'Content-Type: application/json' \ # http://dockerdev:9000/content/https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Fone \ # -d '{"title":"one","body":"one"}' # echo -n '{"body":"one","title":"one"}' | shasum -a 256 # curl -X PUT -H "Authorization: deconst ${APIKEY}" \ # -H 'Content-Type: application/json' \ # http://dockerdev:9000/content/https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Ftwo \ # -d '{"title":"two","body":"two"}' # echo -n '{"body":"two","title":"two"}' | shasum -a 256 with self.betamax.use_cassette('checkcontent'): response = self.cs.checkcontent({ 'https://github.com/org/repo/one': '842d36ad29589a39fc4be06157c5c204a360f98981fc905c0b2a114662172bd8', 'https://github.com/org/repo/two': 'f0e62392fc00c71ba3118c91b97c6f2cbfdcd75e8053fe2d9f029ebfcf6c23fe' }) assert_equal(response, { 'https://github.com/org/repo/one': True, 'https://github.com/org/repo/two': False }) def test_bulkcontent(self): with self.betamax.use_cassette('bulkcontent'): tarball = io.BytesIO() tf = tarfile.open(fileobj=tarball, mode='w:gz') add_tar_entry( tf, 'https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Fone.json', b'{"body":"one","title":"one"}') add_tar_entry( tf, 'https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Ftwo.json', b'{"body":"two","title":"two"}') tf.close() response = self.cs.bulkcontent(tarball.getvalue()) assert_equal(response, { 'accepted': 2, 'failed': 0, 'deleted': 0 })
class TestUSNO_Data: def setup(self): self.lat = 51.0 + 32.0/60.0 self.lng = -22.0/60.0 self.year = 2015 self.usno_data = USNO_Data(self.lat, self.lng) self.recorder = Betamax(self.usno_data.session, default_cassette_options={ 'record_mode': 'once', 'match_requests_on': ['method', 'uri', 'headers'], 'preserve_exact_body_bytes': True }) def test_angle_components(self): (direction, degrees, minutes) = USNO_Data.angle_components(self.lat) assert direction == 1 assert degrees == 51 assert minutes == 32 def test_parameters(self): expected_parameters = { "FFX": "2", "xxy": "2015", "type": "0", "place": "", "xx0": "-1", "xx1": "0", "xx2": "22", "yy0": "1", "yy1": "51", "yy2": "32", "zz0": "1", "zz1": "0", "ZZZ": "END" } self.usno_data.year = 2015 assert self.usno_data.parameters() == expected_parameters def test_as_datetime(self): date = USNO_Data.as_datetime(self.year, 2, 22, '2153') assert date.year == self.year assert date.month == 2 assert date.day == 22 assert date.hour == 21 assert date.minute == 53 assert date.second == 0 assert date.utcoffset() is None def test_day_of_year(self): assert USNO_Data.day_of_year(2015, 2, 22) == 53 assert USNO_Data.day_of_year(2016, 4, 1) == 92 def test_get_data(self): with self.recorder.use_cassette('get_data'): self.usno_data.get_data(self.year) assert self.usno_data.sunrises[-1] == USNO_Data.as_datetime(self.year, 12, 31, '0807') assert self.usno_data.sunsets[-1] == USNO_Data.as_datetime(self.year, 12, 31, '1601') def test_sunrise(self): with self.recorder.use_cassette('get_sunrise'): self.usno_data.get_data(self.year) sunrise = self.usno_data.sunrise(2, 22) assert sunrise.hour == 7 assert sunrise.minute == 2 def test_sunset(self): with self.recorder.use_cassette('get_sunset'): self.usno_data.get_data(self.year) sunset = self.usno_data.sunset(2, 22) assert sunset.hour == 17 assert sunset.minute == 29
class TestSubmit(): def setup(self): self.session = Session() self.betamax = Betamax(self.session) self.cs = ContentService(url=URL, apikey=APIKEY, session=self.session) assert_true(CONFIG.is_valid()) def test_submit_assets(self): with self.betamax.use_cassette('test_submit_assets'): result = submit_assets('test/fixtures/assets', 10000, self.cs) assert_equal(result.uploaded, 2) assert_equal(result.present, 0) aaa, bbb = None, None for asset in result.asset_set.all(): if asset.localpath == 'foo/aaa.jpg': aaa = asset elif asset.localpath == 'bar/bbb.gif': bbb = asset else: assert_true(False, 'Unrecognized asset: {}'.format(asset.localpath)) assert_is_not_none(aaa) assert_is_not_none(bbb) assert_equal(aaa.public_url, '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg') assert_equal(bbb.public_url, '/__local_asset__/bbb-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.gif') def test_submit_assets_batches(self): with self.betamax.use_cassette('test_submit_assets_batches'): result = submit_assets('test/fixtures/batched_assets', 25000, self.cs) assert_equal(result.uploaded, 4) assert_equal(result.batches, 2) assert_equal(result.present, 0) def test_submit_envelopes(self): with self.betamax.use_cassette('test_submit_envelopes'): asset_set = AssetSet() asset_set.append(Asset('foo/aaa.jpg', io.BytesIO())) asset_set.append(Asset('bar/bbb.gif', io.BytesIO())) asset_set.accept_urls({ 'foo/aaa.jpg': '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg', 'bar/bbb.gif': '/__local_asset__/bbb-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.gif' }) result = submit_envelopes( 'test/fixtures/envelopes', asset_set, 'https://github.com/org/repo/', self.cs ) assert_equal(result.uploaded, 3) assert_equal(result.present, 0) assert_equal(result.failed, 0) one, two, three = None, None, None for envelope in result.envelope_set.all(): if envelope.content_id() == 'https://github.com/org/repo/one': one = envelope elif envelope.content_id() == 'https://github.com/org/repo/two': two = envelope elif envelope.content_id() == 'https://github.com/org/repo/three': three = envelope else: assert_true(False, 'Unrecognized envelope: {}'.format(envelope.content_id())) assert_is_not_none(one) assert_is_not_none(two) assert_is_not_none(three) def test_submit_success(self): # Record this one with an empty content service. with self.betamax.use_cassette('test_submit_success'): result = submit(CONFIG, self.session) assert_equal(result.asset_result.uploaded, 2) assert_equal(result.asset_result.present, 0) assert_equal(result.envelope_result.uploaded, 3) assert_equal(result.envelope_result.present, 0) assert_equal(result.envelope_result.deleted, 0) assert_equal(result.envelope_result.failed, 0) assert_equal(result.state, SUCCESS) def test_submit_noop(self): # Record this one with an empty content service. with self.betamax.use_cassette('test_submit_noop'): result = submit(CONFIG, self.session) assert_equal(result.asset_result.uploaded, 0) assert_equal(result.asset_result.present, 2) assert_equal(result.envelope_result.uploaded, 0) assert_equal(result.envelope_result.present, 3) assert_equal(result.envelope_result.deleted, 0) assert_equal(result.envelope_result.failed, 0) assert_equal(result.state, NOOP)