Example #1
0
    def test_inbox_post_where_result_is_gone_before_callback_is_called(
            self, track_lib_mock, lib_mock):

        tests.create_session()
        sp_track1 = spotify.ffi.new('int *')
        track1 = spotify.Track(sp_track=sp_track1)
        sp_track2 = spotify.ffi.new('int *')
        track2 = spotify.Track(sp_track=sp_track2)
        sp_inbox = spotify.ffi.cast('sp_inbox *', spotify.ffi.new('int *'))
        lib_mock.sp_inbox_post_tracks.return_value = sp_inbox
        callback = mock.Mock()

        result = spotify.InboxPostResult('alice', [track1, track2],
                                         callback=callback)
        complete_event = result.complete_event
        result = None  # noqa
        tests.gc_collect()

        # FIXME The mock keeps the handle/userdata alive, thus the search
        # result is kept alive, and this test doesn't test what it is intended
        # to test.
        inboxpost_complete_cb = lib_mock.sp_inbox_post_tracks.call_args[0][5]
        userdata = lib_mock.sp_inbox_post_tracks.call_args[0][6]
        inboxpost_complete_cb(sp_inbox, userdata)

        complete_event.wait(3)
        self.assertEqual(callback.call_count, 1)
        self.assertEqual(callback.call_args[0][0]._sp_inbox, sp_inbox)
Example #2
0
    def test_browser_is_gone_before_callback_is_called(self, lib_mock):
        tests.create_session()
        sp_artist = spotify.ffi.new('int *')
        artist = spotify.Artist(sp_artist=sp_artist)
        sp_artistbrowse = spotify.ffi.cast('sp_artistbrowse *',
                                           spotify.ffi.new('int *'))
        lib_mock.sp_artistbrowse_create.return_value = sp_artistbrowse
        callback = mock.Mock()

        result = spotify.ArtistBrowser(artist=artist, callback=callback)
        complete_event = result.complete_event
        result = None  # noqa
        tests.gc_collect()

        # FIXME The mock keeps the handle/userdata alive, thus the artist is
        # kept alive, and this test doesn't test what it is intended to test.
        artistbrowse_complete_cb = (
            lib_mock.sp_artistbrowse_create.call_args[0][3])
        userdata = lib_mock.sp_artistbrowse_create.call_args[0][4]
        artistbrowse_complete_cb(sp_artistbrowse, userdata)

        complete_event.wait(3)
        self.assertEqual(callback.call_count, 1)
        self.assertEqual(callback.call_args[0][0]._sp_artistbrowse,
                         sp_artistbrowse)
Example #3
0
    def test_set_starred_fails_if_error(self, lib_mock):
        tests.create_session()
        lib_mock.sp_track_set_starred.return_value = (
            spotify.ErrorType.BAD_API_VERSION)
        sp_track = spotify.ffi.cast('sp_track *', spotify.ffi.new('int *'))
        track = spotify.Track(sp_track=sp_track)

        with self.assertRaises(spotify.Error):
            track.starred = True
Example #4
0
    def assert_fails_if_error(self, lib_mock, func):
        tests.create_session()
        lib_mock.sp_track_error.return_value = (
            spotify.ErrorType.BAD_API_VERSION)
        sp_track = spotify.ffi.new('int *')
        track = spotify.Track(sp_track=sp_track)

        with self.assertRaises(spotify.Error):
            func(track)
Example #5
0
    def test_fail_to_init_raises_error(self, track_lib_mock, lib_mock):
        tests.create_session()
        sp_track1 = spotify.ffi.new('int *')
        track1 = spotify.Track(sp_track=sp_track1)
        sp_track2 = spotify.ffi.new('int *')
        track2 = spotify.Track(sp_track=sp_track2)
        lib_mock.sp_inbox_post_tracks.return_value = spotify.ffi.NULL

        with self.assertRaises(spotify.Error):
            spotify.InboxPostResult('alice', [track1, track2], 'Enjoy!')
Example #6
0
    def test_is_starred_is_none_if_unloaded(self, lib_mock):
        tests.create_session()
        lib_mock.sp_track_error.return_value = spotify.ErrorType.OK
        lib_mock.sp_track_is_loaded.return_value = 0
        sp_track = spotify.ffi.new('int *')
        track = spotify.Track(sp_track=sp_track)

        result = track.starred

        lib_mock.sp_track_is_loaded.assert_called_with(sp_track)
        self.assertIsNone(result)
Example #7
0
    def test_availability_is_none_if_unloaded(self, lib_mock):
        tests.create_session()
        lib_mock.sp_track_error.return_value = spotify.ErrorType.IS_LOADING
        lib_mock.sp_track_is_loaded.return_value = 0
        sp_track = spotify.ffi.new('int *')
        track = spotify.Track(sp_track=sp_track)

        result = track.availability

        lib_mock.sp_track_is_loaded.assert_called_with(sp_track)
        self.assertIsNone(result)
Example #8
0
    def test_repr(self, lib_mock):
        tests.create_session()
        sp_toplistbrowse = spotify.ffi.new('int *')
        lib_mock.sp_toplistbrowse_create.return_value = sp_toplistbrowse
        toplist = spotify.Toplist(
            type=spotify.ToplistType.TRACKS, region='NO')

        result = repr(toplist)

        self.assertEqual(
            result,
            "Toplist(type=<ToplistType.TRACKS: 2>, region=%r, "
            "canonical_username=None)" % 'NO')
