예제 #1
0
def fake_key_pair_info():
    mocked = mock.Mock()
    mocked.delete = mock.Mock()
    type(mocked).key_fingerprint = mock.PropertyMock()
    return mocked
예제 #2
0
 def setUp(self):
     self.mock_orchestration = mock.Mock()
     self.mock_stacks = mock.MagicMock()
     self.stack_status = mock.PropertyMock()
     type(self.mock_stacks).stack_status = self.stack_status
     self.mock_orchestration.stacks.get.return_value = self.mock_stacks
예제 #3
0
 def test_cannot_register_draft_that_is_pending_review(self, mock_enqueue, app, user, payload, url_registrations):
     with mock.patch.object(DraftRegistration, 'is_pending_review', mock.PropertyMock(return_value=True)):
         res = app.post_json_api(url_registrations, payload, auth=user.auth, expect_errors=True)
     assert res.status_code == 403
     assert res.json['errors'][0]['detail'] == 'This draft is pending review and cannot be modified.'
 def setUp(self):
     mock.patch.object(
         mech_driver.OpenDaylightDriver,
         'out_of_sync',
         new_callable=mock.PropertyMock(return_value=False)).start()
     super(OpenDaylightMechanismTestPortsV2, self).setUp()
예제 #5
0
    def test_sync(self, connection):
        """Test gmsa.HostGroupWatch.sync."""
        # Access protected module
        # pylint: disable=W0212
        server1_path = os.path.join(self.placement_dir, 'server1.ad.com')
        os.mkdir(server1_path)
        utils.touch(os.path.join(server1_path, 'proid1.app#0000000000001'))

        server2_path = os.path.join(self.placement_dir, 'server2.ad.com')
        os.mkdir(server2_path)
        utils.touch(os.path.join(server2_path, 'proid4.app#0000000000004'))

        server3_path = os.path.join(self.placement_dir, 'server3.ad.com')
        os.mkdir(server3_path)

        server4_path = os.path.join(self.placement_dir, 'server4.ad.com')
        os.mkdir(server4_path)
        utils.touch(os.path.join(server4_path, 'proid3.app#0000000000003'))

        server5_path = os.path.join(self.placement_dir, 'server5.ad.com')
        os.mkdir(server5_path)
        utils.touch(os.path.join(server5_path, 'proid5.app#0000000000005'))
        utils.touch(os.path.join(server5_path, 'proid5.app#0000000000006'))

        with io.open(os.path.join(self.servers_dir, 'server1.ad.com'),
                     'w') as f:
            yaml.dump({
                servers.DC_KEY: 'dc.ad.com',
                servers.DN_KEY: 'CN=server1,DC=AD,DC=COM',
                'partition': 'partition1'
            }, f)

        with io.open(os.path.join(self.servers_dir, 'server2.ad.com'),
                     'w') as f:
            yaml.dump({
                servers.DC_KEY: 'dc.ad.com',
                servers.DN_KEY: 'CN=server2,DC=AD,DC=COM',
                'partition': 'partition1'
            }, f)

        with io.open(os.path.join(self.servers_dir, 'server3.ad.com'),
                     'w') as f:
            yaml.dump({
                servers.DC_KEY: 'dc.ad.com',
                servers.DN_KEY: 'CN=server3,DC=AD,DC=COM',
                'partition': 'partition1'
            }, f)

        with io.open(os.path.join(self.servers_dir, 'server5.ad.com'),
                     'w') as f:
            yaml.dump({
                servers.DC_KEY: 'dc.ad.com',
                servers.DN_KEY: 'CN=server5,DC=AD,DC=COM',
                'partition': 'partition1'
            }, f)

        mock_connection = mock.MagicMock()
        connection.return_value = mock_connection
        type(mock_connection).result = mock.PropertyMock(side_effect={
            'result': 0
        })
        type(mock_connection).response = mock.PropertyMock(return_value=[
            {'attributes': {
                'samAccountName': 'proid1-gmsa-hosts',
                'member': ['CN=server1,DC=AD,DC=COM']
            }},
            {'attributes': {
                'samAccountName': 'proid2-gmsa-hosts',
                'member': ['CN=server3,DC=AD,DC=COM']
            }},
            {'attributes': {
                'samAccountName': 'proid3-gmsa-hosts',
                'member': []
            }},
            {'attributes': {
                'samAccountName': 'proid4-gmsa-hosts',
                'member': []
            }},
            {'attributes': {
                'samAccountName': 'proid5-gmsa-hosts',
                'member': []
            }}
        ])

        watch = gmsa.HostGroupWatch(self.root, 'partition1',
                                    'OU=test,DC=ad,DC=com', '{}-gmsa-hosts')
        watch._sync()

        self.assertEqual(watch._proids, {
            'proid1': {'CN=server1,DC=AD,DC=COM': 1},
            'proid2': {},
            'proid3': {},
            'proid4': {'CN=server2,DC=AD,DC=COM': 1},
            'proid5': {'CN=server5,DC=AD,DC=COM': 2},
        })

        mock_connection.modify.assert_has_calls(
            [
                mock.call('CN=proid2-gmsa-hosts,OU=test,DC=ad,DC=com',
                          {'member': [(ldap3.MODIFY_DELETE,
                                       ['CN=server3,DC=AD,DC=COM'])]}),
                mock.call('CN=proid4-gmsa-hosts,OU=test,DC=ad,DC=com',
                          {'member': [(ldap3.MODIFY_ADD,
                                       ['CN=server2,DC=AD,DC=COM'])]}),
                mock.call('CN=proid5-gmsa-hosts,OU=test,DC=ad,DC=com',
                          {'member': [(ldap3.MODIFY_ADD,
                                       ['CN=server5,DC=AD,DC=COM'])]}),
            ],
            any_order=True
        )
