Пример #1
0
    def test_we_return_false_if_at_least_one_is_not_running(self, mock_httplib, mock_landlord, mock_ec2):
        project = {'name': 'MyProject', 'version': 'v34', 'type': 'play2'}
        mock_landlord.Tenant = StubLandlord
        mock_connection = Mock()
        mock_ec2.connect_to_region.return_value = mock_connection
        instance1 = Mock()
        instance1.id = 'i-938372'
        instance1.public_dns_name = 'my.awesome.dns.com'
        instance1.update.return_value = 'running'

        instance2 = Mock()
        instance2.id = 'i-542211'
        instance2.public_dns_name = 'my.awesome2.dns.com'
        instance2.update.return_value = 'stopped'
        mock_connection.get_only_instances.return_value = [instance1, instance2]
        instances = ['i-278219', 'i-82715']
        url_connection = Mock()
        response = Mock(status=200)
        url_connection.getresponse.return_value = response
        mock_httplib.HTTPConnection.return_value = url_connection

        self.assertEquals(False, ec2.is_running(None, None))
        self.assertEquals(False, ec2.is_running(None, {}))

        result = ec2.is_running(instances, project)
        mock_ec2.connect_to_region.assert_called_with('deploy.region', aws_access_key_id='aws.id',
                                                      aws_secret_access_key='aws.secret')
        mock_connection.get_only_instances.assert_called_with(instances)
        self.assertEquals(True, instance1.update.called)
        self.assertEquals(True, instance2.update.called)
        self.assertEquals(False, result)
Пример #2
0
    def test_rpc_calls(self, mock_node_get, mock_package_get):
        NODE_ID = 42
        NODE_TITLE = "Node"
        PARENT_ID = 1
        PARENT_TITLE = "Parent"

        # mock node
        new_node = Mock()
        new_node.id = NODE_ID
        new_node.title = NODE_TITLE

        parent_node = Mock()
        parent_node.id = PARENT_ID
        parent_node.title = PARENT_TITLE
        parent_node.create_child.return_value = new_node

        # mock package
        package = Mock()
        package.user.username = TEST_USER

        # mock get query
        mock_node_get.return_value = parent_node
        mock_package_get.return_value = package
        parent_node.package = package

        r = self.s.package.add_child_node(
                                    # username=TEST_USER,
                                    #       password=TEST_PASSWORD,
                                    package_id="1",
                                    node_id=str(PARENT_ID))
        result = r['result']
        self.assertEquals(result['id'], NODE_ID)
        self.assertEquals(result['title'], NODE_TITLE)
        self.assertTrue(parent_node.create_child.called)
Пример #3
0
    def test_getLastPenalties(self):
        c1 = Mock()
        c1.id = 15
        c2 = Mock()
        c2.id = 18
        Penalty(clientId=c1.id, adminId=0, inactive=1, type='Ban', timeExpire=-1, data=u'pA').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Ban', timeExpire=self.console.time()+10, data=u'pB').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Warning', timeExpire=self.console.time()+10, data=u'pC').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Kick', timeExpire=self.console.time()-10, data=u'pD').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Ban', timeExpire=self.console.time()-10, data=u'pE').save(self.console)
        Penalty(clientId=c2.id, adminId=0, inactive=0, type='Warning', timeExpire=-1, data=u'pF').save(self.console)
        Penalty(clientId=c2.id, adminId=0, inactive=0, type='TempBan', timeExpire=-1, data=u'pG').save(self.console)
        Penalty(clientId=c2.id, adminId=0, inactive=0, type='Ban', timeExpire=-1, data=u'pH').save(self.console)

        def getLastPenalties(types, num):
            p_datas = []
            for p in self.storage.getLastPenalties(types=types, num=num):
                p_datas.append(p.data)
                self.assertTrue(p.inactive == 0)
                self.assertTrue(p.timeExpire == -1 or p.timeExpire > self.console.time())
            self.assertGreaterEqual(num, len(p_datas))
            return p_datas

        self.assertListEqual([u'pH', u'pG', u'pF', u'pC', u'pB'], getLastPenalties(types=('Ban', 'TempBan', 'Kick', 'Warning', 'Notice'), num=5))
        self.assertListEqual([u'pH', u'pG', u'pF', u'pC'], getLastPenalties(types=('Ban', 'TempBan', 'Kick', 'Warning', 'Notice'), num=4))
        self.assertListEqual([u'pH', u'pG', u'pB'], getLastPenalties(types=('Ban', 'TempBan'), num=5))
Пример #4
0
    def test_sync(self, mock_ndb, mock_repo, mock_set):
        """Ensure that a Repository entity is created for every GitHub repo
        that doesn't already have an entity and a list of the user's repos is
        returned.
        """

        mock_user = Mock()
        repo1 = Mock()
        repo1.id = 'repo1'
        repo2 = Mock()
        repo2.id = 'repo2'
        repo2.name = 'repo2'
        repo2.description = 'description'
        mock_user.github_repos = [repo1, repo2]
        key1 = Mock()
        key2 = Mock()
        keys = [key1, key2]
        mock_ndb.Key.side_effect = keys
        mock_ndb.get_multi.return_value = [repo1, None]

        actual = repository.sync_repos(mock_user)

        self.assertEqual([repo1, mock_repo.return_value], actual)
        expected = [call(repository.Repository, 'github_%s' % repo.id)
                    for repo in [repo1, repo2]]
        self.assertEqual(expected, mock_ndb.Key.call_args_list)
        mock_ndb.get_multi.assert_called_once_with(keys)
        mock_repo.assert_called_once_with(id='github_%s' % repo2.id,
                                          description=repo2.description,
                                          name=repo2.name, owner=mock_user.key)
        mock_ndb.put_multi.assert_called_once_with([mock_repo.return_value])
        mock_set.assert_called_once_with(
            'kaput:repos:%s' % mock_user.key.id(),
            [repo1, mock_repo.return_value])
Пример #5
0
    def test_fan_out(self, mock_context, mock_commit):
        """Ensure that tasks are inserted for each Commit that does not have a
        Release associated with it.
        """

        query = Mock()
        key1 = Mock()
        key2 = Mock()
        query.fetch_page.return_value = ([key1, key2], None, False)
        mock_commit.query.return_value = query
        query.filter.return_value = query
        context = Mock()
        mock_context.new.return_value.__enter__.return_value = context

        repo = Mock()
        release = Mock()

        repository._tag_commits(repo, release)

        mock_commit.query.assert_called_once_with(ancestor=repo.key)
        query.filter.assert_called_once_with(repository.Commit.release == None)
        mock_context.new.assert_called_once_with()
        query.fetch_page.assert_called_once_with(500, start_cursor=None,
                                                 keys_only=True)
        context.add.assert_called_once_with(
            target=repository.tag_commit,
            args=(repo.key.id(), release.key.id(), [key1.id(), key2.id()])
        )
Пример #6
0
    def it_can_fill_itself_from_a_queryset(self):
        class Doc(Document):
            id = fields.NumberField()

        class Col(Collection):
            document = Doc

        model1 = Mock()
        model2 = Mock()
        model1.id = 1
        model2.id = 2

        col = Col()

        eq_(0, len(col.collection_set))

        col._from_queryset([model1, model2])

        eq_(2, len(col.collection_set))

        doc1 = col.collection_set[0]
        doc2 = col.collection_set[1]

        eq_(True, isinstance(doc1, Doc))
        eq_(True, isinstance(doc2, Doc))
        eq_(1, doc1.id)
        eq_(2, doc2.id)
