Beispiel #1
0
 def assert_func(self, func, args, expected_ret):
     m = mock.mock_open()
     m.return_value = self.data
     with mock.patch('builtins.open', m, create=True):
         ret = func('/foo/bar', **args)
         m.assert_called_once_with('/foo/bar', 'rb')
         self.assertEqual(expected_ret, ret, str(func))
 def assert_func(self, func, args, expected_ret):
     m = mock.mock_open()
     m.return_value = self.data
     with mock.patch('builtins.open', m, create=True):
         ret = func('/foo/bar', **args)
         m.assert_called_once_with('/foo/bar', 'rb')
         self.assertEqual(expected_ret, ret, str(func))
Beispiel #3
0
    def test_load_application_key_file_defaults_to_a_file_in_cwd(self):
        open_mock = mock.mock_open(read_data='\x04' * 321)
        with mock.patch('spotify.config.open', open_mock, create=True) as m:
            self.config.load_application_key_file()

        m.assert_called_once_with(b'spotify_appkey.key', 'rb')
        self.assertEqual(self.config.application_key, b'\x04' * 321)
 def test_handle(self):
     os.path.getsize = lambda p: self.data["size"]
     os.path.getmtime = lambda p: 123412341234
     m = mock.mock_open()
     m.return_value = io.BytesIO()
     with mock.patch("builtins.open", m, create=True):
         self.task.handle()
     self.assertEqual(1, len(self.task.items_store.get_items_by_id(item_id=self.item.id)))
Beispiel #5
0
    def setUp(self):
        super().setUp()

        self.open = mock.mock_open()
        self.patch('builtins.open', self.open)

        self.shutil = mock.Mock()
        self.patch('retdec.resource.shutil', self.shutil)
Beispiel #6
0
    def setUp(self):
        super().setUp()

        self.open = mock.mock_open()
        self.patch('builtins.open', self.open)

        self.shutil = mock.Mock()
        self.patch('retdec.resource.shutil', self.shutil)
 def test_handle(self):
     os.path.getsize = lambda p: self.data['size']
     os.path.getmtime = lambda p: 123412341234
     m = mock.mock_open()
     m.return_value = io.BytesIO()
     with mock.patch('builtins.open', m, create=True):
         self.task.handle()
     self.assertEqual(1, len(self.task.items_store.get_items_by_id(item_id=self.item.id)))
Beispiel #8
0
    def test_create_resource_calls_load(self):
        self.factory.load_from_definition = mock.Mock()
        with mock.patch('boto3.resources.factory.open',
                        mock.mock_open(read_data='{}'),
                        create=True):
            self.factory.create_class('test', 'Queue')

            self.assertTrue(self.factory.load_from_definition.called,
                            'Class was not loaded from definition')
            self.factory.load_from_definition.assert_called_with(
                'test', 'Queue', {}, {}, None)
Beispiel #9
0
 def test_handle(self, mock_request):
     tmp_path = self.parent_task.drive.config.local_root + '/' + get_tmp_filename('test')
     dest_path = self.parent_task.drive.config.local_root + '/test'
     tmp_path2 = self.task.local_parent_path + get_tmp_filename('test')
     ts = datetime_to_timestamp(self.item.modified_time)
     mock_request.get(self.task.drive.drive_uri + self.task.drive.drive_path + '/items/' + self.item.id + '/content',
                      content=b'1', status_code=codes.ok)
     m = mock.mock_open()
     with mock.patch('builtins.open', m, create=True):
         self.task.handle()
     self.assertEqual([(tmp_path, dest_path)], self.calls_hist['os.rename'])
     self.assertEqual([(dest_path, OS_USER_ID, OS_USER_GID)], self.calls_hist['os.chown'])
     self.assertEqual([(dest_path, (ts, ts))], self.calls_hist['os.utime'])
     self.assertEqual(tmp_path, tmp_path2)
     m.assert_called_once_with(tmp_path2, 'wb')
     handle = m()
     handle.write.assert_called_once_with(b'1')