Example #9
0
    def test_search_with_callback(self, lib_mock):
        tests.create_session()
        sp_search = spotify.ffi.cast('sp_search *', spotify.ffi.new('int *'))
        lib_mock.sp_search_create.return_value = sp_search
        callback = mock.Mock()

        result = spotify.Search('alice', callback=callback)

        search_complete_cb = lib_mock.sp_search_create.call_args[0][11]
        userdata = lib_mock.sp_search_create.call_args[0][12]
        search_complete_cb(sp_search, userdata)

        result.complete_event.wait(3)
        callback.assert_called_with(result)
Example #10
0
    def test_can_specify_multiple_versions_from_config(self, client_creator):
        config_api_version = '2012-01-01'
        second_config_api_version = '2013-01-01'
        with temporary_file('w') as f:
            del self.environ['FOO_PROFILE']
            self.environ['FOO_CONFIG_FILE'] = f.name
            self.session = create_session(session_vars=self.env_vars)
            f.write('[default]\n')
            f.write('foo_api_versions =\n'
                    '    myservice = %s\n'
                    '    myservice2 = %s\n' % (
                        config_api_version, second_config_api_version)
            )
            f.flush()

            self.session.create_client('myservice', 'us-west-2')
            call_kwargs = client_creator.return_value.\
                create_client.call_args[1]
            self.assertEqual(call_kwargs['api_version'], config_api_version)

            self.session.create_client('myservice2', 'us-west-2')
            call_kwargs = client_creator.return_value.\
                create_client.call_args[1]
            self.assertEqual(
                call_kwargs['api_version'], second_config_api_version)
Example #11
0
    def test_can_specify_multiple_versions_from_config(self, client_creator):
        config_api_version = '2012-01-01'
        second_config_api_version = '2013-01-01'
        with temporary_file('w') as f:
            del self.environ['FOO_PROFILE']
            self.environ['FOO_CONFIG_FILE'] = f.name
            self.session = create_session(session_vars=self.env_vars)
            f.write('[default]\n')
            f.write('foo_api_versions =\n'
                    '    myservice = %s\n'
                    '    myservice2 = %s\n' % (
                        config_api_version, second_config_api_version)
            )
            f.flush()

            self.session.create_client('myservice', 'us-west-2')
            call_kwargs = client_creator.return_value.\
                create_client.call_args[1]
            self.assertEqual(call_kwargs['api_version'], config_api_version)

            self.session.create_client('myservice2', 'us-west-2')
            call_kwargs = client_creator.return_value.\
                create_client.call_args[1]
            self.assertEqual(
                call_kwargs['api_version'], second_config_api_version)
def _get_patched_session():
    with mock.patch('os.environ') as environ:
        environ['AWS_ACCESS_KEY_ID'] = 'access_key'
        environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
        environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
        session = create_session()
    return session
Example #13
0
def test_xml_parsing():
    for dp in ['responses', 'errors']:
        data_path = os.path.join(os.path.dirname(__file__), 'xml')
        data_path = os.path.join(data_path, dp)
        session = create_session()
        xml_files = glob.glob('%s/*.xml' % data_path)
        service_names = set()
        for fn in xml_files:
            service_names.add(os.path.split(fn)[1].split('-')[0])
        for service_name in service_names:
            service = session.get_service(service_name)
            service_xml_files = glob.glob('%s/%s-*.xml' % (data_path,
                                                           service_name))
            for xmlfile in service_xml_files:
                dirname, filename = os.path.split(xmlfile)
                basename = os.path.splitext(filename)[0]
                jsonfile = os.path.join(dirname, basename + '.json')
                sn, opname = basename.split('-', 1)
                opname = opname.split('#')[0]
                operation = service.get_operation(opname)
                r = XmlResponse(session, operation)
                fp = open(xmlfile)
                xml = fp.read()
                fp.close()
                r.parse(xml, 'utf-8')
                save_jsonfile(jsonfile, r)
                fp = open(jsonfile)
                data = json.load(fp)
                fp.close()
                yield check_dicts, xmlfile, r.get_value(), data
def _verify_expected_endpoint_url(region,
                                  bucket,
                                  key,
                                  s3_config,
                                  is_secure=True,
                                  customer_provided_endpoint=None,
                                  expected_url=None,
                                  signature_version=None):
    environ = {}
    with mock.patch('os.environ', environ):
        environ['AWS_ACCESS_KEY_ID'] = 'access_key'
        environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
        environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
        environ['AWS_SHARED_CREDENTIALS_FILE'] = 'no-exist-foo'
        session = create_session()
        session.config_filename = 'no-exist-foo'
        config = Config(signature_version=signature_version, s3=s3_config)
        s3 = session.create_client('s3',
                                   region_name=region,
                                   use_ssl=is_secure,
                                   config=config,
                                   endpoint_url=customer_provided_endpoint)
        with ClientHTTPStubber(s3) as http_stubber:
            http_stubber.add_response()
            s3.put_object(Bucket=bucket, Key=key, Body=b'bar')
            assert_equal(http_stubber.requests[0].url, expected_url)
Example #15
0
 def setUp(self):
     super(EnvVarTest, self).setUp()
     self.environ['AWS_CONFIG_FILE'] = path('aws_config_nocreds')
     self.environ['BOTO_CONFIG'] = ''
     self.environ['AWS_ACCESS_KEY_ID'] = 'foo'
     self.environ['AWS_SECRET_ACCESS_KEY'] = 'bar'
     self.session = create_session(session_vars=TESTENVVARS)
