Example #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)
    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)
Example #3
0
    def testGetSuggestedInstancesTwoSameSize(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.xlarge"
        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": "testId1", "name": "testName1", "namespace": "AWS/EC2", "region": regionMock.name},
                {"id": "testId2", "name": "testName2", "namespace": "AWS/EC2", "region": regionMock.name},
            ],
        )
        getEC2InstancesMock.assert_called_once_with(regionMock.name)
    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)
    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))
Example #7
0
    def test_we_can_get_all_instances_with_region(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.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",
            "StopTime": "8",
            "StartTime": "6",
        }

        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",
            "StopTime": "9",
            "StartTime": "7",
        }

        mock_connection.get_only_instances.return_value = [instance1, instance2]

        instances = ec2.get_all_instances("myRegion")

        mock_ec2.connect_to_region.assert_called_with(
            "myRegion", 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]["stopTime"], "8")
        self.assertEquals(instances[0]["startTime"], "6")
        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[1]["name"], "Instance-2")
        self.assertEquals(instances[1]["version"], "v43")
        self.assertEquals(instances[1]["startTime"], "7")
        self.assertEquals(instances[1]["stopTime"], "9")
        self.assertEquals(instances[1]["project"], "Instance")
        self.assertEquals(instances[1]["date"], datetime.date.today().isoformat())
        self.assertEquals(instances[1]["ip"], "None")
        self.assertEquals(instances[1]["status"], "stopped")
Example #8
0
    def test(self):
        user = Mock()
        user.id = 666

        feed = Mock()
        feed.id = 666

        g = Guesser(feed, user, self.config)
        self.assertEqual(10, 10)
Example #9
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")])
Example #10
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)
Example #11
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")]))
Example #12
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)]
Example #13
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")
Example #14
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())
Example #15
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"),
        )

        self.storage.query = Mock(return_value=None)
        self.assertEquals((), self.storage.getClientPenalties(c1))
Example #16
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)
Example #17
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)))
 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="))
Example #19
0
    def test_context_id_not_None(self):
        product_content = Mock()
        client_handlers = {}
        user_info_cache = Mock()
        favorites_cache = Mock()
        target = Target(
            product_content=product_content,
            client_handlers=client_handlers,
            user_info_cache=user_info_cache,
            favorites_cache=favorites_cache,
        )

        handler = Mock(name="new_client_handler")
        handler.id = "new_id"
        handler.context_id = "context_id_value"
        handler.context_rev = "context_rev_value"

        target.open(handler)
        target.post_context = Mock()

        self.assertEqual(0, target.post_context.call_count)

        self.assertEqual("context_rev_value", handler.context_rev)
        self.assertEqual("context_id_value", handler.context_id)

        self.assertEqual(1, handler.write_message.call_count)
        self.assertDictEqual(
            {"context_id": "context_id_value", "type": "connection_opened"},
            handler.write_message.call_args_list[0][0][0],
        )
    def test_result(self, listdir):
        self.config.add_route("result_file", "/{script}/{taskid}/{filename}")
        self.request.matchdict["script"] = "plot"
        self.request.matchdict["taskid"] = "mytaskid"
        views = Views(self.request)
        task_result = Mock(AsyncResult)
        task_result.id = "mytaskid"
        task_result.ready.return_value = True
        task_result.failed.return_value = False
        views.celery.AsyncResult = Mock(return_value=task_result)
        task = PythonTask()
        task.name = "plot"
        views.celery.tasks = {"plot": task}
        listdir.return_value = ["stderr.txt", "stdout.txt"]

        result = views.result()

        eresult = {
            "result": task_result,
            "files": {"stderr.txt": "/plot/mytaskid/stderr.txt", "stdout.txt": "/plot/mytaskid/stdout.txt"},
            "task": task,
            "result_html": None,
        }
        self.assertEqual(result, eresult)
        listdir.assert_called_with("/tmp/results/mytaskid")