Пример #7
0
    def it_can_fetch_data_from_the_underlying_model(self):
        DjangoModel = Mock(name="DjangoModel")
        mock_model = Mock()
        mock_model.id = 1
        DjangoModel.objects.get.return_value = mock_model

        manager = BackendManager('django')
        # The manager needs to know which model it connects to
        # This is normally done when the Document is created.
        manager._model = DjangoModel

        doc = Mock(name="mock_document", spec=Document)
        field = fields.NumberField()
        field.name = "id"
        doc.id = 1
        doc._context = {}
        doc._get_context.return_value = {}
        doc._meta.identifier = ["id"]
        doc._identifier_state.return_value = {"id": 1}
        doc._save.return_value = {"id": 1}
        doc._meta.local_fields = [field]

        # make sure we are working with correct expectations
        eq_(DjangoBackendManager, type(manager))
        eq_({'id': 1}, manager.fetch(doc))
        eq_([('objects.get', {'id': 1})], DjangoModel.method_calls)
Пример #8
0
  def testGetSuggestedInstancesTwoDifferentSize(self, getEC2InstancesMock):
    regionMock = Mock(spec="boto.ec2.region.Region")
    regionMock.name = "us-west-2"
    # Instance 1
    instanceMock1 = Mock(spec="boto.ec2.instance.Instance")
    instanceMock1.state = "running"
    instanceMock1.instance_type = "m3.large"
    instanceMock1.launch_time = "2014-05-06T15:17:33.324Z"
    instanceMock1.region = regionMock
    instanceMock1.id = "testId1"
    instanceMock1.tags = {"Name": "testName1"}
    # Instance 2
    instanceMock2 = Mock(spec="boto.ec2.instance.Instance")
    instanceMock2.state = "running"
    instanceMock2.instance_type = "m3.xlarge"
    instanceMock2.launch_time = "2014-05-06T15:18:33.324Z"
    instanceMock2.region = regionMock
    instanceMock2.id = "testId2"
    instanceMock2.tags = {"Name": "testName2"}
    getEC2InstancesMock.return_value = [
        instanceMock1,
        instanceMock2,
    ]

    suggestions = ec2_utils.getSuggestedInstances(regionMock.name)
    self.assertIsInstance(suggestions, types.GeneratorType)
    suggestions = list(suggestions)

    self.assertSequenceEqual(suggestions, [
        {"id": "testId2", "name": "testName2", "namespace": "AWS/EC2",
         "region": regionMock.name},
        {"id": "testId1", "name": "testName1", "namespace": "AWS/EC2",
         "region": regionMock.name},
    ])
    getEC2InstancesMock.assert_call_once_with(regionMock.name)
Пример #9
0
  def testGetSuggestedInstancesTwoDifferentSize(self, getRDSInstancesMock):
    region = "us-west-2"
    # Instance 1
    instanceMock1 = Mock(spec="boto.rds.dbinstance.DBInstance")
    instanceMock1.status = "available"
    instanceMock1.allocated_storage = 64.0
    instanceMock1.id = "testId1"
    # Instance 2
    instanceMock2 = Mock(spec="boto.rds.dbinstance.DBInstance")
    instanceMock2.status = "available"
    instanceMock2.allocated_storage = 65.0
    instanceMock2.id = "testId2"

    getRDSInstancesMock.return_value = [
        instanceMock1,
        instanceMock2,
    ]

    suggestions = rds_utils.getSuggestedInstances(region)
    self.assertIsInstance(suggestions, types.GeneratorType)
    suggestions = list(suggestions)

    self.assertSequenceEqual(suggestions, [
        {"id": "testId2", "name": "testId2", "namespace": "AWS/RDS",
         "region": region},
        {"id": "testId1", "name": "testId1", "namespace": "AWS/RDS",
         "region": region},
    ])
    getRDSInstancesMock.assert_call_once_with(region)
Пример #10
0
    def test_we_capture_the_checkurl_exception_and_return_false(self, mock_landlord, mock_ec2):
        properties = {'region': 'myRegion', 'environment': 'STAGE', 'domain': 'this.is.awesome'}
        project = {'name': 'MyProject', 'version': 'v34', 'type': 'play2'}
        instances_ids = ['blah']

        mock_landlord.Tenant = StubNameLandlord
        mock_connection = Mock()
        mock_ec2.connect_to_region.return_value = mock_connection

        instance1 = Mock()
        instance1.id = 'i-938372'
        instance1.ip_address = '192.1.11.1'
        instance1.state = 'running'
        instance1.launch_time = datetime.date.today().isoformat()
        instance1.tags = {'Name': 'STAGE-Instance-1', 'Project': 'Instance', 'Version': 'v43'}

        instance2 = Mock()
        instance2.id = 'i-542211'
        instance2.state = 'stopped'
        instance2.ip_address = None
        instance2.launch_time = datetime.date.today().isoformat()
        instance2.tags = {'Name': 'STAGE-Instance-2', 'Project': 'Instance', 'Version': 'v43'}

        mock_connection.get_only_instances.return_value = [instance1, instance2]

        real_function = ec2.check_url

        ec2.check_url = Mock(side_effect=[Exception('BOOM!','I have created an instance and you are wasting money... muahahaha')])

        result = ec2.is_running(instances_ids, project)

        self.assertEquals(False, result)

        ec2.check_url = real_function
Пример #11
0
def test_pdbfix_templates():
    template1_pdb_gz_filepath = get_installed_resource_filename(os.path.join('resources', 'KC1D_HUMAN_D0_4KB8_D.pdb.gz'))
    template1_pdb_filepath = os.path.join(ensembler.core.default_project_dirnames.templates_structures_resolved, 'KC1D_HUMAN_D0_4KB8_D.pdb')
    template2_pdb_gz_filepath = get_installed_resource_filename(os.path.join('resources', 'KC1D_HUMAN_D0_3UYS_D.pdb.gz'))
    template2_pdb_filepath = os.path.join(ensembler.core.default_project_dirnames.templates_structures_resolved, 'KC1D_HUMAN_D0_3UYS_D.pdb')
    with ensembler.utils.enter_temp_dir():
        ensembler.utils.create_dir(ensembler.core.default_project_dirnames.templates_structures_resolved)
        ensembler.utils.create_dir(ensembler.core.default_project_dirnames.templates_structures_modeled_loops)
        with gzip.open(template1_pdb_gz_filepath) as template1_pdb_gz_file:
            with open(template1_pdb_filepath, 'w') as template1_pdb_file:
                contents = template1_pdb_gz_file.read()
                if type(contents) == bytes:
                    contents = contents.decode('utf-8')
                template1_pdb_file.write(contents)
        with gzip.open(template2_pdb_gz_filepath) as template2_pdb_gz_file:
            with open(template2_pdb_filepath, 'w') as template2_pdb_file:
                contents = template2_pdb_gz_file.read()
                if type(contents) == bytes:
                    contents = contents.decode('utf-8')
                template2_pdb_file.write(contents)

        template1 = Mock()
        template1.id = 'KC1D_HUMAN_D0_4KB8_D'
        template1.seq = 'LRVGNRYRLGRKIGSGSFGDIYLGTDIAAGEEVAIKLECVKTKHPQLHIESKIYKMMQGGVGIPTIRWCGAEGDYNVMVMELLGPSLEDLFNFCSRKFSLKTVLLLADQMISRIEYIHSKNFIHRDVKPDNFLMGLGKKGNLVYIIDFGLAKKYRDARTHQHIPYRENKNLTGTARYASINTHLGIEQSRRDDLESLGYVLMYFNLGSLPWQGLKAATKRQKYERISEKKMSTPIEVLCKGYPSEFATYLNFCRSLRFDDKPDYSYLRQLFRNLFHRQGFSYDYVFDWNMLKFGASRAADDAERERRDREERLRH'

        template2 = Mock()
        template2.id = 'KC1D_HUMAN_D0_3UYS_D'
        template2.seq = 'MELRVGNRYRLGRKIGSGSFGDIYLGTDIAAGEEVAIKLECVKTKHPQLHIESKIYKMMQGGVGIPTIRWCGAEGDYNVMVMELLGPSLEDLFNFCSRKFSLKTVLLLADQMISRIEYIHSKNFIHRDVKPDNFLMGLGKKGNLVYIIDFGLAKKYRDARTHQHIPYRENKNLTGTARYASINTHLGIEQSRRDDLESLGYVLMYFNLGSLPWQGLKAATKRQKYERISEKKMSTPIEVLCKGYPSEFATYLNFCRSLRFDDKPDYSYLRQLFRNLFHRQGFSYDYVFDWNMLK'

        templates = [template1, template2]

        missing_residues_list = pdbfix_templates(templates)