예제 #6
0
class TestGitHubAuthViews(GitHubAddonTestCase,
                          OAuthAddonAuthViewsTestCaseMixin, OsfTestCase):
    @mock.patch('addons.github.models.UserSettings.revoke_remote_oauth_access',
                mock.PropertyMock())
    def test_delete_external_account(self):
        super(TestGitHubAuthViews, self).test_delete_external_account()
예제 #7
0
def test_name(packagehandler):
    type(packagehandler.setuphandler).name = mock.PropertyMock(
        return_value='name')
    assert packagehandler.name == 'name'
예제 #8
0
def _mock_env(fingerprint=None):
    env = mock.Mock()
    prop_fingerprint = mock.PropertyMock(return_value=fingerprint)
    type(env).fingerprint = prop_fingerprint
    return env
예제 #9
0
def _mock_static(pod, path_format, locale=None):
    doc = mock.Mock()
    type(doc).pod = mock.PropertyMock(return_value=pod)
    type(doc).path_format = mock.PropertyMock(return_value=path_format)
    type(doc).locale = mock.PropertyMock(return_value=locale)
    return doc
예제 #10
0
class TestApiBaseViews(ApiTestCase):
    def setUp(self):
        super(TestApiBaseViews, self).setUp()
        self.EXCLUDED_VIEWS = [MoveFileMetadataView, CopyFileMetadataView]

    def test_root_returns_200(self):
        res = self.app.get('/{}'.format(API_BASE))
        assert_equal(res.status_code, 200)

    def test_does_not_exist_returns_404(self):
        res = self.app.get('/{}{}'.format(API_BASE, "notapage"),
                           expect_errors=True)
        assert_equal(res.status_code, 404)

    def test_does_not_exist_formatting(self):
        if DEBUG_MODE:
            raise SkipTest
        else:
            url = '/{}{}/'.format(API_BASE, 'notapage')
            res = self.app.get(url, expect_errors=True)
            errors = res.json['errors']
            assert (isinstance(errors, list))
            assert_equal(errors[0], {'detail': 'Not found.'})

    def test_view_classes_have_minimal_set_of_permissions_classes(self):
        base_permissions = [
            TokenHasScope, (IsAuthenticated, IsAuthenticatedOrReadOnly)
        ]
        for view in VIEW_CLASSES:
            if view in self.EXCLUDED_VIEWS:
                continue
            for cls in base_permissions:
                if isinstance(cls, tuple):
                    has_cls = any([c in view.permission_classes for c in cls])
                    assert_true(
                        has_cls,
                        "{0} lacks the appropriate permission classes".format(
                            view))
                else:
                    assert_in(
                        cls, view.permission_classes,
                        "{0} lacks the appropriate permission classes".format(
                            view))
            for key in ['read', 'write']:
                scopes = getattr(view, 'required_{}_scopes'.format(key), None)
                assert_true(bool(scopes))
                for scope in scopes:
                    assert_is_not_none(scope)
                if key == 'write':
                    assert_not_in(CoreScopes.ALWAYS_PUBLIC, scopes)

    def test_view_classes_support_embeds(self):
        for view in VIEW_CLASSES:
            if view in self.EXCLUDED_VIEWS:
                continue
            assert_true(hasattr(view, '_get_embed_partial'),
                        "{0} lacks embed support".format(view))

    def test_view_classes_define_or_override_serializer_class(self):
        for view in VIEW_CLASSES:
            has_serializer_class = getattr(view, 'serializer_class', None) or \
                                   getattr(view, 'get_serializer_class', None)
            assert_true(
                has_serializer_class,
                "{0} should include serializer class or override get_serializer_class()"
                .format(view))

    @mock.patch('osf.models.OSFUser.is_confirmed',
                mock.PropertyMock(return_value=False))
    def test_unconfirmed_user_gets_error(self):

        user = factories.AuthUserFactory()

        res = self.app.get('/{}nodes/'.format(API_BASE),
                           auth=user.auth,
                           expect_errors=True)
        assert_equal(res.status_code, http.BAD_REQUEST)

    @mock.patch('osf.models.OSFUser.is_disabled',
                mock.PropertyMock(return_value=True))
    def test_disabled_user_gets_error(self):

        user = factories.AuthUserFactory()

        res = self.app.get('/{}nodes/'.format(API_BASE),
                           auth=user.auth,
                           expect_errors=True)
        assert_equal(res.status_code, http.BAD_REQUEST)