Example #16
0
    def test_inbox_post_tracks(self, track_lib_mock, lib_mock):
        session = tests.create_session()
        sp_track1 = spotify.ffi.new('int *')
        track1 = spotify.Track(sp_track=sp_track1)
        sp_track2 = spotify.ffi.new('int *')
        track2 = spotify.Track(sp_track=sp_track2)
        sp_inbox = spotify.ffi.cast('sp_inbox *', spotify.ffi.new('int *'))
        lib_mock.sp_inbox_post_tracks.return_value = sp_inbox

        result = spotify.InboxPostResult('alice', [track1, track2], '♥')

        lib_mock.sp_inbox_post_tracks.assert_called_with(
            session._sp_session, mock.ANY, mock.ANY, 2, mock.ANY, mock.ANY,
            mock.ANY)
        self.assertEqual(
            spotify.ffi.string(lib_mock.sp_inbox_post_tracks.call_args[0][1]),
            b'alice')
        self.assertIn(sp_track1, lib_mock.sp_inbox_post_tracks.call_args[0][2])
        self.assertIn(sp_track2, lib_mock.sp_inbox_post_tracks.call_args[0][2])
        self.assertEqual(
            spotify.ffi.string(lib_mock.sp_inbox_post_tracks.call_args[0][4]),
            b'\xe2\x99\xa5')
        self.assertIsInstance(result, spotify.InboxPostResult)
        self.assertEqual(result._sp_inbox, sp_inbox)

        self.assertFalse(result.complete_event.is_set())
        inboxpost_complete_cb = lib_mock.sp_inbox_post_tracks.call_args[0][5]
        userdata = lib_mock.sp_inbox_post_tracks.call_args[0][6]
        inboxpost_complete_cb(sp_inbox, userdata)
        self.assertTrue(result.complete_event.wait(3))
Example #17
0
def _verify_expected_endpoint_url(region, bucket, key, s3_config,
                                  is_secure=True,
                                  customer_provided_endpoint=None,
                                  expected_url=None):
    http_response = mock.Mock()
    http_response.status_code = 200
    http_response.headers = {}
    http_response.content = b''
    environ = {}
    with mock.patch('os.environ', environ):
        environ['AWS_ACCESS_KEY_ID'] = 'access_key'
        environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
        environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
        session = create_session()
        session.config_filename = 'no-exist-foo'
        config = None
        if s3_config is not None:
            config = Config(s3=s3_config)
        s3 = session.create_client('s3', region_name=region, use_ssl=is_secure,
                                   config=config,
                                   endpoint_url=customer_provided_endpoint)
        with mock.patch('botocore.endpoint.Session.send') as mock_send:
            mock_send.return_value = http_response
            s3.put_object(Bucket=bucket,
                          Key=key, Body=b'bar')
            request_sent = mock_send.call_args[0][0]
            assert_equal(request_sent.url, expected_url)
Example #18
0
 def setUp(self):
     self.environ = {}
     self.environ_patch = mock.patch('os.environ', self.environ)
     self.environ_patch.start()
     self.environ['FOO_PROFILE'] = 'foo'
     self.environ['FOO_REGION'] = 'us-west-11'
     data_path = os.path.join(os.path.dirname(__file__), 'data')
     self.environ['FOO_DATA_PATH'] = data_path
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'foo_config')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.session = create_session()
     config_chain_builder = ConfigChainFactory(
         session=self.session,
         environ=self.environ,
     )
     config_store = self.session.get_component('config_store')
     config_updates = {
         'profile':
         config_chain_builder.create_config_chain(
             instance_name='profile',
             env_var_names='FOO_PROFILE',
         ),
         'region':
         config_chain_builder.create_config_chain(
             instance_name='region',
             env_var_names='FOO_REGION',
             config_property_names='foo_region',
         ),
         'data_path':
         config_chain_builder.create_config_chain(
             instance_name='data_path',
             env_var_names='FOO_DATA_PATH',
             config_property_names='data_path',
         ),
         'config_file':
         config_chain_builder.create_config_chain(
             instance_name='config_file',
             env_var_names='FOO_CONFIG_FILE',
         ),
         'credentials_file':
         config_chain_builder.create_config_chain(
             instance_name='credentials_file',
             default='/tmp/nowhere',
         ),
         'ca_bundle':
         config_chain_builder.create_config_chain(
             instance_name='ca_bundle',
             env_var_names='FOO_AWS_CA_BUNDLE',
             config_property_names='foo_ca_bundle',
         ),
         'api_versions':
         config_chain_builder.create_config_chain(
             instance_name='api_versions',
             config_property_names='foo_api_versions',
             default={},
         ),
     }
     for name, provider in config_updates.items():
         config_store.set_config_provider(name, provider)
Example #19
0
 def test_profile_does_not_exist_with_default_profile(self):
     session = create_session(session_vars=self.env_vars)
     config = session.get_scoped_config()
     # We should have loaded this properly, and we'll check
     # that foo_access_key which is defined in the config
     # file should be present in the loaded config dict.
     self.assertIn('aws_access_key_id', config)