Example #21
0
def get_test_exhibits_window():
    from mock import Mock

    win = Gtk.Window()
    win.set_size_request(600, 200)

    exhibit_banner = ExhibitBanner()

    exhibits_list = [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.add(scroll)

    win.show_all()
    win.connect("destroy", Gtk.main_quit)
    return win
Example #22
0
    def test_metadata_from_package(self):
        """Testing ExtensionInfo metadata from package"""
        app_name = "test_extension.dummy"
        project_name = "DummyExtension"
        module_name = "test_extension.dummy.submodule"
        extension_id = "%s:DummyExtension" % module_name
        htdocs_path = os.path.join(settings.MEDIA_ROOT, "ext", project_name)
        static_path = os.path.join(settings.STATIC_ROOT, "ext", extension_id)

        ext_class = Mock()
        ext_class.__module__ = module_name
        ext_class.id = extension_id
        ext_class.metadata = None

        entrypoint = FakeEntryPoint(ext_class, project_name=project_name)
        extension_info = ExtensionInfo(entrypoint, ext_class)
        metadata = entrypoint.dist.metadata

        self.assertEqual(extension_info.app_name, app_name)
        self.assertEqual(extension_info.author, metadata["Author"])
        self.assertEqual(extension_info.author_email, metadata["Author-email"])
        self.assertEqual(extension_info.description, metadata["Description"])
        self.assertFalse(extension_info.enabled)
        self.assertEqual(extension_info.installed_htdocs_path, htdocs_path)
        self.assertEqual(extension_info.installed_static_path, static_path)
        self.assertFalse(extension_info.installed)
        self.assertEqual(extension_info.license, metadata["License"])
        self.assertEqual(extension_info.metadata, metadata)
        self.assertEqual(extension_info.name, metadata["Name"])
        self.assertEqual(extension_info.summary, metadata["Summary"])
        self.assertEqual(extension_info.url, metadata["Home-page"])
        self.assertEqual(extension_info.version, metadata["Version"])
    def test_submit_job(self, mock_g, mock_n, mock_k, mock_session_post):

        # Mock OpenStack clients and response to POST
        mock_image = {"name": test_image_name, "id": test_image_id}
        mock_gclient = Mock()
        mock_gclient.images = Mock()
        mock_gclient.images.list = Mock(return_value=[mock_image])
        mock_g.return_value = mock_gclient

        mock_flavor = Mock()
        mock_flavor.name = test_flavor_name
        mock_flavor.id = test_flavor_id
        mock_nclient = Mock()
        mock_nclient.flavors = Mock()
        mock_nclient.flavors.list = Mock(return_value=[mock_flavor])
        mock_n.return_value = mock_nclient

        mock_response = Mock()
        mock_response.text = test_job_id
        mock_response.status_code = 200
        mock_session_post.return_value = mock_response

        c = ProcClient(test_auth, host=test_host)

        # good submission using image and flavor names
        c.submit_job(test_job_works, test_image_name, test_flavor_name)
        mock_session_post.assert_called_once_with(test_job_url, params=test_params_works, files=test_files_works)

        mock_session_post.reset_mock()

        # good submission using image and flavor UUIDs
        c.submit_job(test_job_works, test_image_id, test_flavor_id)
        mock_session_post.assert_called_once_with(test_job_url, params=test_params_works, files=test_files_works)

        mock_session_post.reset_mock()

        # With nopost we should not do a POST
        c.submit_job(test_job_works, test_image_name, test_flavor_name, nopost=True)
        self.assertEqual(mock_session_post.call_count, 0)

        # failed submission due to bad image name
        with self.assertRaises(ValueError):
            c.submit_job(test_job_works, "bad_image", test_flavor_name)
        self.assertEqual(mock_session_post.call_count, 0)

        # failed submission due to bad flavor name
        with self.assertRaises(ValueError):
            c.submit_job(test_job_works, test_image_name, "yucky")
        self.assertEqual(mock_session_post.call_count, 0)

        # failed submission because no Executable line in job file
        with self.assertRaises(ValueError):
            c.submit_job(test_job_fails, test_image_name, test_flavor_name)
        self.assertEqual(mock_session_post.call_count, 0)

        # works without Executable by specifying jobscriptonvm
        c.submit_job(test_job_fails, test_image_name, test_flavor_name, jobscriptonvm=test_script_on_vm)
        mock_session_post.assert_called_once_with(test_job_url, params=test_params_on_vm, files=test_files_on_vm)

        mock_session_post.reset_mock()
Example #24
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)
Example #25
0
def test_pdbfix_KC1D_HUMAN_D0_4KB8_D():
    set_loglevel("debug")
    template_pdb_gz_filepath = get_installed_resource_filename(
        os.path.join("tests", "resources", "KC1D_HUMAN_D0_4KB8_D.pdb.gz")
    )
    template_pdb_filepath = os.path.join(
        ensembler.core.default_project_dirnames.templates_structures_resolved, "KC1D_HUMAN_D0_4KB8_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(template_pdb_gz_filepath) as template_pdb_gz_file:
            with open(template_pdb_filepath, "w") as template_pdb_file:
                contents = template_pdb_gz_file.read()
                if type(contents) == bytes:
                    contents = contents.decode("utf-8")
                template_pdb_file.write(contents)
        template = Mock()
        template.id = "KC1D_HUMAN_D0_4KB8_D"
        template.seq = "LRVGNRYRLGRKIGSGSFGDIYLGTDIAAGEEVAIKLECVKTKHPQLHIESKIYKMMQGGVGIPTIRWCGAEGDYNVMVMELLGPSLEDLFNFCSRKFSLKTVLLLADQMISRIEYIHSKNFIHRDVKPDNFLMGLGKKGNLVYIIDFGLAKKYRDARTHQHIPYRENKNLTGTARYASINTHLGIEQSRRDDLESLGYVLMYFNLGSLPWQGLKAATKRQKYERISEKKMSTPIEVLCKGYPSEFATYLNFCRSLRFDDKPDYSYLRQLFRNLFHRQGFSYDYVFDWNMLKFGASRAADDAERERRDREERLRH"

        missing_residues = pdbfix_template(template)

        assert (0, 278) not in missing_residues
        assert missing_residues == {
            (0, 14): ["SER", "GLY", "SER", "PHE", "GLY"],
            (0, 34): ["VAL", "LYS", "THR", "LYS", "HIS"],
            (0, 147): ["ARG", "THR", "HIS"],
        }
 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), "")