예제 #11
0
def testrail_client(mocker):
    fake_statuses = mock.PropertyMock(return_value={1: 'passed', 2: 'skipped'})
    mocker.patch('xunit2testrail.reporter.TrClient.statuses',
                 new_callable=fake_statuses)
    return
예제 #12
0
def test_target_capacity(mock_resource_group, is_stale):
    with mock.patch(f'{__name__}.MockResourceGroup.is_stale',
                    mock.PropertyMock(return_value=is_stale)):
        assert mock_resource_group.target_capacity == 0 if is_stale else 5
예제 #13
0
    def test_workflow(self, fake_requests, client_logger, logger):
        self.dispatcher = gnocchi.GnocchiDispatcher(self.conf.conf)

        base_url = self.dispatcher.conf.dispatcher_gnocchi.url
        url_params = {
            'url': urlparse.urljoin(base_url, '/v1/resource'),
            # NOTE(sileht): we don't use urlparse.quote here
            # to ensure / is converted in %2F
            'resource_id': self.sample['resource_id'].replace("/", "%2F"),
            'resource_type': self.resource_type,
            'metric_name': self.sample['counter_name']
        }
        headers = {
            'Content-Type': 'application/json',
            'X-Auth-Token': 'fake_token'
        }

        patch_responses = []
        post_responses = []

        # This is needed to mock Exception in py3
        fake_requests.ConnectionError = requests.ConnectionError

        expected_calls = [
            mock.call.session(),
            mock.call.session().mount('http://', mock.ANY),
            mock.call.session().mount('https://', mock.ANY),
            mock.call.session().post(
                "%(url)s/%(resource_type)s/%(resource_id)s/"
                "metric/%(metric_name)s/measures" % url_params,
                headers=headers,
                data=json_matcher(self.measures_attributes))
        ]
        post_responses.append(MockResponse(self.measure))

        if self.measure == 401:
            type(self.ks_client).auth_token = mock.PropertyMock(side_effect=[
                'fake_token', 'new_token', 'new_token', 'new_token',
                'new_token'
            ])
            headers = {
                'Content-Type': 'application/json',
                'X-Auth-Token': 'new_token'
            }

            expected_calls.append(mock.call.session().post(
                "%(url)s/%(resource_type)s/%(resource_id)s/"
                "metric/%(metric_name)s/measures" % url_params,
                headers=headers,
                data=json_matcher(self.measures_attributes)))

            post_responses.append(MockResponse(200))

        if self.post_resource:
            attributes = self.postable_attributes.copy()
            attributes.update(self.patchable_attributes)
            attributes['id'] = self.sample['resource_id']
            attributes['metrics'] = dict((metric_name, {
                'archive_policy_name': 'low'
            }) for metric_name in self.metric_names)
            expected_calls.append(
                mock.call.session().post("%(url)s/%(resource_type)s" %
                                         url_params,
                                         headers=headers,
                                         data=json_matcher(attributes)), )
            post_responses.append(MockResponse(self.post_resource))

        if self.metric:
            expected_calls.append(mock.call.session().post(
                "%(url)s/%(resource_type)s/%(resource_id)s/metric" %
                url_params,
                headers=headers,
                data=json_matcher({
                    self.sample['counter_name']: {
                        'archive_policy_name': 'low'
                    }
                })))
            post_responses.append(MockResponse(self.metric))

        if self.measure_retry:
            expected_calls.append(mock.call.session().post(
                "%(url)s/%(resource_type)s/%(resource_id)s/"
                "metric/%(metric_name)s/measures" % url_params,
                headers=headers,
                data=json_matcher(self.measures_attributes)))
            post_responses.append(MockResponse(self.measure_retry))

        if self.patch_resource and self.patchable_attributes:
            expected_calls.append(
                mock.call.session().patch(
                    "%(url)s/%(resource_type)s/%(resource_id)s" % url_params,
                    headers=headers,
                    data=json_matcher(self.patchable_attributes)), )
            patch_responses.append(MockResponse(self.patch_resource))

        s = fake_requests.session.return_value
        s.patch.side_effect = patch_responses
        s.post.side_effect = post_responses

        self.dispatcher.record_metering_data([self.sample])

        # Check that the last log message is the expected one
        if self.measure == 500 or self.measure_retry == 500:
            logger.error.assert_called_with(
                "Fail to post measure on metric %s of resource %s "
                "with status: %d: Internal Server Error" %
                (self.sample['counter_name'], self.sample['resource_id'], 500))

        elif self.post_resource == 500 or (self.patch_resource == 500
                                           and self.patchable_attributes):
            logger.error.assert_called_with(
                "Resource %s %s failed with status: "
                "%d: Internal Server Error" %
                (self.sample['resource_id'],
                 'update' if self.patch_resource else 'creation', 500))
        elif self.metric == 500:
            logger.error.assert_called_with(
                "Fail to create metric %s of resource %s "
                "with status: %d: Internal Server Error" %
                (self.sample['counter_name'], self.sample['resource_id'], 500))
        elif self.patch_resource == 204 and self.patchable_attributes:
            client_logger.debug.assert_called_with('Resource %s updated',
                                                   self.sample['resource_id'])
        elif self.measure == 200:
            client_logger.debug.assert_called_with(
                "Measure posted on metric %s of resource %s",
                self.sample['counter_name'], self.sample['resource_id'])

        self.assertEqual(expected_calls, fake_requests.mock_calls)