Пример #12
0
    def test_getClientPenalties(self):
        c1 = Mock()
        c1.id = 15
        c2 = Mock()
        c2.id = 18
        Penalty(clientId=c1.id, adminId=0, inactive=1, type='Ban', timeExpire=-1, data='pA').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Ban', timeExpire=self.console.time()+10, data='pB').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Warning', timeExpire=self.console.time()+10, data='pC').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Kick', timeExpire=self.console.time()-10, data='pD').save(self.console)
        Penalty(clientId=c1.id, adminId=0, inactive=0, type='Ban', timeExpire=self.console.time()-10, data='pE').save(self.console)
        Penalty(clientId=c2.id, adminId=0, inactive=0, type='Warning', timeExpire=-1, data='pF').save(self.console)
        Penalty(clientId=c2.id, adminId=0, inactive=0, type='TempBan', timeExpire=-1, data='pG').save(self.console)

        def assertPenalties(client, types, penalties_in=[], penalties_notin=[]):
            penalties = self.storage.getClientPenalties(client=client, type=types)
            self.assertIsInstance(penalties, list)
            bucket = []
            for i in penalties:
                self.assertIsInstance(i, Penalty)
                self.assertEqual(i.clientId, client.id)
                bucket.append(i.data)
            for i in penalties_in:
                self.assertIn(i, bucket)
            for i in penalties_notin:
                self.assertNotIn(i, bucket)

        assertPenalties(client=c1, types=('Ban', 'TempBan', 'Kick', 'Warning', 'Notice'), penalties_in=('pB','pC'), penalties_notin=('pA','pD','pE','pF','pG'))
        assertPenalties(client=c2, types=('Ban', 'TempBan', 'Kick', 'Warning', 'Notice'), penalties_in=('pF','pG'), penalties_notin=('pA','pB','pC','pD','pE'))
    def it_can_return_a_django_m2m_relationship_as_collection(self):
        DjangoModel = Mock(name="DjangoModel")
        mock_model = Mock()
        mock_model.id = 1
        mock_model.get_absolute_url.return_value = "A"

        OtherModel = Mock(name="OtherMock")
        mock1 = Mock()
        mock1.id = 1
        mock1.get_absolute_url.return_value = "1"
        mock2 = Mock()
        mock2.id = 2
        mock2.get_absolute_url.return_value = "2"

        # This mocks a many2many relation ship, its not a queryset, just a list
        mock_model.others.all.return_value = [mock1, mock2]

        x = [mock2, mock1]

        def mock_side_effect(*args, **kwargs):
            return x.pop()

        OtherModel.objects.get.side_effect = mock_side_effect
        DjangoModel.objects.get.return_value = mock_model

        # Now create a simple document setup
        class OtherDoc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = "django"
                identifier = "id"
                model = OtherModel

        class OtherCollection(Collection):
            document = OtherDoc

        class Doc(Document):
            id = fields.NumberField()
            others = fields.CollectionField(OtherCollection)

            class Meta:
                backend_type = "django"
                identifier = "id"
                model = DjangoModel

        manager = BackendManager("django")
        # The manager needs to know which model it connects to
        # This is normally done when the Document is created.
        manager._model = DjangoModel

        # make sure we are working with correct expectations
        eq_(DjangoBackendManager, type(manager))

        doc = Doc({"id": 1})
        # doc.fetch()

        expected = {"id": 1, "others": [{"id": 1}, {"id": 2}]}
        eq_(expected, manager.fetch(doc))
Пример #14
0
def test_align_target_template():
    target = Mock()
    template = Mock()
    target.id = 'mock_target'
    target.seq = 'YILGDTLGVGGKVKVGKH'
    template.id = 'mock_template'
    template.seq = 'YQNLSPVGSGGSVCAAFD'
    aln = ensembler.modeling.align_target_template(target, template, substitution_matrix='gonnet')
    assert aln == [('YILGDTLGVGGKVKVGKH', 'YQNLSPVGSGGSVCAAFD', 18.099999999999998, 0, 18)]
    aln2 = ensembler.modeling.align_target_template(target, template, substitution_matrix='blosum62')
    assert aln2 == [('YILGDTLGVGGKVKVGKH', 'YQNLSPVGSGGSVCAAFD', 10.0, 0, 18)]
Пример #15
0
 def test_should_post_only_first_status_on_first_query(self, m_time,
                                                       m_post):
     api = Mock()
     status = Mock()
     status.id = 2
     status2 = Mock()
     status2.id = 1
     api.GetSearch.return_value = [status, status2]
     ct = Chantweep(Mock(), api, '#foo', 'foo', search_interval=30)
     ct._query_twitter()
     m_post.assert_called_with(status)
     self.assertEqual(m_post.call_count, 1)
Пример #16
0
 def test_allocations (self):
     project_1 = Mock(['id'])
     project_1.id = "1"
     project_2 = Mock(['id'])
     project_2.id = "2"
     resource = Mock(['id'])
     resource.id = "1"
     dt = datetime(2000, 1, 1)
     Session.add(Allocation(project_1, resource, 0, dt, dt))
     Session.add(Allocation(project_2, resource, 0, dt, dt))
     assert_equal(
         set(get_projects()),
         set([Project.cached("1"), Project.cached("2")]))
Пример #17
0
 def test_manager_projects (self):
     project_1 = Mock(['id'])
     project_1.id = "1"
     project_2 = Mock(['id'])
     project_2.id = "2"
     resource = Mock(['id'])
     resource.id = "1"
     dt = datetime(2000, 1, 1)
     Session.add(Allocation(project_1, resource, 0, dt, dt))
     Session.add(Allocation(project_2, resource, 0, dt, dt))
     assert_equal(
         get_projects(manager=User.cached("1")),
         [Project.cached("1")])
Пример #18
0
    def test_get_latest_taupage_image_id_returns_id_of_eldest_image(self, get_taupage_images_mock, _):
        image_1 = Mock(spec=Image)
        image_1.id = "image1"
        image_1.creationDate = datetime.datetime(2015, 1, 6, 15, 1, 24, 78915)
        image_2 = Mock(spec=Image)
        image_2.id = "image2"
        image_2.creationDate = datetime.datetime(2015, 1, 6, 15, 8, 24, 78915)
        image_3 = Mock(spec=Image)
        image_3.id = "image3"
        image_3.creationDate = datetime.datetime(2015, 1, 6, 15, 7, 24, 78915)

        get_taupage_images_mock.return_value = [image_1, image_2, image_3]

        self.assertEqual("image2", Ec2Api().get_latest_taupage_image_id())
