Пример #1
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)
Пример #2
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)
Пример #3
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
Пример #4
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)
Пример #5
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)
Пример #6
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))
Пример #7
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()])
        )
Пример #8
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)
Пример #9
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])
Пример #10
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'))
Пример #11
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)
Пример #12
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)
    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_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")])
Пример #17
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")]))
Пример #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_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)
Пример #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_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)
Пример #23
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')))
Пример #24
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
Пример #25
0
    def makeInstance(self, tablename='users', id=1):
        """Return a mock model instance."""

        instance = Mock()
        instance.__tablename__ = tablename
        instance.id = id
        return instance
 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 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)
Пример #29
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)
    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":"user1","password":"pass1"})

        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)