예제 #14
0
    def test_raises_for_invalid_json_body(self, user, pyramid_request, patch):
        type(pyramid_request).json_body = mock.PropertyMock(
            side_effect=ValueError())

        with pytest.raises(PayloadError):
            update(user, pyramid_request)
class ViewTests(TestCase):
    def verify_health_response(self, expected_status_code, overall_status,
                               database_connection, analytics_api):
        """Verify that the health endpoint returns the expected response."""
        response = self.client.get(reverse('health'))
        self.assertEqual(response.status_code, expected_status_code)
        self.assertEqual(response['content-type'], 'application/json')
        expected = {
            u'overall_status': overall_status,
            u'detailed_status': {
                u'database_connection': database_connection,
                u'analytics_api': analytics_api
            }
        }
        self.assertDictEqual(json.loads(response.content), expected)

    def test_status(self):
        response = self.client.get(reverse('status'))
        self.assertEqual(response.status_code, 200)

    @mock.patch('analyticsclient.status.Status.healthy',
                mock.PropertyMock(return_value=True))
    def test_healthy(self):
        with LogCapture(level=logging.ERROR) as l:
            self.verify_health_response(expected_status_code=200,
                                        overall_status=OK,
                                        database_connection=OK,
                                        analytics_api=OK)
            l.check()

    @mock.patch('analyticsclient.status.Status.healthy',
                mock.PropertyMock(return_value=True))
    @mock.patch('django.db.backends.BaseDatabaseWrapper.cursor',
                mock.Mock(side_effect=DatabaseError('example error')))
    def test_health_database_outage(self):
        with LogCapture(level=logging.ERROR) as l:
            self.verify_health_response(expected_status_code=503,
                                        overall_status=UNAVAILABLE,
                                        database_connection=UNAVAILABLE,
                                        analytics_api=OK)
            l.check(('analytics_dashboard.core.views', 'ERROR',
                     'Insights database is not reachable: example error'))

    @mock.patch('analyticsclient.status.Status.healthy',
                mock.PropertyMock(return_value=False))
    def test_health_analytics_api_unhealthy(self):
        with LogCapture(level=logging.ERROR) as l:
            self.verify_health_response(expected_status_code=503,
                                        overall_status=UNAVAILABLE,
                                        database_connection=OK,
                                        analytics_api=UNAVAILABLE)
            l.check(('analytics_dashboard.core.views', 'ERROR',
                     'Analytics API health check failed from dashboard'))

    @mock.patch('analyticsclient.status.Status.healthy',
                mock.PropertyMock(side_effect=TimeoutError('example error')))
    def test_health_analytics_api_unreachable(self):
        with LogCapture(level=logging.ERROR) as l:
            self.verify_health_response(expected_status_code=503,
                                        overall_status=UNAVAILABLE,
                                        database_connection=OK,
                                        analytics_api=UNAVAILABLE)
            l.check((
                'analytics_dashboard.core.views', 'ERROR',
                'Analytics API health check timed out from dashboard: example error'
            ))

    @mock.patch('analyticsclient.status.Status.healthy',
                mock.PropertyMock(return_value=False))
    @mock.patch('django.db.backends.BaseDatabaseWrapper.cursor',
                mock.Mock(side_effect=DatabaseError('example error')))
    def test_health_both_unavailable(self):
        with LogCapture(level=logging.ERROR) as l:
            self.verify_health_response(expected_status_code=503,
                                        overall_status=UNAVAILABLE,
                                        database_connection=UNAVAILABLE,
                                        analytics_api=UNAVAILABLE)
            l.check(('analytics_dashboard.core.views', 'ERROR',
                     'Insights database is not reachable: example error'),
                    ('analytics_dashboard.core.views', 'ERROR',
                     'Analytics API health check failed from dashboard'))