Example #20
0
 def setUp(self):
     super(EnvVarTest, self).setUp()
     self.environ['AWS_CONFIG_FILE'] = path('aws_config_nocreds')
     self.environ['BOTO_CONFIG'] = ''
     self.environ['AWS_ACCESS_KEY_ID'] = 'foo'
     self.environ['AWS_SECRET_ACCESS_KEY'] = 'bar'
     self.session = create_session(session_vars=TESTENVVARS)
 def test_can_get_session_vars_info_from_default_session(self):
     # This test is to ensure that you can still reach the session_vars_map
     # information from the session and that it has the expected value.
     self.session = create_session()
     self.assertEqual(self.session.session_var_map['region'],
                      ('region', 'AWS_DEFAULT_REGION', None, None))
     self.assertEqual(
         self.session.session_var_map['profile'],
         (None, ['AWS_DEFAULT_PROFILE', 'AWS_PROFILE'], None, None))
     self.assertEqual(self.session.session_var_map['data_path'],
                      ('data_path', 'AWS_DATA_PATH', None, None))
     self.assertEqual(self.session.session_var_map['config_file'],
                      (None, 'AWS_CONFIG_FILE', '~/.aws/config', None))
     self.assertEqual(self.session.session_var_map['ca_bundle'],
                      ('ca_bundle', 'AWS_CA_BUNDLE', None, None))
     self.assertEqual(self.session.session_var_map['api_versions'],
                      ('api_versions', None, {}, None))
     self.assertEqual(
         self.session.session_var_map['credentials_file'],
         (None, 'AWS_SHARED_CREDENTIALS_FILE', '~/.aws/credentials', None))
     self.assertEqual(
         self.session.session_var_map['metadata_service_timeout'],
         ('metadata_service_timeout', 'AWS_METADATA_SERVICE_TIMEOUT', 1,
          int))
     self.assertEqual(
         self.session.session_var_map['metadata_service_num_attempts'],
         ('metadata_service_num_attempts',
          'AWS_METADATA_SERVICE_NUM_ATTEMPTS', 1, int))
     self.assertEqual(self.session.session_var_map['parameter_validation'],
                      ('parameter_validation', None, True, None))
Example #22
0
 def test_emit_first_non_none(self):
     session = create_session(session_vars=self.env_vars)
     session.register('foo', lambda **kwargs: None)
     session.register('foo', lambda **kwargs: 'first')
     session.register('foo', lambda **kwargs: 'second')
     response = session.emit_first_non_none_response('foo')
     self.assertEqual(response, 'first')
Example #23
0
def _verify_expected_endpoint_url(region,
                                  bucket,
                                  key,
                                  s3_config,
                                  is_secure=True,
                                  customer_provided_endpoint=None,
                                  expected_url=None,
                                  signature_version=None):
    http_response = mock.Mock()
    http_response.status_code = 200
    http_response.headers = {}
    http_response.content = b''
    environ = {}
    with mock.patch('os.environ', environ):
        environ['AWS_ACCESS_KEY_ID'] = 'access_key'
        environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
        environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
        session = create_session()
        session.config_filename = 'no-exist-foo'
        config = Config(signature_version=signature_version, s3=s3_config)
        s3 = session.create_client('s3',
                                   region_name=region,
                                   use_ssl=is_secure,
                                   config=config,
                                   endpoint_url=customer_provided_endpoint)
        with mock.patch('botocore.endpoint.Session.send') as mock_send:
            mock_send.return_value = http_response
            s3.put_object(Bucket=bucket, Key=key, Body=b'bar')
            request_sent = mock_send.call_args[0][0]
            assert_equal(request_sent.url, expected_url)
Example #24
0
 def test_emit_first_non_none(self):
     session = create_session(session_vars=self.env_vars)
     session.register('foo', lambda **kwargs: None)
     session.register('foo', lambda **kwargs: 'first')
     session.register('foo', lambda **kwargs: 'second')
     response = session.emit_first_non_none_response('foo')
     self.assertEqual(response, 'first')
Example #25
0
    def test_more(self, lib_mock):
        session = tests.create_session()
        sp_search1 = spotify.ffi.cast('sp_search *', spotify.ffi.new('int *'))
        sp_search2 = spotify.ffi.cast('sp_search *', spotify.ffi.new('int *'))
        lib_mock.sp_search_create.side_effect = [sp_search1, sp_search2]
        lib_mock.sp_search_error.return_value = spotify.ErrorType.OK
        lib_mock.sp_search_query.return_value = spotify.ffi.new(
            'char[]', b'alice')

        result = spotify.Search('alice')

        lib_mock.sp_search_create.assert_called_with(
            session._sp_session, mock.ANY,
            0, 20, 0, 20, 0, 20, 0, 20,
            int(spotify.SearchType.STANDARD), mock.ANY, mock.ANY)
        self.assertEqual(
            spotify.ffi.string(lib_mock.sp_search_create.call_args[0][1]),
            b'alice')
        self.assertEqual(lib_mock.sp_search_add_ref.call_count, 0)
        self.assertIsInstance(result, spotify.Search)
        self.assertEqual(result._sp_search, sp_search1)

        result = result.more(
            track_count=30, album_count=30, artist_count=30, playlist_count=30)

        lib_mock.sp_search_create.assert_called_with(
            session._sp_session, mock.ANY,
            20, 30, 20, 30, 20, 30, 20, 30,
            int(spotify.SearchType.STANDARD), mock.ANY, mock.ANY)
        self.assertEqual(
            spotify.ffi.string(lib_mock.sp_search_create.call_args[0][1]),
            b'alice')
        self.assertEqual(lib_mock.sp_search_add_ref.call_count, 0)
        self.assertIsInstance(result, spotify.Search)
        self.assertEqual(result._sp_search, sp_search2)
Example #26
0
def _get_patched_session():
    with mock.patch('os.environ') as environ:
        environ['AWS_ACCESS_KEY_ID'] = 'access_key'
        environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
        environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
        session = create_session()
    return session
Example #27
0
 def test_profile_does_not_exist_with_default_profile(self):
     session = create_session(session_vars=self.env_vars)
     config = session.get_scoped_config()
     # We should have loaded this properly, and we'll check
     # that foo_access_key which is defined in the config
     # file should be present in the loaded config dict.
     self.assertIn('aws_access_key_id', config)