Beispiel #10
0
class TestRedmineRequest(unittest.TestCase):
    def setUp(self):
        self.url = URL
        self.redmine = Redmine(self.url)
        self.response = mock.Mock()
        patcher_get = mock.patch('requests.get', return_value=self.response)
        patcher_post = mock.patch('requests.post', return_value=self.response)
        patcher_put = mock.patch('requests.put', return_value=self.response)
        patcher_get.start()
        patcher_post.start()
        patcher_put.start()
        self.addCleanup(patcher_get.stop)
        self.addCleanup(patcher_post.stop)
        self.addCleanup(patcher_put.stop)

    def test_successful_response_via_username_password(self):
        self.redmine.username = '******'
        self.redmine.password = '******'
        self.response.status_code = 200
        self.response.json = json_response({'success': True})
        self.assertEqual(
            self.redmine.request('get', self.url)['success'], True)

    def test_successful_response_via_api_key(self):
        self.redmine.key = '123'
        self.response.status_code = 200
        self.response.json = json_response({'success': True})
        self.assertEqual(
            self.redmine.request('get', self.url)['success'], True)

    def test_successful_response_via_put_method(self):
        self.response.status_code = 200
        self.response.content = ''
        self.assertEqual(self.redmine.request('put', self.url), True)

    @mock.patch('redmine.open', mock.mock_open(), create=True)
    def test_successful_file_upload(self):
        self.response.status_code = 201
        self.response.json = json_response({'upload': {'token': '123456'}})
        self.assertEqual(self.redmine.upload('foo'), '123456')

    @mock.patch('redmine.open', mock.mock_open(), create=True)
    def test_successful_file_download(self):
        self.response.status_code = 200
        self.response.iter_content = lambda chunk_size: (
            str(num) for num in range(0, 5))
        self.assertEqual(
            self.redmine.download('http://foo/bar.txt', '/some/path'),
            '/some/path/bar.txt')

    def test_successful_in_memory_file_download(self):
        self.response.status_code = 200
        self.response.iter_content = lambda: (str(num) for num in range(0, 5))
        self.assertEqual(
            ''.join(self.redmine.download('http://foo/bar.txt')()), '01234')

    def test_file_url_exception(self):
        from redmine.exceptions import FileUrlError
        self.response.status_code = 200
        self.assertRaises(
            FileUrlError,
            lambda: self.redmine.download('http://bad_url', '/some/path'))

    def test_file_upload_no_file_exception(self):
        from redmine.exceptions import NoFileError
        self.assertRaises(NoFileError, lambda: self.redmine.upload('foo', ))

    def test_file_upload_not_supported_exception(self):
        from redmine.exceptions import VersionMismatchError
        self.redmine.ver = '1.0.0'
        self.assertRaises(VersionMismatchError,
                          lambda: self.redmine.upload('foo', ))

    def test_conflict_error_exception(self):
        from redmine.exceptions import ConflictError
        self.response.status_code = 409
        self.assertRaises(ConflictError,
                          lambda: self.redmine.request('put', self.url))

    def test_auth_error_exception(self):
        from redmine.exceptions import AuthError
        self.response.status_code = 401
        self.assertRaises(AuthError,
                          lambda: self.redmine.request('get', self.url))

    def test_impersonate_error_exception(self):
        from redmine.exceptions import ImpersonateError
        self.redmine.impersonate = 'not_exists'
        self.response.status_code = 412
        self.assertRaises(ImpersonateError,
                          lambda: self.redmine.request('get', self.url))

    def test_server_error_exception(self):
        from redmine.exceptions import ServerError
        self.response.status_code = 500
        self.assertRaises(ServerError,
                          lambda: self.redmine.request('post', self.url))

    def test_request_entity_too_large_error_exception(self):
        from redmine.exceptions import RequestEntityTooLargeError
        self.response.status_code = 413
        self.assertRaises(RequestEntityTooLargeError,
                          lambda: self.redmine.request('post', self.url))

    def test_validation_error_exception(self):
        from redmine.exceptions import ValidationError
        self.response.status_code = 422
        self.response.json = json_response(
            {'errors': ['foo', 'bar', ['foo', 'bar']]})
        self.assertRaises(ValidationError,
                          lambda: self.redmine.request('post', self.url))

    def test_not_found_error_exception(self):
        from redmine.exceptions import ResourceNotFoundError
        self.response.status_code = 404
        self.assertRaises(ResourceNotFoundError,
                          lambda: self.redmine.request('get', self.url))

    def test_unknown_error_exception(self):
        from redmine.exceptions import UnknownError
        self.response.status_code = 888
        self.assertRaises(UnknownError,
                          lambda: self.redmine.request('get', self.url))

    def test_auth(self):
        self.redmine.username = '******'
        self.redmine.password = '******'
        self.response.status_code = 200
        self.response.json = json_response(
            {'user': {
                'firstname': 'John',
                'lastname': 'Smith',
                'id': 1
            }})
        self.assertEqual(self.redmine.auth().firstname, 'John')