Пример #19
0
    def test_we_can_get_all_instances(self, mock_landlord, mock_ec2):
        persistence.save('Instance1', 'v43')
        persistence.save('Instance2', 'v43')
        mock_landlord.Tenant = StubLandlord
        mock_connection = Mock()
        mock_ec2.connect_to_region.return_value = mock_connection

        instance1 = Mock()
        instance1.id = 'i-938372'
        instance1.dns_name = '192.1.11.1.dnsname'
        instance1.ip_address = '192.1.11.1'
        instance1.state = 'running'
        instance1.tags = {'Name': 'STAGE-Instance-1', 'Project': 'Instance', 'Version': 'v43', 'AutoStopped': 'True'}
        instance1.launch_time = datetime.date.today().isoformat()
        instance1.image_id = 'ami-192812'

        instance2 = Mock()
        instance2.id = 'i-542211'
        instance2.dns_name = '192.5.5.5.dnsname'
        instance2.ip_address = '192.5.5.5'
        instance2.state = 'stopped'
        instance2.tags = {'Name': 'Instance2', 'Project': 'Instance', 'Version': 'v43'}
        instance2.launch_time = datetime.date.today().isoformat()
        instance2.image_id = 'ami-237829'

        mock_connection.get_only_instances.return_value = [instance1, instance2]

        instances = ec2.get_all_instances()

        mock_ec2.connect_to_region.assert_called_with('eu-west-1', aws_access_key_id='aws.id',
                                                      aws_secret_access_key='aws.secret')
        mock_connection.get_only_instances.assert_called_with(filters={"tag:Deployer": "igor"})
        self.assertEquals(len(instances), 2)
        self.assertEquals(instances[0]['name'], 'Instance-1')
        self.assertEquals(instances[0]['version'], 'v43')
        self.assertEquals(instances[0]['project'], 'Instance')
        self.assertEquals(instances[0]['date'], datetime.date.today().isoformat())
        self.assertEquals(instances[0]['ip'], '192.1.11.1')
        self.assertEquals(instances[0]['status'], 'running')
        self.assertEquals(instances[0]['autoStopped'], 'True')

        self.assertEquals(instances[1]['name'], 'Instance2')
        self.assertEquals(instances[1]['version'], 'v43')
        self.assertEquals(instances[1]['project'], 'Instance')
        self.assertEquals(instances[1]['date'], datetime.date.today().isoformat())
        self.assertEquals(instances[1]['ip'], '192.5.5.5')
        self.assertEquals(instances[1]['status'], 'stopped')
        self.assertEquals(instances[1]['ami'], 'ami-237829')
        self.assertEquals(instances[1]['autoStopped'], 'NA')
Пример #20
0
    def test_create_consumer_payload(self):
        local_distributor = YumHTTPDistributor()
        repo = Mock()
        repo.display_name = 'foo'
        repo.id = 'bar'
        config = {'https_ca': 'pear',
                  'gpgkey': 'kiwi',
                  'auth_cert': 'durian',
                  'auth_ca': True,
                  'http': True,
                  'https': True}
        binding_config = {}
        pulp_server_config.set('server', 'server_name', 'apple')
        cert_file = os.path.join(self.working_dir, "orange_file")
        with open(cert_file, 'w') as filewriter:
            filewriter.write("orange")

        pulp_server_config.set('security', 'ssl_ca_certificate', cert_file)

        result = local_distributor.create_consumer_payload(repo, config, binding_config)

        target = {
            'server_name': 'apple',
            'ca_cert': 'orange',
            'relative_path': '/pulp/repos/bar',
            'gpg_keys': {'pulp.key': 'kiwi'},
            'client_cert': 'durian',
            'protocols': ['http', 'https'],
            'repo_name': 'foo'
        }
        compare_dict(result, target)
Пример #21
0
    def test_kill_run(self, datetime, kill_pid_tree_mock):
        """
        Test :func:`.kill_run`.
        """
        event_queue = Mock()
        kill_request = Mock()
        kill_request.id = 1234
        kill_request.run.pid = 5678

        dts = datetime.now.return_value.isoformat.return_value

        kill_queue = Queue()
        kill_queue.put(kill_request)
        exit_queue = Mock()

        exit_queue_return = [Empty, None]

        def exit_queue_side_effect(*args, **kwargs):
            value = exit_queue_return.pop(0)
            if callable(value):
                raise value()

        exit_queue.get.side_effect = exit_queue_side_effect

        kill_run(kill_queue, event_queue, exit_queue)

        kill_pid_tree_mock.assert_called_with(5678)
        kill_request.patch.assert_called_with({
            'execute_dts': dts,
        })
        event_queue.put.assert_called_with((
            '{"kill_request_id": 1234, "kind": "kill_request", '
            '"event": "executed"}'
        ))
Пример #22
0
    def test__handle_enqueue_action(self, Run, datetime, config):
        """
        Test :func:`._handle_enqueue_action`.
        """
        run_queue = Mock()
        event_queue = Mock()

        run = Mock()
        run.id = 1234
        run.enqueue_dts = None
        Run.return_value = run

        message = {
            'action': 'enqueue',
            'run_id': 1234,
        }

        _handle_enqueue_action(message, run_queue, event_queue)

        run.patch.assert_called_once_with({
            'enqueue_dts': datetime.now.return_value.isoformat.return_value
        })
        run_queue.put.assert_called_once_with(run)
        event_queue.put.assert_called_once_with(
            '{"kind": "run", "event": "enqueued", "run_id": 1234}')
        datetime.now.assert_called_with(utc)
Пример #23
0
def get_test_exhibits_window():
    exhibit_banner = exhibits.ExhibitBanner()

    exhibits_list = [exhibits.FeaturedExhibit()]
    for (i, (title, url)) in enumerate([
        ("1 some title", "https://wiki.ubuntu.com/Brand?"
            "action=AttachFile&do=get&target=orangeubuntulogo.png"),
        ("2 another title", "https://wiki.ubuntu.com/Brand?"
            "action=AttachFile&do=get&target=blackeubuntulogo.png"),
        ("3 yet another title", "https://wiki.ubuntu.com/Brand?"
            "action=AttachFile&do=get&target=xubuntu.png"),
        ]):
        exhibit = Mock()
        exhibit.id = i
        exhibit.package_names = "apt,2vcard"
        exhibit.published = True
        exhibit.style = "some uri to html"
        exhibit.title_translated = title
        exhibit.banner_url = url
        exhibit.html = None
        exhibits_list.append(exhibit)

    exhibit_banner.set_exhibits(exhibits_list)

    scroll = Gtk.ScrolledWindow()
    scroll.add_with_viewport(exhibit_banner)

    win = get_test_window(child=scroll)
    return win