Example #28
0
def test_xml_parsing():
    for dp in ['responses', 'errors']:
        data_path = os.path.join(os.path.dirname(__file__), 'xml')
        data_path = os.path.join(data_path, dp)
        session = create_session()
        xml_files = glob.glob('%s/*.xml' % data_path)
        service_names = set()
        for fn in xml_files:
            service_names.add(os.path.split(fn)[1].split('-')[0])
        for service_name in service_names:
            service = session.get_service(service_name)
            service_xml_files = glob.glob('%s/%s-*.xml' %
                                          (data_path, service_name))
            for xmlfile in service_xml_files:
                dirname, filename = os.path.split(xmlfile)
                basename = os.path.splitext(filename)[0]
                jsonfile = os.path.join(dirname, basename + '.json')
                sn, opname = basename.split('-', 1)
                opname = opname.split('#')[0]
                operation = service.get_operation(opname)
                r = XmlResponse(session, operation)
                fp = open(xmlfile)
                xml = fp.read()
                fp.close()
                r.parse(xml, 'utf-8')
                save_jsonfile(jsonfile, r)
                fp = open(jsonfile)
                data = json.load(fp)
                fp.close()
                yield check_dicts, xmlfile, r.get_value(), data
Example #29
0
 def test_multiple_env_vars_uses_second_var(self):
     env_vars = {
         'profile': (None, ['BAR_DEFAULT_PROFILE', 'BAR_PROFILE'], None),
     }
     session = create_session(session_vars=env_vars)
     self.environ.pop('BAR_DEFAULT_PROFILE', None)
     self.environ['BAR_PROFILE'] = 'second'
     self.assertEqual(session.get_config_variable('profile'), 'second')
Example #30
0
 def test(self):
     tests.clear_server()
     self.assertEqual(tests.create_dataset().getcode(), 201)
     session_id, res = tests.create_session()
     self.assertEqual(res.getcode(), 200)
     self.assertEqual(tests.upload_data(session_id).getcode(), 200)
     self.assertEqual(tests.test_db(), True)
     self.assertEqual(tests.test_db_form(), True)
Example #31
0
 def test_multiple_env_vars_uses_second_var(self):
     env_vars = {
         'profile': (None, ['BAR_DEFAULT_PROFILE', 'BAR_PROFILE'], None),
     }
     session = create_session(session_vars=env_vars)
     self.environ.pop('BAR_DEFAULT_PROFILE', None)
     self.environ['BAR_PROFILE'] = 'second'
     self.assertEqual(session.get_config_variable('profile'), 'second')
Example #32
0
 def test_supports_multiple_env_vars_for_single_logical_name(self):
     env_vars = {
         'profile': (None, ['BAR_DEFAULT_PROFILE', 'BAR_PROFILE'], None),
     }
     session = create_session(session_vars=env_vars)
     self.environ['BAR_DEFAULT_PROFILE'] = 'first'
     self.environ['BAR_PROFILE'] = 'second'
     self.assertEqual(session.get_config_variable('profile'), 'first')
Example #33
0
 def test_supports_multiple_env_vars_for_single_logical_name(self):
     env_vars = {
         'profile': (None, ['BAR_DEFAULT_PROFILE', 'BAR_PROFILE'], None),
     }
     session = create_session(session_vars=env_vars)
     self.environ['BAR_DEFAULT_PROFILE'] = 'first'
     self.environ['BAR_PROFILE'] = 'second'
     self.assertEqual(session.get_config_variable('profile'), 'first')
Example #34
0
    def test_emitter_can_be_passed_in(self):
        events = HierarchicalEmitter()
        session = create_session(event_hooks=events)
        calls = []
        handler = lambda **kwargs: calls.append(kwargs)
        events.register('foo', handler)

        session.emit('foo')
        self.assertEqual(len(calls), 1)
Example #35
0
    def test_emitter_can_be_passed_in(self):
        events = HierarchicalEmitter()
        session = create_session(event_hooks=events)
        calls = []
        handler = lambda **kwargs: calls.append(kwargs)
        events.register('foo', handler)

        session.emit('foo')
        self.assertEqual(len(calls), 1)
Example #36
0
    def test_create_with_callback(self, lib_mock):
        tests.create_session()
        sp_toplistbrowse = spotify.ffi.cast(
            'sp_toplistbrowse *', spotify.ffi.new('int *'))
        lib_mock.sp_toplistbrowse_create.return_value = sp_toplistbrowse
        callback = mock.Mock()

        result = spotify.Toplist(
            type=spotify.ToplistType.TRACKS, region=spotify.ToplistRegion.USER,
            callback=callback)

        toplistbrowse_complete_cb = (
            lib_mock.sp_toplistbrowse_create.call_args[0][4])
        userdata = lib_mock.sp_toplistbrowse_create.call_args[0][5]
        toplistbrowse_complete_cb(sp_toplistbrowse, userdata)

        result.complete_event.wait(3)
        callback.assert_called_with(result)
Example #37
0
    def test_inbox_post_with_callback(self, track_lib_mock, lib_mock):
        tests.create_session()
        sp_track1 = spotify.ffi.new('int *')
        track1 = spotify.Track(sp_track=sp_track1)
        sp_track2 = spotify.ffi.new('int *')
        track2 = spotify.Track(sp_track=sp_track2)
        sp_inbox = spotify.ffi.cast('sp_inbox *', spotify.ffi.new('int *'))
        lib_mock.sp_inbox_post_tracks.return_value = sp_inbox
        callback = mock.Mock()

        result = spotify.InboxPostResult('alice', [track1, track2],
                                         callback=callback)

        inboxpost_complete_cb = lib_mock.sp_inbox_post_tracks.call_args[0][5]
        userdata = lib_mock.sp_inbox_post_tracks.call_args[0][6]
        inboxpost_complete_cb(sp_inbox, userdata)

        result.complete_event.wait(3)
        callback.assert_called_with(result)