Example #27
0
    def test_existing_id(self):
        client_handlers = {"existing_id": "existing_handler"}
        product_content = Mock()
        user_info_cache = Mock()
        favorites_cache = Mock()
        target = Target(
            product_content=product_content,
            client_handlers=client_handlers,
            user_info_cache=user_info_cache,
            favorites_cache=favorites_cache,
        )

        target.get_context = Mock(return_value="get_context_value")
        target.post_context = Mock()
        handler = Mock(name="new_client_handler")
        handler.id = "existing_id"
        handler.context_id = "context_id"
        handler._context = None

        target.open(handler)

        self.assertTrue("existing_id" in client_handlers)
        self.assertEqual("existing_handler", client_handlers["existing_id"])
        self.assertEqual("context_id", handler.context_id)
        self.assertIsNone(handler._context)

        self.assertEqual(0, target.post_context.call_count)

        self.assertEqual(1, handler.write_message.call_count)
        self.assertDictEqual(
            {"context_id": "context_id", "type": "connection_opened"}, handler.write_message.call_args_list[0][0][0]
        )
Example #28
0
def test_loopmodel_KC1D_HUMAN_D0_3UZP_A():
    """
    No missing residues
    """
    with integrationtest_context(set_up_project_stage="templates_resolved"):
        template = Mock()
        template.id = "KC1D_HUMAN_D0_3UZP_A"
        template.seq = "YRLGRKIGSGSFGDIYLGTDIAAGEEVAIKLECVKTKHPQLHIESKIYKMMQGGVGIPTIRWCGAEGDYNVMVMELLGPSLEDLFNFCSRKFSLKTVLLLADQMISRIEYIHSKNFIHRDVKPDNFLMGLGKKGNLVYIIDFGLAKKYRDARTHQHIPYRENKNLTGTARYASINTHLGIEQSRRDDLESLGYVLMYFNLGSLPWQGLKAATKRQKYERISEKKMSTPIEVLCKGYPSEFATYLNFCRSLRFDDKPDYSYLRQLFRNLF"

        missing_residues = pdbfix_template(template)
        loopmodel_template(template, missing_residues)

        assert not os.path.exists(
            os.path.join(
                ensembler.core.default_project_dirnames.templates_structures_modeled_loops, "KC1D_HUMAN_D0_3UZP_A.pdb"
            )
        )
        log = yaml.load(
            open(
                os.path.join(
                    ensembler.core.default_project_dirnames.templates_structures_modeled_loops,
                    "KC1D_HUMAN_D0_3UZP_A-loopmodel-log.yaml",
                )
            )
        )
        assert log["no_missing_residues"] == True
    def test__handle_enqueue_action(self, Worker, Run, datetime, config):
        """
        Test :func:`._handle_enqueue_action`.
        """
        worker = Mock()
        Worker.get_list.return_value = [worker]

        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, "worker": worker.resource_uri}
        )
        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)
Example #30
0
def test_pdbfix_ABL1_HUMAN_D0_2E2B_B():
    set_loglevel("debug")
    template_pdb_gz_filepath = get_installed_resource_filename(
        os.path.join("tests", "resources", "ABL1_HUMAN_D0_2E2B_B.pdb.gz")
    )
    template_pdb_filepath = os.path.join(
        ensembler.core.default_project_dirnames.templates_structures_resolved, "ABL1_HUMAN_D0_2E2B_B.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(template_pdb_gz_filepath) as template_pdb_gz_file:
            with open(template_pdb_filepath, "w") as template_pdb_file:
                contents = template_pdb_gz_file.read()
                if type(contents) == bytes:
                    contents = contents.decode("utf-8")
                template_pdb_file.write(contents)
        template = Mock()
        template.id = "ABL1_HUMAN_D0_2E2B_B"
        template.seq = "ITMKHKLGGGQYGEVYEGVWKKYSLTVAVKTLKEDTMEVEEFLKEAAVMKEIKHPNLVQLLGVCTREPPFYIITEFMTYGNLLDYLRECNRQEVNAVVLLYMATQISSAMEYLEKKNFIHRDLAARNCLVGENHLVKVADFGLSRLMTGDTYTAHAGAKFPIKWTAPESLAYNKFSIKSDVWAFGVLLWEIATYGMSPYPGIDLSQVYELLEKDYRMERPEGCPEKVYELMRACWQWNPSDRPSFAEIHQAFETMFQESSISDEVEKELGKQ"

        missing_residues = pdbfix_template(template)

        assert (0, 271) not in missing_residues
        assert missing_residues == {
            (0, 32): ["LYS", "GLU", "ASP", "THR", "MET"],
            (0, 139): ["ARG", "LEU", "MET", "THR", "GLY", "ASP"],
        }