Пример #24
0
 def test_numPenalties(self):
     c1 = Mock()
     c1.id = 15
     c2 = Mock()
     c2.id = 18
     Penalty(clientId=c1.id, adminId=0, timeExpire=-1, type='Ban', inactive=1, data='pA').save(self.console)
     Penalty(clientId=c1.id, adminId=0, timeExpire=-1, type='Ban', inactive=0, data='pB').save(self.console)
     Penalty(clientId=c1.id, adminId=0, timeExpire=-1, type='Warning', inactive=0, data='pC').save(self.console)
     Penalty(clientId=c1.id, adminId=0, timeExpire=-1, type='Kick', inactive=0, data='pD').save(self.console)
     Penalty(clientId=c2.id, adminId=0, timeExpire=-1, type='Notice', inactive=0, data='pE').save(self.console)
     Penalty(clientId=c2.id, adminId=0, timeExpire=-1, type='Warning', inactive=0, data='pF').save(self.console)
     Penalty(clientId=c1.id, adminId=0, timeExpire=-1, type='TempBan', inactive=0, data='pG').save(self.console)
     self.assertEqual(1, self.storage.numPenalties(client=c1))
     self.assertEqual(4, self.storage.numPenalties(client=c1, type=('Ban', 'TempBan', 'Kick', 'Warning', 'Notice')))
     self.assertEqual(0, self.storage.numPenalties(client=c2))
     self.assertEqual(2, self.storage.numPenalties(client=c2, type=('Ban', 'TempBan', 'Kick', 'Warning', 'Notice')))
    def test_destroyVirtualMachineCommand(self):
        content = Mock()
        si = create_autospec(spec=vim.ServiceInstance)
        si.RetrieveContent = Mock(return_value=content)

        pvService = Mock()
        pvService.connect = Mock(return_value=si)
        pvService.destroy_vm_by_name = MagicMock()

        csRetrieverService = Mock()
        csRetrieverService.getVCenterTemplateAttributeData = Mock(return_value=VCenterTemplateModel(template_name='test', vm_folder='Alex', vCenter_resource_name='vCenter'))
        csRetrieverService.getPowerStateAttributeData = Mock(return_value=True)
        csRetrieverService.getVMClusterAttributeData = Mock(return_value=VMClusterModel(cluster_name="cluster1", resource_pool="resourcePool1"))
        csRetrieverService.getVMStorageAttributeData = Mock(return_value="datastore")
        csRetrieverService.getVCenterConnectionDetails = Mock(return_value={"vCenter_url": "vCenter","user":"******","password":"******"})

        resource_att = Mock()
        vm_name = Mock(return_value='test')
        resource_att.name = vm_name
        helpers.get_resource_context_details = Mock(return_value=resource_att)
        helpers.get_api_session = Mock()

        context_att = Mock()
        vm_id = Mock(return_value='id')
        context_att.id = vm_id
        helpers.get_reservation_context_details = Mock(return_value=context_att)

        command = DestroyVirtualMachineCommand(pvService, csRetrieverService)
        command.execute()

        self.assertTrue(pvService.connect.called)
        self.assertTrue(pvService.destroy_vm_by_name.called)
        self.assertTrue(si.RetrieveContent.called)
        pvService.destroy_vm_by_name.assert_called_with(content, si, vm_name)
        self.assertTrue(helpers.get_api_session().DeleteResource.called)
 def test_should_allow_authorized_user_to_add_project(self):
     project = Mock()
     project.is_parent_project.return_value = True
     project.id = 3
     mock_user = object()
     project.is_editable_by.return_value = True
     self.assertTrue(project_tags.add_sub_project_link(project, mock_user).__contains__('/add_project?parent_id='))
 def test_should_not_provide_add_sub_projects_link_for_sub_projects(self):
     project = Mock()
     project.is_parent_project.return_value = False
     project.id = 3
     mock_user = object()
     project.is_editable_by.return_value = True
     self.assertEquals(project_tags.add_sub_project_link(project, mock_user), '')
Пример #28
0
    def makeInstance(self, tablename='users', id=1):
        """Return a mock model instance."""

        instance = Mock()
        instance.__tablename__ = tablename
        instance.id = id
        return instance
Пример #29
0
    def test_that_the_venue_for_an_existing_event_is_returned(self):
        mock_event = Mock()
        mock_event.id = 1
        mock_venue = Mock()
        mock_event.venue = mock_venue

        eq_(self.importer.venue_for_event(mock_event), mock_venue)
Пример #30
0
    def test__handle_kill_action(self, KillRequest, datetime, config):
        """
        Test :func:`._handle_kill_action`.
        """
        config.get.return_value = 'foo'

        kill_queue = Mock()
        event_queue = Mock()

        kill_request = Mock()
        kill_request.id = 1234
        kill_request.enqueue_dts = None
        KillRequest.return_value = kill_request

        message = {
            'action': 'kill',
            'kill_request_id': 1234,
        }

        _handle_kill_action(message, kill_queue, event_queue)

        kill_request.patch.assert_called_with({
            'enqueue_dts': datetime.now.return_value.isoformat.return_value
        })
        event_queue.put.assert_called_once_with((
            '{"kill_request_id": 1234, "kind": "kill_request", '
            '"event": "enqueued"}'
        ))
        datetime.now.assert_called_once_with(utc)
Пример #31
0
    def test_get_user_stack_status_launch_failure(self):
        self.init_block()

        mock_result = Mock()
        mock_result.id = "bogus_task_id"
        mock_result.ready.return_value = True
        mock_result.successful.return_value = False
        mock_launch_stack_task = Mock(return_value=mock_result)

        with patch.multiple(self.block,
                            launch_stack_task=mock_launch_stack_task):
            data = {"initialize": True, "reset": False}
            response = self.call_handler("get_user_stack_status", data)

        self.assertTrue(mock_launch_stack_task.called)
        self.assertEqual(response["status"], "LAUNCH_ERROR")
Пример #32
0
    def test_get_user_stack_status_reset(self):
        self.init_block()
        self.update_stack({"status": "RESUME_FAILED"})

        mock_result = Mock()
        mock_result.id = 'bogus_task_id'
        mock_result.ready.return_value = False
        mock_launch_stack_task = Mock(return_value=mock_result)

        with patch.multiple(self.block,
                            launch_stack_task=mock_launch_stack_task):
            data = {"initialize": False, "reset": True}
            response = self.call_handler("get_user_stack_status", data)

        self.assertTrue(mock_launch_stack_task.called)
        self.assertEqual(response["status"], "LAUNCH_PENDING")
Пример #33
0
    def test_add_queue(self, fake_queue, fake_listener):
        fake_source = Mock()
        fake_source.id = 'fake-id'
        fake_queue().downloader = Mock()

        # test
        batch = Threaded(None, None, None, None)
        queue = batch._add_queue(fake_source)

        # validation
        fake_queue.assert_called_with(fake_source)
        fake_listener.assert_called_with(batch)
        fake_queue().start.assert_called_with()
        self.assertEqual(fake_queue().downloader.event_listener, fake_listener())
        self.assertEqual(batch.queues[fake_source.id], fake_queue())
        self.assertEqual(queue, fake_queue())
Пример #34
0
    def test_find_queue(self, fake_add, fake_lock):
        fake_source = Mock()
        fake_source.id = 'fake-id'
        fake_lock.__enter__ = Mock()
        fake_lock.__exit__ = Mock()

        # test
        canceled = Mock()
        canceled.is_set.return_value = False
        batch = Batch(canceled, None, None, None, None)
        batch.queues[fake_source.id] = Mock()
        queue = batch.find_queue(fake_source)

        # validation
        self.assertFalse(fake_add.called)
        self.assertEqual(queue, batch.queues[fake_source.id])
