def test_collection_post_error(self, mock_method):
     mock_method.side_effect = GitCommandError('git clone',
                                               'Boom!',
                                               stderr='mocked response')
     request = testing.DummyRequest({})
     request.validated = {
         'repo_url': 'git://example.org/bar.git',
         'repo_name': None
     }
     request.errors = Errors()
     resource = RepositoryResource(request)
     resource.collection_post()
     [error] = request.errors
     self.assertEqual(error['location'], 'body')
     self.assertEqual(error['name'], 'repo_url')
     self.assertEqual(error['description'], 'mocked response')
    def test_collection_post_success(self):
        # NOTE: cloning to a different directory called `remote` because
        #       the API is trying to clone into the same folder as the
        #       tests: self.WORKING_DIR.
        #
        # FIXME: This is too error prone & tricky to reason about
        api_repo_name = '%s_remote' % (self.id(), )
        self.remote_workspace = self.mk_workspace(working_dir=os.path.join(
            self.WORKING_DIR, 'remote'),
                                                  name=api_repo_name)
        request = testing.DummyRequest({})
        request.validated = {
            'repo_url': self.remote_workspace.working_dir,
            'repo_name': None
        }
        # Cleanup the repo created by the API on tear down
        self.addCleanup(lambda: EG.workspace(
            os.path.join(self.WORKING_DIR, api_repo_name)).destroy())
        self.addCleanup(lambda: EG.workspace(
            os.path.join(self.WORKING_DIR, 'foo-bar')).destroy())
        request.route_url = lambda route, name: ('/repos/%s.json' %
                                                 (api_repo_name, ))
        request.errors = Errors()
        resource = RepositoryResource(request)

        with patch.object(request.registry, 'notify') as mocked_notify:
            resource.collection_post()
            self.assertEqual(request.response.headers['Location'],
                             '/repos/%s.json' % (api_repo_name, ))
            self.assertEqual(request.response.status_code, 301)
            mocked_notify.assert_called()
            (event, ) = mocked_notify.call_args[0]
            self.assertIsInstance(event, RepositoryCloned)
            self.assertIs(event.config, self.config.registry.settings)
            self.assertEqual(
                event.repo.working_dir,
                os.path.abspath(os.path.join(self.WORKING_DIR, api_repo_name)))
            # check that the repo can be cloned with a different name
            request.validated['repo_name'] = 'foo-bar'
            resource.collection_post()
            self.assertEqual(request.response.status_code, 301)
            self.assertTrue(
                os.path.exists(os.path.join(self.WORKING_DIR, 'foo-bar')))