예제 #16
0
def _mock_collection(basename=None, root=None):
    collection = mock.Mock()
    type(collection).basename = mock.PropertyMock(return_value=basename)
    type(collection).root = mock.PropertyMock(return_value=root)
    return collection
예제 #17
0
 def setUp(self):
     super(TestTokenController, self).setUp()
     type(pecan.request).remote_user = mock.PropertyMock(
         return_value=USERNAME)
예제 #18
0
 def test_str_operator(self):
     mock_invite = hikari_test_helpers.mock_class_namespace(
         invites.InviteCode,
         code=mock.PropertyMock(return_value="hikari"))()
     assert str(mock_invite) == "https://discord.gg/hikari"
예제 #19
0
 def test_can_mark_complete_admin_grader(self, available_now):
     with patch_obj(self.block_to_test, 'is_admin_grader', mock.PropertyMock(return_value=True)), \
             patch_obj(self.block_to_test, 'available_now', mock.PropertyMock(return_value=available_now)):
         self.assertEqual(self.block.can_mark_complete, True)
예제 #20
0
 def test_question_property_no_questions(self):
     with mock.patch.object(self.block_to_test, 'activity_questions',
                            mock.PropertyMock(return_value=[])):
         self.assertIsNone(self.block.question)
예제 #21
0
    The newly-created Event entities.
  """
    return [CreateEvent(blockable) for _ in xrange(event_count)]


def CreateSantaEvents(blockable, event_count):
    return [CreateSantaEvent(blockable) for _ in xrange(event_count)]


def CreateBit9Events(blockable, event_count):
    return [CreateBit9Event(blockable) for _ in xrange(event_count)]


@mock.patch.object(settings.ProdEnv,
                   'ENABLE_BIGQUERY_STREAMING',
                   new_callable=mock.PropertyMock(return_value=False))
def CreateUser(_, admin=False, **kwargs):
    """Creates an User entity.

  Args:
    admin: Whether or not administrative privileges should be assigned.
    **kwargs: Dictionary of any user properties to customize.

  Returns:
    The newly created User.
  """
    email = kwargs.pop('email', None) or RandomEmail()
    roles = set(kwargs.pop('roles', []))

    # Create an User entity if one doesn't exist, and update the resulting
    # entity with any overridden properties.
예제 #22
0
 def test_question_property_no_matching_questions(self):
     self.block.question_id = 'q1'
     questions = [make_question('123', '123'), make_question('456', '456')]
     with mock.patch.object(self.block_to_test, 'activity_questions',
                            mock.PropertyMock(return_value=questions)):
         self.assertIsNone(self.block.question)
예제 #23
0
    def test_exec_command(self):
        gsc_mock = self.patch('tempest_lib.common.ssh.Client.'
                              '_get_ssh_connection')
        ito_mock = self.patch('tempest_lib.common.ssh.Client._is_timed_out')
        select_mock = self.patch('select.poll')

        client_mock = mock.MagicMock()
        tran_mock = mock.MagicMock()
        chan_mock = mock.MagicMock()
        poll_mock = mock.MagicMock()

        def reset_mocks():
            gsc_mock.reset_mock()
            ito_mock.reset_mock()
            select_mock.reset_mock()
            poll_mock.reset_mock()
            client_mock.reset_mock()
            tran_mock.reset_mock()
            chan_mock.reset_mock()

        select_mock.return_value = poll_mock
        gsc_mock.return_value = client_mock
        ito_mock.return_value = True
        client_mock.get_transport.return_value = tran_mock
        tran_mock.open_session.return_value = chan_mock
        poll_mock.poll.side_effect = [[0, 0, 0]]

        # Test for a timeout condition immediately raised
        client = ssh.Client('localhost', 'root', timeout=2)
        with testtools.ExpectedException(exceptions.TimeoutException):
            client.exec_command("test")

        chan_mock.fileno.assert_called_once_with()
        chan_mock.exec_command.assert_called_once_with("test")
        chan_mock.shutdown_write.assert_called_once_with()

        SELECT_POLLIN = 1
        poll_mock.register.assert_called_once_with(chan_mock, SELECT_POLLIN)
        poll_mock.poll.assert_called_once_with(10)

        # Test for proper reading of STDOUT and STDERROR and closing
        # of all file descriptors.

        reset_mocks()

        select_mock.return_value = poll_mock
        gsc_mock.return_value = client_mock
        ito_mock.return_value = False
        client_mock.get_transport.return_value = tran_mock
        tran_mock.open_session.return_value = chan_mock
        poll_mock.poll.side_effect = [[1, 0, 0]]
        closed_prop = mock.PropertyMock(return_value=True)
        type(chan_mock).closed = closed_prop
        chan_mock.recv_exit_status.return_value = 0
        chan_mock.recv.return_value = ''
        chan_mock.recv_stderr.return_value = ''

        client = ssh.Client('localhost', 'root', timeout=2)
        client.exec_command("test")

        chan_mock.fileno.assert_called_once_with()
        chan_mock.exec_command.assert_called_once_with("test")
        chan_mock.shutdown_write.assert_called_once_with()

        SELECT_POLLIN = 1
        poll_mock.register.assert_called_once_with(chan_mock, SELECT_POLLIN)
        poll_mock.poll.assert_called_once_with(10)
        chan_mock.recv_ready.assert_called_once_with()
        chan_mock.recv.assert_called_once_with(1024)
        chan_mock.recv_stderr_ready.assert_called_once_with()
        chan_mock.recv_stderr.assert_called_once_with(1024)
        chan_mock.recv_exit_status.assert_called_once_with()
        closed_prop.assert_called_once_with()
예제 #24
0
 def test_question_property_one_matching_question(self):
     self.block.question_id = '456'
     questions = [make_question('123', '123'), make_question('456', '456')]
     with mock.patch.object(self.block_to_test, 'activity_questions',
                            mock.PropertyMock(return_value=questions)):
         self.assertEqual(self.block.question, questions[1])
예제 #25
0
class TestRegistrationRetractions(SearchTestCase):

    def setUp(self):
        super(TestRegistrationRetractions, self).setUp()
        self.user = UserFactory(usename='Doug Bogie')
        self.title = 'Red Special'
        self.consolidate_auth = Auth(user=self.user)
        self.project = ProjectFactory(
            title=self.title,
            creator=self.user,
            is_public=True,
        )
        self.registration = RegistrationFactory(
            project=self.project,
            title=self.title,
            creator=self.user,
            is_public=True,
            is_registration=True
        )

    def test_retraction_is_searchable(self):

        self.registration.retract_registration(self.user)
        docs = query('category:registration AND ' + self.title)['results']
        assert_equal(len(docs), 1)

    @mock.patch('website.project.model.Node.archiving', mock.PropertyMock(return_value=False))
    def test_pending_retraction_wiki_content_is_searchable(self):
        # Add unique string to wiki
        wiki_content = {'home': 'public retraction test'}
        for key, value in wiki_content.items():
            docs = query(value)['results']
            assert_equal(len(docs), 0)
            self.registration.update_node_wiki(
                key, value, self.consolidate_auth,
            )
            # Query and ensure unique string shows up
            docs = query(value)['results']
            assert_equal(len(docs), 1)

        # Query and ensure registration does show up
        docs = query('category:registration AND ' + self.title)['results']
        assert_equal(len(docs), 1)

        # Retract registration
        self.registration.retract_registration(self.user, '')
        self.registration.save()
        self.registration.reload()

        # Query and ensure unique string in wiki doesn't show up
        docs = query('category:registration AND "{}"'.format(wiki_content['home']))['results']
        assert_equal(len(docs), 1)

        # Query and ensure registration does show up
        docs = query('category:registration AND ' + self.title)['results']
        assert_equal(len(docs), 1)

    @mock.patch('website.project.model.Node.archiving', mock.PropertyMock(return_value=False))
    def test_retraction_wiki_content_is_not_searchable(self):
        # Add unique string to wiki
        wiki_content = {'home': 'public retraction test'}
        for key, value in wiki_content.items():
            docs = query(value)['results']
            assert_equal(len(docs), 0)
            self.registration.update_node_wiki(
                key, value, self.consolidate_auth,
            )
            # Query and ensure unique string shows up
            docs = query(value)['results']
            assert_equal(len(docs), 1)

        # Query and ensure registration does show up
        docs = query('category:registration AND ' + self.title)['results']
        assert_equal(len(docs), 1)

        # Retract registration
        self.registration.retract_registration(self.user, '')
        self.registration.retraction.state = Retraction.APPROVED
        self.registration.retraction.save()
        self.registration.save()
        self.registration.update_search()

        # Query and ensure unique string in wiki doesn't show up
        docs = query('category:registration AND "{}"'.format(wiki_content['home']))['results']
        assert_equal(len(docs), 0)

        # Query and ensure registration does show up
        docs = query('category:registration AND ' + self.title)['results']
        assert_equal(len(docs), 1)
예제 #26
0
 def test_question_property_multiple_matching_questions(self):
     self.block.question_id = '123'
     questions = [make_question('123', '123'), make_question('123', '123')]
     with mock.patch.object(self.block_to_test, 'activity_questions', mock.PropertyMock(return_value=questions)), \
             self.assertRaises(ValueError):
         _ = self.block.question  # pylint:disable=invalid-name
예제 #27
0
 def test_has_updates_is_false_if_active_with_no_output(self):
     target = ('neutron.agent.linux.ovsdb_monitor.SimpleInterfaceMonitor'
               '.is_active')
     with mock.patch(target,
                     new_callable=mock.PropertyMock(return_value=True)):
         self.assertFalse(self.monitor.has_updates)
예제 #28
0
 def _test_update_device_up(self, extensions, kwargs):
     with mock.patch('neutron.plugins.ml2.plugin.Ml2Plugin'
                     '._device_to_port_id'):
         type(self.l3plugin).supported_extension_aliases = (
             mock.PropertyMock(return_value=extensions))
         self.callbacks.update_device_up(mock.ANY, **kwargs)
예제 #29
0
 def test_cannot_register_draft_that_has_already_been_approved(self, app, user, payload, url_registrations):
     with mock.patch.object(DraftRegistration, 'requires_approval', mock.PropertyMock(return_value=True)), mock.patch.object(DraftRegistration, 'is_approved', mock.PropertyMock(return_value=True)):
         res = app.post_json_api(url_registrations, payload, auth=user.auth, expect_errors=True)
     assert res.status_code == 403
     assert res.json['errors'][0]['detail'] == 'This draft has already been approved and cannot be modified.'
예제 #30
0
class TestNodeSettings(OAuthAddonNodeSettingsTestSuiteMixin,
                       unittest.TestCase):

    short_name = 'gitlab'
    full_name = 'GitLab'
    ExternalAccountFactory = GitLabAccountFactory

    NodeSettingsFactory = GitLabNodeSettingsFactory
    NodeSettingsClass = NodeSettings
    UserSettingsFactory = GitLabUserSettingsFactory

    ## Mixin Overrides ##

    def _node_settings_class_kwargs(self, node, user_settings):
        return {
            'user_settings': self.user_settings,
            'repo': 'mock',
            'user': '******',
            'owner': self.node,
            'repo_id': '123'
        }

    def test_set_folder(self):
        # GitLab doesn't use folderpicker, and the nodesettings model
        # does not need a `set_repo` method
        pass

    def test_serialize_settings(self):
        # GitLab's serialized_settings are a little different from
        # common storage addons.
        settings = self.node_settings.serialize_waterbutler_settings()
        expected = {
            'host': 'https://some-super-secret',
            'owner': 'abc',
            'repo': 'mock',
            'repo_id': '123'
        }
        assert_equal(settings, expected)

    @mock.patch('addons.gitlab.models.UserSettings.revoke_remote_oauth_access',
                mock.PropertyMock())
    def test_complete_has_auth_not_verified(self):
        super(TestNodeSettings, self).test_complete_has_auth_not_verified()

    @mock.patch('addons.gitlab.api.GitLabClient.repos')
    def test_to_json(self, mock_repos):
        mock_repos.return_value = {}
        super(TestNodeSettings, self).test_to_json()

    @mock.patch('addons.gitlab.api.GitLabClient.repos')
    def test_to_json_user_is_owner(self, mock_repos):
        mock_repos.return_value = {}
        result = self.node_settings.to_json(self.user)
        assert_true(result['user_has_auth'])
        assert_equal(result['gitlab_user'], 'abc')
        assert_true(result['is_owner'])
        assert_true(result['valid_credentials'])
        assert_equal(result.get('gitlab_repo', None), 'mock')

    @mock.patch('addons.gitlab.api.GitLabClient.repos')
    def test_to_json_user_is_not_owner(self, mock_repos):
        mock_repos.return_value = {}
        not_owner = UserFactory()
        result = self.node_settings.to_json(not_owner)
        assert_false(result['user_has_auth'])
        assert_equal(result['gitlab_user'], 'abc')
        assert_false(result['is_owner'])
        assert_true(result['valid_credentials'])
        assert_equal(result.get('repo_names', None), None)