Пример #35
0
def test_magic_methods(player_service):
    player = Mock()
    player.id = 0
    player_service[0] = player

    assert len(player_service) == 1
    assert list(iter(player_service)) == [player]
    assert player_service[0] is player
    assert player_service.get_player(0) is player

    player_service.remove_player(player)

    assert len(player_service) == 0
    assert list(iter(player_service)) == []
    assert player_service[0] is None
    assert player_service.get_player(0) is None
Пример #36
0
 def test_with_addon(self):
     addon = Mock()
     addon.name = 'Firebug'
     addon.id = 1843
     s = render("""{{ dev_breadcrumbs(addon) }}""", {
         'request': self.request,
         'addon': addon
     })
     doc = pq(s)
     crumbs = doc('li')
     assert crumbs.text() == 'Developer Hub My Submissions Firebug'
     assert crumbs.eq(1).text() == 'My Submissions'
     assert crumbs.eq(1).children('a').attr('href') == (
         reverse('devhub.addons'))
     assert crumbs.eq(2).text() == 'Firebug'
     assert crumbs.eq(2).children('a') == []
Пример #37
0
def get_submission(task=None, participation=None, sr=None, scored=True):
    task = task if task is not None else get_task()
    participation = participation if participation is not None \
        else get_participation()
    sr = sr if sr is not None else get_sr(scored=scored)

    submission = Mock()
    submission.timestamp = make_datetime(get_int(2 ** 11 + 2 ** 8, 2 ** 11))
    submission.tokened.return_value = False

    submission.get_result.return_value = sr
    submission.participation = participation
    submission.task = task

    submission.id = get_int()
    return submission
Пример #38
0
 def test_show_cluster_instance(self,
                                mock_cluster_load_instance,
                                mock_cluster_load):
     tenant_id = Mock()
     cluster_id = Mock()
     instance_id = Mock()
     context = trove_testtools.TroveTestContext(self)
     req = Mock()
     req.environ = Mock()
     req.environ.__getitem__ = Mock(return_value=context)
     cluster = Mock()
     mock_cluster_load.return_value = cluster
     cluster.id = cluster_id
     self.controller.show_instance(req, tenant_id, cluster_id, instance_id)
     mock_cluster_load_instance.assert_called_with(context, cluster.id,
                                                   instance_id)
    def test_associate_onu(self):
        with patch.object(ServiceInstance.objects, "get") as get_si, \
            patch.object(ONUDevice.objects, "get") as get_onu:

            mock_si = Mock()
            mock_si.get_westbound_service_instance_properties.return_value = "BRCM1234"
            get_si.return_value = mock_si

            mock_onu = Mock()
            mock_onu.id = 12
            get_onu.return_value = mock_onu

            self.policy.associate_onu_device(self.si)

            self.assertEqual(self.si.onu_device_id, mock_onu.id)
            self.si.save.assert_called()
Пример #40
0
    def test_validate_c_tag_on_update_fail(self):
        s = Mock()
        s.c_tag = 222
        s.onu_device = "BRCM1234"
        s.id = 2

        self.models_decl.RCORDSubscriber_decl.objects.filter.return_value = [s]

        self.rcord_subscriber.id = 1
        self.rcord_subscriber.is_new = False
        self.rcord_subscriber.c_tag = 222
        with self.assertRaises(Exception) as e:
            self.rcord_subscriber.save()

        self.assertEqual(e.exception.message, "The c_tag you specified (222) has already been used on device BRCM1234")
        self.models_decl.RCORDSubscriber_decl.save.assert_not_called()
Пример #41
0
    def test_get_layout(self, get_action_method, get_template_method):
        with app.app_context():
            mock_action = Mock()
            mock_action.actionType.name.return_value = 'test'
            mock_action.actionType.property_types = MagicMock()

            template = {
                'tag':
                'root',
                'attrs': {
                    'title': mock_action.actionType.name.return_value
                },
                'children': [{
                    'tag': 'ap',
                    'primary': 1,
                    'attrs': {
                        'cols': 2
                    }
                }, {
                    'tag': 'ap',
                    'primary': 2,
                    'attrs': {
                        'cols': 2
                    }
                }]
            }

            assert_result = deepcopy(template)
            property_types = []
            for i in xrange(1, 6):
                property_type = Mock()
                property_type.id = i
                property_types.append(property_type)
                if i > 2:
                    assert_result['children'].append({
                        'tag': 'ap',
                        'primary': i
                    })

            mock_action.actionType.property_types.__iter__.return_value = property_types

            get_action_method.return_value = mock_action
            get_template_method.return_value = template

            layout = apt_layout.APTLayout(-1)
            result = layout.get_layout()
            self.assertDictEqual(assert_result, result)
Пример #42
0
    def test_save_output_directory(self, mock_walk, mock_rename, dataset_mock):
        """Simulate saving a directory output called "datafiles/" with the following structure:

        /tmp/runsandbox/output/
        └── datafiles/
            ├── a.txt
            ├── b.txt
            └── morefiles/
                └── c.txt
        """
        from pathlib import Path

        run = Mock()
        run.id = 9981
        argument = Mock()
        argument.name = "datafiles"
        output_path = "/tmp/runsandbox/output/"
        upload_path = "/tmp/runsandbox/upload"

        dataset_mock.create_dataset = Mock(return_value=Mock())

        runcontainer.Command._save_output_directory_argument(
            run,
            argument,
            output_path,
            upload_path,
        )

        mock_walk.assert_called_with(Path("/tmp/runsandbox/output/datafiles"))

        mock_rename.assert_has_calls(
            [
                call(
                    Path("/tmp/runsandbox/output/datafiles/a.txt"),
                    "/tmp/runsandbox/upload/datafiles__a_9981.txt",
                ),
                call(
                    Path("/tmp/runsandbox/output/datafiles/b.txt"),
                    "/tmp/runsandbox/upload/datafiles__b_9981.txt",
                ),
                call(
                    Path("/tmp/runsandbox/output/datafiles/subdir/c.txt"),
                    "/tmp/runsandbox/upload/datafiles__subdir__c_9981.txt",
                ),
            ],
            any_order=True,
        )
Пример #43
0
 def test_with_app(self):
     product = Mock()
     product.name = 'Steamcube'
     product.id = 9999
     product.app_slug = 'scube'
     s = render("""{{ hub_breadcrumbs(product) }}""", {
         'request': self.request,
         'product': product
     })
     crumbs = pq(s)('li')
     expected = [
         ('Home', reverse('home')),
         ('Developers', reverse('ecosystem.landing')),
         ('My Submissions', reverse('mkt.developers.apps')),
         ('Steamcube', None),
     ]
     mkt.site.tests.check_links(expected, crumbs, verify=False)
Пример #44
0
    def test_delete_vehicle(self):
        client = Mock()
        vehicle = Mock()
        vehicle.id = 2
        client.get_world.return_value.get_actor.return_value = vehicle

        delete_vehicle(client, vehicle.id)

        self.assertEqual([
            call.get_world(),
            call.get_world().wait_for_tick(),
            call.get_world().get_actor(2),
            call.get_world().wait_for_tick(),
            call.get_world().get_actor().destroy(),
            call.get_world(),
            call.get_world().wait_for_tick()
        ], client.mock_calls)
Пример #45
0
    def test_find_queue_not_found(self, fake_add, fake_lock):
        fake_source = Mock()
        fake_source.id = 'fake-id'
        fake_lock.__enter__ = Mock()
        fake_lock.__exit__ = Mock()

        # test
        canceled = Mock()
        canceled.is_set.return_value = False
        batch = Batch(canceled, None, None, None, None)
        queue = batch.find_queue(fake_source)

        # validation
        fake_add.assert_called_with(fake_source)
        self.assertEqual(batch._mutex.__enter__.call_count, 1)
        self.assertEqual(batch._mutex.__exit__.call_count, 1)
        self.assertEqual(queue, fake_add())