Example #38
0
    def test_set_starred(self, lib_mock):
        session = tests.create_session()
        lib_mock.sp_track_set_starred.return_value = spotify.ErrorType.OK
        sp_track = spotify.ffi.cast('sp_track *', spotify.ffi.new('int *'))
        track = spotify.Track(sp_track=sp_track)

        track.starred = True

        lib_mock.sp_track_set_starred.assert_called_with(
            session._sp_session, mock.ANY, 1, 1)
Example #39
0
 def test_default_profile_is_obeyed(self):
     self.environ['BOTO_DEFAULT_PROFILE'] = 'personal'
     session = create_session()
     credentials = session.get_credentials()
     self.assertEqual(credentials.access_key, 'fie')
     self.assertEqual(credentials.secret_key, 'baz')
     self.assertEqual(credentials.token, 'fiebaz')
     self.assertEqual(credentials.method, 'config')
     self.assertEqual(len(session.available_profiles), 2)
     self.assertIn('default', session.available_profiles)
     self.assertIn('personal', session.available_profiles)
Example #40
0
 def setUp(self):
     super(AlternateCredentialResolverTest, self).setUp()
     self.environ['AWS_CONFIG_FILE'] = path('aws_config')
     self.environ['BOTO_CONFIG'] = ''
     self.session = create_session(session_vars=TESTENVVARS)
     self.small_resolver = credentials.CredentialResolver(
         session=self.session,
         methods=[
             credentials.BotoProvider(),
             credentials.ConfigProvider(session=self.session)
         ])
Example #41
0
 def test_default_profile_is_obeyed(self):
     self.environ['BOTO_DEFAULT_PROFILE'] = 'personal'
     session = create_session()
     credentials = session.get_credentials()
     self.assertEqual(credentials.access_key, 'fie')
     self.assertEqual(credentials.secret_key, 'baz')
     self.assertEqual(credentials.token, 'fiebaz')
     self.assertEqual(credentials.method, 'config')
     self.assertEqual(len(session.available_profiles), 2)
     self.assertIn('default', session.available_profiles)
     self.assertIn('personal', session.available_profiles)
Example #42
0
 def test_type_conversions_occur_when_specified(self):
     # Specify that we can retrieve the var from the
     # FOO_TIMEOUT env var, with a conversion function
     # of int().
     self.env_vars['metadata_service_timeout'] = (
         None, 'FOO_TIMEOUT', None, int)
     # Environment variables are always strings.
     self.environ['FOO_TIMEOUT'] = '10'
     session = create_session(session_vars=self.env_vars)
     # But we should type convert this to a string.
     self.assertEqual(
         session.get_config_variable('metadata_service_timeout'), 10)
Example #43
0
 def setUp(self):
     self.environ = {}
     self.environ_patch = mock.patch('os.environ', self.environ)
     self.environ_patch.start()
     self.environ['FOO_PROFILE'] = 'foo'
     self.environ['FOO_REGION'] = 'us-west-11'
     data_path = os.path.join(os.path.dirname(__file__), 'data')
     self.environ['FOO_DATA_PATH'] = data_path
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'foo_config')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.session = create_session()
     config_chain_builder = ConfigChainFactory(
         session=self.session,
         environ=self.environ,
     )
     config_store = self.session.get_component('config_store')
     config_updates = {
         'profile': config_chain_builder.create_config_chain(
             instance_name='profile',
             env_var_names='FOO_PROFILE',
         ),
         'region': config_chain_builder.create_config_chain(
             instance_name='region',
             env_var_names='FOO_REGION',
             config_property_name='foo_region',
         ),
         'data_path': config_chain_builder.create_config_chain(
             instance_name='data_path',
             env_var_names='FOO_DATA_PATH',
             config_property_name='data_path',
         ),
         'config_file': config_chain_builder.create_config_chain(
             instance_name='config_file',
             env_var_names='FOO_CONFIG_FILE',
         ),
         'credentials_file': config_chain_builder.create_config_chain(
             instance_name='credentials_file',
             default='/tmp/nowhere',
         ),
         'ca_bundle': config_chain_builder.create_config_chain(
             instance_name='ca_bundle',
             env_var_names='FOO_AWS_CA_BUNDLE',
             config_property_name='foo_ca_bundle',
         ),
         'api_versions': config_chain_builder.create_config_chain(
             instance_name='api_versions',
             config_property_name='foo_api_versions',
             default={},
         ),
     }
     for name, provider in config_updates.items():
         config_store.set_config_provider(name, provider)
Example #44
0
 def test_config_loader_delegation(self):
     session = create_session(profile='credfile-profile')
     with temporary_file('w') as f:
         f.write('[credfile-profile]\naws_access_key_id=a\n')
         f.write('aws_secret_access_key=b\n')
         f.flush()
         session.set_config_variable('credentials_file', f.name)
         # Now trying to retrieve the scoped config should pull in
         # values from the shared credentials file.
         self.assertEqual(session.get_scoped_config(),
                          {'aws_access_key_id': 'a',
                           'aws_secret_access_key': 'b'})
Example #45
0
 def setUp(self):
     super(AlternateCredentialResolverTest, self).setUp()
     self.environ['AWS_CONFIG_FILE'] = path('aws_config')
     self.environ['BOTO_CONFIG'] = ''
     self.session = create_session(session_vars=TESTENVVARS)
     self.small_resolver = credentials.CredentialResolver(
         session=self.session,
         methods=[
             credentials.BotoProvider(),
             credentials.ConfigProvider(session=self.session)
         ]
     )