Beispiel #11
0
 def test_handle_error(self):
     m = mock.mock_open()
     m.side_effect = OSError()
     with mock.patch('builtins.open', m, create=True):
         self.task.handle()
class TestResourceManager(unittest.TestCase):
    def setUp(self):
        self.url = URL
        self.redmine = Redmine(self.url)

    def test_supports_project_resource(self):
        self.assertIsInstance(self.redmine.project, ResourceManager)

    def test_supports_issue_resource(self):
        self.assertIsInstance(self.redmine.issue, ResourceManager)

    def test_supports_time_entry_resource(self):
        self.assertIsInstance(self.redmine.time_entry, ResourceManager)

    def test_supports_enumeration_resource(self):
        self.assertIsInstance(self.redmine.enumeration, ResourceManager)

    def test_supports_attachment_resource(self):
        self.assertIsInstance(self.redmine.attachment, ResourceManager)

    def test_supports_issue_journal_resource(self):
        self.assertIsInstance(self.redmine.issue_journal, ResourceManager)

    def test_supports_wiki_page_resource(self):
        self.assertIsInstance(self.redmine.wiki_page, ResourceManager)

    def test_supports_project_membership_resource(self):
        self.assertIsInstance(self.redmine.project_membership, ResourceManager)

    def test_supports_issue_category_resource(self):
        self.assertIsInstance(self.redmine.issue_category, ResourceManager)

    def test_supports_issue_relation_resource(self):
        self.assertIsInstance(self.redmine.issue_relation, ResourceManager)

    def test_supports_version_resource(self):
        self.assertIsInstance(self.redmine.version, ResourceManager)

    def test_supports_user_resource(self):
        self.assertIsInstance(self.redmine.user, ResourceManager)

    def test_supports_group_resource(self):
        self.assertIsInstance(self.redmine.group, ResourceManager)

    def test_supports_role_resource(self):
        self.assertIsInstance(self.redmine.role, ResourceManager)

    def test_supports_news_resource(self):
        self.assertIsInstance(self.redmine.news, ResourceManager)

    def test_supports_issue_status_resource(self):
        self.assertIsInstance(self.redmine.issue_status, ResourceManager)

    def test_supports_tracker_resource(self):
        self.assertIsInstance(self.redmine.tracker, ResourceManager)

    def test_supports_query_resource(self):
        self.assertIsInstance(self.redmine.query, ResourceManager)

    def test_supports_custom_field_resource(self):
        self.assertIsInstance(self.redmine.custom_field, ResourceManager)

    def test_supports_custom_resources(self):
        self.redmine.custom_resource_paths = (__name__, )
        self.assertIsInstance(self.redmine.foo_resource, ResourceManager)

    def test_not_supported_resource_exception(self):
        from redmine.exceptions import ResourceError
        self.assertRaises(ResourceError, lambda: self.redmine.foobar)

    def test_not_supported_version_exception(self):
        from redmine.exceptions import ResourceVersionMismatchError
        self.redmine.ver = '0.0.1'
        self.assertRaises(ResourceVersionMismatchError,
                          lambda: self.redmine.project)

    def test_convert_dict_to_resource_object(self):
        from redmine.resources import Project
        project = self.redmine.project.to_resource({
            'name': 'Foo',
            'identifier': 'foo',
            'id': 1
        })
        self.assertIsInstance(project, Project)
        self.assertEqual(project.name, 'Foo')
        self.assertEqual(project.identifier, 'foo')
        self.assertEqual(project.id, 1)

    def test_convert_dicts_to_resource_set_object(self):
        resourceset = self.redmine.project.to_resource_set([{
            'name': 'Foo',
            'identifier': 'foo',
            'id': 1
        }, {
            'name': 'Bar',
            'identifier': 'bar',
            'id': 2
        }])
        self.assertIsInstance(resourceset, ResourceSet)
        self.assertEqual(resourceset[0].name, 'Foo')
        self.assertEqual(resourceset[0].identifier, 'foo')
        self.assertEqual(resourceset[0].id, 1)
        self.assertEqual(resourceset[1].name, 'Bar')
        self.assertEqual(resourceset[1].identifier, 'bar')
        self.assertEqual(resourceset[1].id, 2)

    @mock.patch('requests.get')
    def test_get_single_resource(self, mock_get):
        mock_get.return_value = response = mock.Mock(status_code=200)
        response.json = json_response(
            {'project': {
                'name': 'Foo',
                'identifier': 'foo',
                'id': 1
            }})
        project = self.redmine.project.get('foo')
        self.assertEqual(project.name, 'Foo')
        self.assertEqual(project.identifier, 'foo')
        self.assertEqual(project.id, 1)

    def test_get_all_resources(self):
        self.assertIsInstance(self.redmine.project.all(), ResourceSet)

    def test_get_filtered_resources(self):
        self.assertIsInstance(self.redmine.issue.filter(project_id='foo'),
                              ResourceSet)

    def test_prepare_params(self):
        from datetime import date, datetime
        time_entries = self.redmine.time_entry.filter(
            from_date=date(2014, 3, 9), to_date=date(2014, 3, 10))
        self.assertEqual(time_entries.manager.params['from'], '2014-03-09')
        self.assertEqual(time_entries.manager.params['to'], '2014-03-10')
        time_entries = self.redmine.time_entry.filter(
            from_date=datetime(2014, 3, 9), to_date=datetime(2014, 3, 10))
        self.assertEqual(time_entries.manager.params['from'],
                         '2014-03-09T00:00:00Z')
        self.assertEqual(time_entries.manager.params['to'],
                         '2014-03-10T00:00:00Z')

    @mock.patch('requests.post')
    def test_create_resource(self, mock_post):
        mock_post.return_value = response = mock.Mock(status_code=201)
        response.json = json_response(
            {'user': {
                'firstname': 'John',
                'lastname': 'Smith',
                'id': 1
            }})
        user = self.redmine.user.create(firstname='John', lastname='Smith')
        self.assertEqual(user.firstname, 'John')
        self.assertEqual(user.lastname, 'Smith')

    @mock.patch('redmine.open', mock.mock_open(), create=True)
    @mock.patch('requests.post')
    def test_create_resource_with_uploads(self, mock_post):
        mock_post.return_value = response = mock.Mock(status_code=201)
        response.json = json_response({
            'upload': {
                'token': '123456'
            },
            'issue': {
                'subject': 'Foo',
                'project_id': 1,
                'id': 1
            }
        })
        issue = self.redmine.issue.create(project_id=1,
                                          subject='Foo',
                                          uploads=[{
                                              'path': 'foo'
                                          }])
        self.assertEqual(issue.project_id, 1)
        self.assertEqual(issue.subject, 'Foo')

    def test_create_empty_resource(self):
        project = self.redmine.project.new()
        defaults = dict((include, None) for include in project._includes)
        defaults.update(
            dict((relation, None) for relation in project._relations))
        self.assertEqual(project._attributes, defaults)

    @mock.patch('requests.put')
    def test_update_resource(self, mock_put):
        mock_put.return_value = mock.Mock(status_code=200, content='')
        manager = self.redmine.wiki_page
        manager.params['project_id'] = 1
        self.assertEqual(manager.update('Foo', title='Bar'), True)
        del manager.params['project_id']

    @mock.patch('redmine.open', mock.mock_open(), create=True)
    @mock.patch('requests.put')
    @mock.patch('requests.post')
    def test_update_resource_with_uploads(self, mock_post, mock_put):
        mock_put.return_value = mock.Mock(status_code=200, content='')
        mock_post.return_value = response = mock.Mock(status_code=201)
        response.json = json_response({'upload': {'token': '123456'}})
        manager = self.redmine.issue
        manager.params['subject'] = 'Foo'
        self.assertEqual(
            manager.update(1, subject='Bar', uploads=[{
                'path': 'foo'
            }]), True)
        del manager.params['subject']

    @mock.patch('requests.delete')
    def test_delete_resource(self, mock_delete):
        mock_delete.return_value = mock.Mock(status_code=200, content='')
        self.assertEqual(self.redmine.group.delete(1), True)

    def test_resource_get_method_unsupported_exception(self):
        self.assertRaises(ResourceBadMethodError,
                          lambda: self.redmine.enumeration.get('foo'))

    def test_resource_all_method_unsupported_exception(self):
        self.assertRaises(ResourceBadMethodError,
                          lambda: self.redmine.attachment.all())

    def test_resource_filter_method_unsupported_exception(self):
        self.assertRaises(ResourceBadMethodError,
                          lambda: self.redmine.project.filter())

    def test_resource_create_method_unsupported_exception(self):
        self.assertRaises(ResourceBadMethodError,
                          lambda: self.redmine.query.create())

    def test_resource_update_method_unsupported_exception(self):
        self.assertRaises(ResourceBadMethodError,
                          lambda: self.redmine.query.update(1))

    def test_resource_delete_method_unsupported_exception(self):
        self.assertRaises(ResourceBadMethodError,
                          lambda: self.redmine.query.delete(1))

    def test_filter_no_filters_exception(self):
        from redmine.exceptions import ResourceNoFiltersProvidedError
        self.assertRaises(ResourceNoFiltersProvidedError,
                          lambda: self.redmine.issue.filter())

    def test_filter_unknown_filters_exception(self):
        from redmine.exceptions import ResourceFilterError
        self.assertRaises(ResourceFilterError,
                          lambda: self.redmine.version.filter(foo='bar'))

    def test_create_no_fields_exception(self):
        from redmine.exceptions import ResourceNoFieldsProvidedError
        self.assertRaises(ResourceNoFieldsProvidedError,
                          lambda: self.redmine.user.create())

    def test_update_no_fields_exception(self):
        from redmine.exceptions import ResourceNoFieldsProvidedError
        self.assertRaises(ResourceNoFieldsProvidedError,
                          lambda: self.redmine.project.update(1))

    def test_get_validation_exception(self):
        self.assertRaises(ValidationError,
                          lambda: self.redmine.wiki_page.get('foo'))

    def test_create_validation_exception(self):
        self.assertRaises(
            ValidationError,
            lambda: self.redmine.issue_category.create(foo='bar'))

    def test_update_validation_exception(self):
        self.assertRaises(
            ValidationError,
            lambda: self.redmine.wiki_page.update('Foo', title='Bar'))

    def test_delete_validation_exception(self):
        self.assertRaises(ValidationError,
                          lambda: self.redmine.wiki_page.delete('Foo'))

    @mock.patch('requests.put')
    @mock.patch('requests.post')
    def test_create_validation_exception_via_put(self, mock_post, mock_put):
        mock_post.return_value = mock.Mock(status_code=404)
        mock_put.return_value = mock.Mock(status_code=200)
        self.assertRaises(
            ValidationError,
            lambda: self.redmine.user.create(firstname='John',
                                             lastname='Smith'))

    @mock.patch('requests.get')
    def test_reraises_not_found_exception(self, mock_get):
        from redmine.exceptions import ResourceNotFoundError
        mock_get.return_value = mock.Mock(status_code=404)
        self.assertRaises(
            ResourceNotFoundError,
            lambda: self.redmine.project.get('non-existent-project'))

    @mock.patch('requests.get')
    def test_resource_requirements_exception(self, mock_get):
        from redmine.exceptions import ResourceRequirementsError
        FooResource.requirements = (
            'foo plugin',
            ('bar plugin', '1.2.3'),
        )
        mock_get.return_value = mock.Mock(status_code=404)
        self.redmine.custom_resource_paths = (__name__, )
        self.assertRaises(ResourceRequirementsError,
                          lambda: self.redmine.foo_resource.get(1))
Beispiel #13
0
 def test_handle_error(self):
     m = mock.mock_open()
     m.side_effect = OSError()
     with mock.patch("builtins.open", m, create=True):
         self.task.handle()