Пример #46
0
    def test_no_multiple_answers_no_request(self, manage_addSurveyAnswer):
        survey = self.survey
        survey.allow_multiple_answers = False
        old_answer = Mock()
        old_answer.id = '12345'
        survey.getAnswerForRespondent = Mock(return_value=old_answer)
        survey._delObject = Mock()

        survey.addSurveyAnswer()

        survey._delObject.assert_called_with('12345')
        manage_addSurveyAnswer.assert_called_with(survey, {},
                                                  REQUEST=None,
                                                  draft=False,
                                                  id=None,
                                                  respondent=None,
                                                  creation_date=None)
Пример #47
0
 def fake_job(self):
     job = Mock(Job)
     job.id = 'foo'
     job.description = ""
     job.ms_filename = ""
     job.dir = '/somedir/foo'
     job.state = 'STOPPED'
     job.db = Mock(JobDb)
     job.db.runInfo.return_value = 'bla'
     job.db.maxMSLevel.return_value = 3
     job.db.molecules.return_value = {'total': 3, 'rows': [1, 2, 3]}
     job.db.moleculesTotalCount.return_value = 3
     job.db.scansWithMolecules.return_value = [4, 5]
     job.db.chromatogram.return_value = [1, 2, 3]
     job.db.extractedIonChromatogram.return_value = [1, 2, 3]
     job.db.fragments.return_value = [1, 2, 3]
     return job
Пример #48
0
    def test_create_consumer_payload_global_auth(self, mock_load_config):
        test_distributor = YumHTTPDistributor()
        repo = Mock()
        repo.display_name = 'foo'
        repo.id = 'bar'
        config = {
            'https_ca': 'pear',
            'gpgkey': 'kiwi',
            'http': True,
            'https': True
        }
        binding_config = {}

        repo_auth_config = ConfigParser.SafeConfigParser()
        repo_auth_config.add_section('repos')
        repo_auth_config.set('repos', 'global_cert_location', self.working_dir)
        mock_load_config.return_value = repo_auth_config

        with open(os.path.join(self.working_dir, 'pulp-global-repo.cert'),
                  'w+') as cert_file:
            cert_file.write('cert')
        with open(os.path.join(self.working_dir, 'pulp-global-repo.key'),
                  'w+') as cert_file:
            cert_file.write('key')
        with open(os.path.join(self.working_dir, 'pulp-global-repo.ca'),
                  'w+') as cert_file:
            cert_file.write('ca')

        result = test_distributor.create_consumer_payload(
            repo, config, binding_config)

        target = {
            'server_name': 'apple',
            'ca_cert': 'pear',
            'relative_path': '/pulp/repos/bar',
            'gpg_keys': {
                'pulp.key': 'kiwi'
            },
            'protocols': ['http', 'https'],
            'repo_name': 'foo',
            'client_cert': None,
            'global_auth_cert': 'cert',
            'global_auth_key': 'key',
            'global_auth_ca': 'ca'
        }
        compare_dict(result, target)
Пример #49
0
    def test__get_query_in_campaign_push__push_rule__query_to_push(self):
        # Arrange
        game = Mock()
        game.id = 1

        campaign = Mock()
        campaign.countries_codes = ["BR", "AR"]

        push = Mock()
        push.rule.campaign = campaign
        push.rule.game = game

        # Act
        query = AsyncAlertsStartedCampaign().get_query_to_campaign_push(push)

        # Assert
        self.assertDictEqual(query, {"regions": "BR,AR", "games": "1"})
Пример #50
0
    def test_delete_port(self, m):
        # create a mock SwitchPort instance
        port = Mock()
        port.id = 1
        port.tologdict.return_value = {}
        port.host_learning = True
        port.switch.ofId = "of:1234"
        port.portId = "1"

        key = urllib.quote("of:1234/1", safe='')
        m.delete("http://onos-fabric:8181/onos/v1/network/configuration/ports/%s" % key,
                 status_code=204)

        with patch.object(Service.objects, "get") as onos_fabric_get:
            onos_fabric_get.return_value = self.fabric
            self.sync_step(model_accessor=self.model_accessor).delete_record(port)
            self.assertTrue(m.called)
Пример #51
0
    def test_should_send_correct_email_in_html_format_in_english_to_a_newly_created_user(
            self):
        site = get_current_site(None)
        user = Mock(spec=User)
        user.email = '*****@*****.**'
        user.id = 1
        user.first_name = "test"
        language_code = "en"

        request = Mock()
        request.user.first_name = "rakoto"

        with patch(
                "django.contrib.auth.tokens.default_token_generator.make_token"
        ) as make_token:
            make_token.return_value = "token"
            send_email_to_data_sender(user,
                                      language_code,
                                      type="created_user",
                                      request=request)
            emails = [mail.outbox.pop() for i in range(len(mail.outbox))]

            self.assertEqual(1, len(emails))
            sent_email = emails[0]

            self.assertEqual("html", sent_email.content_subtype)
            self.assertEqual(settings.EMAIL_HOST_USER, sent_email.from_email)
            self.assertEqual(['*****@*****.**'], sent_email.to)
            self.assertEqual([settings.HNI_SUPPORT_EMAIL_ID], sent_email.bcc)
            ctx_dict = {
                'domain': site.domain,
                'uid': int_to_base36(user.id),
                'user': user,
                'token': "token",
                'protocol': 'http',
                'creator_user': request.user.first_name,
                'site': site,
                'account_type': 'Pro SMS',
            }
            self.assertEqual(
                render_to_string(
                    'registration/created_user_email_subject_en.txt') %
                site.domain, sent_email.subject)
            self.assertEqual(
                render_to_string('registration/created_user_email_en.html',
                                 ctx_dict), sent_email.body)
Пример #52
0
    def setUp(self):
        self.stack_states = {
            'CREATE_IN_PROGRESS', 'CREATE_FAILED', 'CREATE_COMPLETE',
            'SUSPEND_IN_PROGRESS', 'SUSPEND_FAILED', 'SUSPEND_COMPLETE',
            'RESUME_IN_PROGRESS', 'RESUME_FAILED', 'RESUME_COMPLETE',
            'DELETE_IN_PROGRESS', 'DELETE_FAILED', 'DELETE_COMPLETE'
        }

        # Create a set of mock stacks to be returned by the heat client mock.
        self.stacks = {}
        for state in self.stack_states:
            stack = Mock()
            stack.stack_status = state
            stack.id = "%s_ID" % state
            self.stacks[state] = stack

        # Mock settings
        self.configuration = {
            "suspend_timeout": 120,
            "suspend_concurrency": 1,
            "suspend_in_parallel": False,
            "delete_age": 14,
            "delete_attempts": 3,
            "task_timeouts": {
                "sleep": 0,
                "retries": 10
            },
            "credentials": {
                "os_auth_url": "bogus_auth_url",
                "os_auth_token": "",
                "os_username": "******",
                "os_password": "******",
                "os_user_id": "",
                "os_user_domain_id": "",
                "os_user_domain_name": "",
                "os_project_id": "bogus_project_id",
                "os_project_name": "",
                "os_project_domain_id": "",
                "os_project_domain_name": "",
                "os_region_name": "bogus_region_name"
            }
        }
        self.student_id = 'bogus_student_id'
        self.course_id = 'bogus_course_id'
        self.stack_name = 'bogus_stack_name'