Example #46
0
    def test_create_client_with_ca_bundle_from_config(self, client_creator):
        with temporary_file('w') as f:
            del self.environ['FOO_PROFILE']
            self.environ['FOO_CONFIG_FILE'] = f.name
            self.session = create_session(session_vars=self.env_vars)
            f.write('[default]\n')
            f.write('foo_ca_bundle=config-certs.pem\n')
            f.flush()

            self.session.create_client('ec2', 'us-west-2')
            call_kwargs = client_creator.return_value.\
                create_client.call_args[1]
            self.assertEqual(call_kwargs['verify'], 'config-certs.pem')
Example #47
0
 def test_default_profile_specified_raises_exception(self):
     # If you explicity set the default profile and you don't
     # have that in your config file, an exception is raised.
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'boto_config_empty')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.environ['FOO_PROFILE'] = 'default'
     session = create_session(session_vars=self.env_vars)
     # In this case, even though we specified default, because
     # the boto_config_empty config file does not have a default
     # profile, we should be raising an exception.
     with self.assertRaises(botocore.exceptions.ProfileNotFound):
         session.get_scoped_config()
Example #48
0
 def test_profile(self):
     self.assertEqual(self.session.get_variable('profile'), 'foo')
     self.assertEqual(self.session.get_variable('region'), 'moon-west-1')
     self.session.get_variable('profile') == 'default'
     saved_region = self.environ['FOO_REGION']
     del self.environ['FOO_REGION']
     saved_profile = self.environ['FOO_PROFILE']
     del self.environ['FOO_PROFILE']
     session = create_session(session_vars=self.env_vars)
     self.assertEqual(session.get_variable('profile'), None)
     self.assertEqual(session.get_variable('region'), 'us-west-1')
     self.environ['FOO_REGION'] = saved_region
     self.environ['FOO_PROFILE'] = saved_profile
Example #49
0
 def setUp(self):
     super(TestResetStreamOnRetry, self).setUp()
     self.total_calls = 0
     self.auth = Mock()
     self.session = create_session(include_builtin_handlers=False)
     self.service = Mock()
     self.service.endpoint_prefix = 's3'
     self.service.session = self.session
     self.endpoint = RestEndpoint(
         self.service, 'us-east-1', 'https://s3.amazonaws.com/',
         auth=self.auth)
     self.http_session = Mock()
     self.endpoint.http_session = self.http_session
     self.get_response_patch = patch('botocore.response.get_response')
     self.get_response = self.get_response_patch.start()
     self.retried_on_exception = None
Example #50
0
 def setUp(self):
     self.env_vars = {'profile': (None, 'FOO_PROFILE', None),
                      'region': ('foo_region', 'FOO_REGION', None),
                      'data_path': ('data_path', 'FOO_DATA_PATH', None),
                      'config_file': (None, 'FOO_CONFIG_FILE', None)}
     self.environ = {}
     self.environ_patch = mock.patch('os.environ', self.environ)
     self.environ_patch.start()
     self.environ['FOO_PROFILE'] = 'foo'
     self.environ['FOO_REGION'] = 'moon-west-1'
     data_path = os.path.join(os.path.dirname(__file__), 'data')
     self.environ['FOO_DATA_PATH'] = data_path
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'foo_config')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.session = create_session(session_vars=self.env_vars)
Example #51
0
 def setUp(self):
     super(TestRetryInterface, self).setUp()
     self.total_calls = 0
     self.auth = Mock()
     self.session = create_session(include_builtin_handlers=False)
     self.service = Mock()
     self.service.endpoint_prefix = 'ec2'
     self.service.session = self.session
     self.endpoint = QueryEndpoint(
         self.service, 'us-west-2', 'https://ec2.us-west-2.amazonaws.com/',
         auth=self.auth)
     self.http_session = Mock()
     self.endpoint.http_session = self.http_session
     self.get_response_patch = patch('botocore.response.get_response')
     self.get_response = self.get_response_patch.start()
     self.retried_on_exception = None
Example #52
0
 def setUp(self):
     super(CredentialResolverTest, self).setUp()
     self.environ['AWS_CONFIG_FILE'] = path('aws_config_nocreds')
     self.environ['BOTO_CONFIG'] = ''
     self.environ['AWS_ACCESS_KEY_ID'] = 'foo'
     self.environ['AWS_SECRET_ACCESS_KEY'] = 'bar'
     self.session = create_session(session_vars=TESTENVVARS)
     self.default_resolver = credentials.CredentialResolver(
         session=self.session
     )
     self.small_resolver = credentials.CredentialResolver(
         session=self.session,
         methods=[
             credentials.BotoProvider(),
             credentials.ConfigProvider()
         ]
     )
Example #53
0
    def test_param_api_version_overrides_config_value(self, client_creator):
        config_api_version = '2012-01-01'
        override_api_version = '2014-01-01'
        with temporary_file('w') as f:
            del self.environ['FOO_PROFILE']
            self.environ['FOO_CONFIG_FILE'] = f.name
            self.session = create_session(session_vars=self.env_vars)
            f.write('[default]\n')
            f.write('foo_api_versions =\n'
                    '    myservice = %s\n' % config_api_version)
            f.flush()

            self.session.create_client(
                'myservice', 'us-west-2', api_version=override_api_version)
            call_kwargs = client_creator.return_value.\
                create_client.call_args[1]
            self.assertEqual(call_kwargs['api_version'], override_api_version)