Пример #53
0
    def test_customer_create_call(self, mock_customer_module):
        mock_customer = Mock()
        mock_customer.id = 'cus_%s' % uuid().hex
        mock_customer_module.create.return_value = mock_customer

        token = uuid().hex

        stripe_customer = payment.StripeCustomer(None)
        stripe_user_id = stripe_customer.token_for_customer(token, self.user)

        exp_kwargs = dict(description='Poold user: %s' % self.user.id,
                          card=token,
                          email=self.user.email)
        mock_customer_module.create.assert_called_once_with(api_key=None,
                                                            **exp_kwargs)
        assert_equal(mock_customer.id, stripe_user_id)
        self.patched_logger.transaction.assert_called_once_with(
            'New Stripe Customer Created', **exp_kwargs)
Пример #54
0
def _create_mock_contact_message(mock_pk=1, mock_name="message name", mock_email="*****@*****.**",
                                 mock_content="lorem ipsum dolor sit amet "):
    """

    :param mock_pk:
    :param mock_name:
    :param mock_email:
    :param mock_content:

    :return:
    """
    mock_message = Mock(spec=ContactMessage)
    mock_message.id = mock_pk
    mock_message.name = mock_name
    mock_message.email = mock_email
    mock_message.content = mock_content

    return mock_message
Пример #55
0
    def test_delete_sensor(self):
        client = Mock()
        sensor = Mock()
        sensor.id = 2
        client.get_world.return_value.get_actor.return_value = sensor

        delete_sensor(client, sensor.id)

        self.assertEqual(
            [call.get_world(),
                call.get_world().wait_for_tick(),
                call.get_world().get_actor(2),
                call.get_world().wait_for_tick(),
                call.get_world().get_actor().destroy(),
                call.get_world(),
                call.get_world().wait_for_tick()],
            client.mock_calls
        )
Пример #56
0
def test_s3_backed_store_handler_store(mock_write_communication_to_buffer,
                                       mock_prefix_s3_key):
    key = Mock()
    bucket = Mock(get_key=Mock(side_effect=[key]))

    comm = Mock()
    comm.id = sentinel.comm_id
    handler = S3BackedStoreHandler(bucket, sentinel.prefix_len)

    mock_prefix_s3_key.side_effect = [sentinel.prefixed_key]
    mock_write_communication_to_buffer.side_effect = [sentinel.buf]
    handler.store(comm)
    bucket.get_key.assert_called_once_with(sentinel.prefixed_key,
                                           validate=False)
    mock_prefix_s3_key.assert_called_once_with(sentinel.comm_id,
                                               sentinel.prefix_len)
    mock_write_communication_to_buffer.assert_called_once_with(comm)
    key.set_contents_from_string.assert_called_once_with(sentinel.buf)
Пример #57
0
    def test_construction(self, fake_queue, fake_setDaemon):
        source = Mock()
        source.id = 'fake_id'
        source.max_concurrent = 10

        # test
        canceled = Mock()
        canceled.is_set.return_value = False
        queue = RequestQueue(canceled, source)
        queue.setDaemon = Mock()

        # validation
        fake_queue.assert_called_with(source.max_concurrent)
        fake_setDaemon.assert_called_with(True)
        self.assertEqual(queue._halted, False)
        self.assertEqual(queue.canceled, canceled)
        self.assertEqual(queue.queue, fake_queue())
        self.assertEqual(queue.downloader, source.get_downloader())
Пример #58
0
    def test_execute_no_shebang(self, config, datetime, RunLog):
        """
        Test :func:`.execute_run` when the shebang is invalid.
        """
        config.get.return_value = '/tmp'

        run = Mock()
        run.run_log = None
        run.id = 1234
        run.job.script_content = (
            u'I love cheese\n\necho "H\xe9llo World!";\n')

        event_queue = Mock()
        exit_queue = Mock()
        run_queue = Queue()
        run_queue.put(run)

        exit_queue_return = [Empty, None]

        def exit_queue_side_effect(*args, **kwargs):
            value = exit_queue_return.pop(0)
            if callable(value):
                raise value()

        exit_queue.get.side_effect = exit_queue_side_effect

        execute_run(run_queue, event_queue, exit_queue)

        dts = datetime.now.return_value.isoformat.return_value

        self.assertEqual(dts, run.patch.call_args_list[0][0][0]['start_dts'])
        log_out = RunLog.return_value.post.call_args_list[0][0][0]['content']
        self.assertTrue(
            log_out.startswith('[job runner worker] Could not execute job:'))
        self.assertEqual(
            [call({
                'return_dts': dts,
                'return_success': False,
            })], run.patch.call_args_list[1:])
        self.assertEqual([
            call('{"kind": "run", "event": "started", "run_id": 1234}'),
            call('{"kind": "run", "event": "returned", "run_id": 1234}'),
        ], event_queue.put.call_args_list)
        datetime.now.assert_called_with(utc)
Пример #59
0
 def test_getClientFirstPenalty(self):
     client = Mock()
     client.id = 15
     self.storage.setClientPenalty(Penalty(clientId=client.id, adminId=0, timeAdd=2, timeExpire=-1, type='Ban', data='pA'))
     self.storage.setClientPenalty(Penalty(clientId=client.id, adminId=0, timeAdd=4, timeExpire=-1, type='Kick', data='pB'))
     self.storage.setClientPenalty(Penalty(clientId=client.id, adminId=0, timeAdd=1, timeExpire=-1, type='Notice', data='pC'))
     self.storage.setClientPenalty(Penalty(clientId=client.id, adminId=0, timeAdd=3, timeExpire=-1, type='Ban', data='pD'))
     self.storage.setClientPenalty(Penalty(clientId=client.id, adminId=0, timeAdd=6, timeExpire=-1, type='Kick', data='pE'))
     self.storage.setClientPenalty(Penalty(clientId=client.id, adminId=0, timeAdd=5, timeExpire=-1, type='Ban', data='pF'))
     penalty = self.storage.getClientFirstPenalty(client=client)
     self.assertIsInstance(penalty, Penalty)
     self.assertEqual(penalty.data, 'pA')
     penalty = self.storage.getClientFirstPenalty(client=client, type=('Ban', 'Kick'))
     self.assertIsInstance(penalty, Penalty)
     self.assertEqual(penalty.data, 'pA')
     penalty = self.storage.getClientFirstPenalty(client=client, type=('Ban', 'Kick','Notice'))
     self.assertIsInstance(penalty, Penalty)
     self.assertEqual(penalty.data, 'pC')
     self.assertIsNone(self.storage.getClientFirstPenalty(Penalty(clientId=3231)))
Пример #60
0
    def test_stop_with_error(self, mocklog):
        self.pm.start()
        self.pm.terminate_process = Mock(side_effect=BadRequest)

        procmock = Mock()
        procmock._proc_start_time = 0
        procmock.id = sentinel.pid
        self.pm.procs[sentinel.pid] = procmock
        self.pm.procs_by_name['dummy'] = procmock

        self.pm.stop()

        self.pm.terminate_process.assert_called_once_with(sentinel.pid)
        mocklog.warn.assert_has_calls([
            call("Failed to terminate process (%s): %s", sentinel.pid, ANY),
            call("ProcManager procs not empty: %s", self.pm.procs),
            call("ProcManager procs_by_name not empty: %s",
                 self.pm.procs_by_name)
        ])