Example #54
0
def _create_s3_client(region, is_secure, endpoint_url, s3_config,
                      signature_version):
    environ = {}
    with mock.patch('os.environ', environ):
        environ['AWS_ACCESS_KEY_ID'] = 'access_key'
        environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
        environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
        environ['AWS_SHARED_CREDENTIALS_FILE'] = 'no-exist-foo'
        session = create_session()
        session.config_filename = 'no-exist-foo'
        config = Config(
            signature_version=signature_version,
            s3=s3_config
        )
        s3 = session.create_client('s3', region_name=region, use_ssl=is_secure,
                                   config=config,
                                   endpoint_url=endpoint_url)
        return s3
def test_xml_parsing():
    for dp in ['responses', 'errors']:
        data_path = os.path.join(os.path.dirname(__file__), 'xml')
        data_path = os.path.join(data_path, dp)
        session = create_session()
        xml_files = glob.glob('%s/*.xml' % data_path)
        service_names = set()
        for fn in xml_files:
            service_names.add(os.path.split(fn)[1].split('-')[0])
        for service_name in service_names:
            service = session.get_service(service_name)
            service_xml_files = glob.glob('%s/%s-*.xml' % (data_path,
                                                           service_name))
            for xmlfile in service_xml_files:
                expected = _get_expected_parsed_result(xmlfile)
                operation_obj = _get_operation_obj(service, xmlfile)
                raw_response_body = _get_raw_response_body(xmlfile)
                yield _test_parsed_response, xmlfile, raw_response_body, operation_obj, expected
Example #56
0
def test_known_endpoints():
    # Verify the actual values from the _endpoints.json file.  While
    # TestEndpointHeuristics verified the generic functionality given any
    # endpoints file, this test actually verifies the _endpoints.json against a
    # fixed list of known endpoints.  This list doesn't need to be kept 100% up
    # to date, but serves as a basis for regressions as the endpoint heuristics
    # logic evolves.
    with mock.patch('os.environ') as environ:
        environ['AWS_ACCESS_KEY_ID'] = 'access_key'
        environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
        environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
        session = create_session()
        resolver = session.get_component('endpoint_resolver')

    for region_name, service_dict in KNOWN_REGIONS.items():
        for service_name, endpoint in service_dict.items():
            endpoint = 'https://%s' % endpoint
            yield (_test_single_service_region, service_name,
                   region_name, endpoint, resolver)
Example #57
0
 def setUp(self):
     self.env_vars = {
         'profile': (None, 'FOO_PROFILE', None, None),
         'region': ('foo_region', 'FOO_REGION', None, None),
         'data_path': ('data_path', 'FOO_DATA_PATH', None, None),
         'config_file': (None, 'FOO_CONFIG_FILE', None, None),
         'credentials_file': (None, None, '/tmp/nowhere', None),
         'ca_bundle': ('foo_ca_bundle', 'FOO_AWS_CA_BUNDLE', None, None),
     }
     self.environ = {}
     self.environ_patch = mock.patch('os.environ', self.environ)
     self.environ_patch.start()
     self.environ['FOO_PROFILE'] = 'foo'
     self.environ['FOO_REGION'] = 'us-west-11'
     data_path = os.path.join(os.path.dirname(__file__), 'data')
     self.environ['FOO_DATA_PATH'] = data_path
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'foo_config')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.session = create_session(session_vars=self.env_vars)
Example #58
0
    def test_create_client_verify_param_overrides_all(self, client_creator):
        with temporary_file('w') as f:
            # Set the ca cert using the config file
            del self.environ['FOO_PROFILE']
            self.environ['FOO_CONFIG_FILE'] = f.name
            self.session = create_session(session_vars=self.env_vars)
            f.write('[default]\n')
            f.write('foo_ca_bundle=config-certs.pem\n')
            f.flush()

            # Set the ca cert with an environment variable
            self.environ['FOO_AWS_CA_BUNDLE'] = 'env-certs.pem'

            # Set the ca cert using the verify parameter
            self.session.create_client(
                'ec2', 'us-west-2', verify='verify-certs.pem')
            call_kwargs = client_creator.return_value.\
                create_client.call_args[1]
            # The verify parameter should override all the other
            # configurations
            self.assertEqual(call_kwargs['verify'], 'verify-certs.pem')
Example #59
0
 def setUp(self):
     self.env_vars = {
         'profile': (None, 'FOO_PROFILE', None),
         'region': ('foo_region', 'FOO_REGION', None),
         'data_path': ('data_path', 'FOO_DATA_PATH', None),
         'config_file': (None, 'FOO_CONFIG_FILE', None),
         'credentials_file': (None, None, '/tmp/nowhere'),
     }
     self.environ = {}
     self.environ_patch = mock.patch('os.environ', self.environ)
     self.environ_patch.start()
     self.environ['FOO_PROFILE'] = 'foo'
     self.environ['FOO_REGION'] = 'moon-west-1'
     data_path = os.path.join(os.path.dirname(__file__), 'data')
     self.environ['FOO_DATA_PATH'] = data_path
     config_path = os.path.join(os.path.dirname(__file__), 'cfg',
                                'foo_config')
     self.environ['FOO_CONFIG_FILE'] = config_path
     self.session = create_session(session_vars=self.env_vars)
     self.loader = botocore.loaders.Loader()
     self.session.register_component('data_loader', self.loader)
Example #60
0
 def test_get_aws_services_in_alphabetical_order(self):
     session = create_session(session_vars=self.env_vars)
     services = session.get_available_services()
     self.assertEqual(sorted(services), services)