Пример #1
0
    def test_restructure_layout_preferences_forwards(self):

        empty_workspace = Mock()
        empty_workspace_layout_pref = Mock()
        empty_workspace_layout_preferences = TestQueryResult([])
        empty_workspace.workspacepreference_set.filter.side_effect = (
            lambda **kwargs: empty_workspace_layout_pref
            if kwargs.get("name") == "layout"
            else empty_workspace_layout_preferences
        )
        empty_workspace.tab_set.all.return_value = TestQueryResult([])

        workspace = Mock()
        workspace_layout_pref = Mock()
        workspace_columns_pref = Mock()
        workspace_columns_pref.name = "columns"
        workspace_columns_pref.value = 15
        workspace_layout_preferences = TestQueryResult([workspace_columns_pref])
        workspace.workspacepreference_set.filter.side_effect = (
            lambda **kwargs: workspace_layout_pref
            if kwargs.get("name", "") == "layout"
            else workspace_layout_preferences
        )

        workspace_tab = Mock()
        workspace_tab_layout_pref = Mock()
        workspace_tab_columns_pref = Mock()
        workspace_tab_columns_pref.name = "columns"
        workspace_tab_columns_pref.value = 15
        workspace_tab_layout_preferences = TestQueryResult([workspace_tab_columns_pref])
        workspace_tab.tabpreference_set.filter.side_effect = (
            lambda **kwargs: workspace_tab_layout_pref
            if kwargs.get("name", "") == "layout"
            else workspace_tab_layout_preferences
        )

        workspace_empty_tab = Mock()
        workspace_empty_tab_layout_pref = Mock()
        workspace_empty_tab_layout_preferences = TestQueryResult([])
        workspace_empty_tab.tabpreference_set.filter.side_effect = (
            lambda **kwargs: workspace_empty_tab_layout_pref
            if kwargs.get("name", "") == "layout"
            else workspace_empty_tab_layout_preferences
        )
        workspace.tab_set.all.return_value = TestQueryResult([workspace_empty_tab, workspace_tab])

        migration = self._pick_migration("0016_restructure_layout_preferences")
        orm = Mock(autospec=migration.orm())
        orm.Workspace.objects.all.return_value = TestQueryResult([empty_workspace, workspace])
        migration.migration_instance().forwards(orm)

        self.assertTrue(empty_workspace_layout_pref.update.called)
        self.assertEqual(empty_workspace_layout_preferences.delete.call_count, 0)
        self.assertFalse(empty_workspace.workspacepreference_set.create.called)

        self.assertTrue(workspace_layout_pref.update.called)
        self.assertTrue(workspace_layout_preferences.delete.called)
        self.assertTrue(workspace_tab_layout_preferences.delete.called)
        self.assertFalse(workspace_empty_tab_layout_preferences.delete.called)
        self.assertTrue(workspace.workspacepreference_set.create.called)
Пример #2
0
    def test_resource_offers_creates_nodes(self, mock_get_slave):
        mock_get_slave.return_value = SlaveInfo(u'localhost', 5151)
        mock_cpu = Mock()
        mock_cpu.name = u'cpus'
        mock_cpu.value = 10
        
        mock_disk = Mock()
        mock_disk.name = u'disk'
        mock_disk.value = 4000
 
        mock_mem = Mock()
        mock_mem.name = u'mem'
        mock_mem.value = 100000
        
        mock_offer = Mock()
        mock_offer.id.value = 1
        mock_offer.slave_id.value = 1
        mock_offer.hostname.value = u'localhost'
        mock_offer.resources = [mock_cpu, mock_disk, mock_mem]
        offers = [mock_offer]

        my_scheduler, driver, master_info = self._get_mocked_scheduler_driver_master()

        localhost_exists = Node.objects.filter(hostname=u'localhost').exists()
        self.assertFalse(localhost_exists, 'there should not be a node before the first offer')
        my_scheduler.resourceOffers(driver, offers)
        localhost_exists = Node.objects.all().exists()
        self.assertTrue(localhost_exists, 'there should be a node after the first offer')
Пример #3
0
 def test_hash_function(self):
     mock_item_1 = Mock()
     mock_item_1.value = 1
     mock_item_2 = Mock()
     mock_item_2.value = 2
     input_list = [mock_item_1, mock_item_1, mock_item_2, mock_item_2]
     expected = [mock_item_1, mock_item_2]
     self.assertEqual(expected, unique_list_items(input_list, lambda x: x.value))
Пример #4
0
 def mock_read(path):
     result = Mock(spec=EtcdResult)
     if path == TEST_HOST_PATH + "/bird_ip":
         result.value = "192.168.24.1"
         return result
     if path == TEST_HOST_PATH + "/bird6_ip":
         result.value = "fd30:4500::1"
         return result
     assert False
Пример #5
0
 def mock_read(path):
     result = Mock(spec=EtcdResult)
     if path == TEST_HOST_PATH + "/bird_ip":
         result.value = ""
         return result
     if path == TEST_HOST_PATH + "/bird6_ip":
         result.value = ""
         return result
     assert False
Пример #6
0
	def test_got_csrf(self):
		cookie1 = Mock()
		cookie1.name = 'csrftoken'
		cookie1.value = 'csrf value 1'
		cookie1.domain = 'other domain'
		cookie2 = Mock()
		cookie2.name = 'csrftoken'
		cookie2.value = 'csrf value 2'
		cookie2.domain = 'test.trigger.io'
		self.remote.cookies = [cookie1, cookie2]
		eq_(self.remote._csrf_token(), 'csrf value 2')
Пример #7
0
 def test_wait_for_ready(self, m_sleep):
     m_resp_1 = Mock()
     m_resp_1.value = "false"
     m_resp_2 = Mock()
     m_resp_2.value = "true"
     responses = [
         etcd.EtcdException(),
         etcd.EtcdKeyNotFound(),
         m_resp_1,
         m_resp_2,
     ]
     self.m_client.read.side_effect = iter(responses)
     self.watcher.wait_for_ready(1)
     self.assertEqual(m_sleep.mock_calls, [call(1)] * 3)
Пример #8
0
 def test_exec_config_with_set_workspaces(self):
     """Test exec config with set workspaces subcommand."""
     args = Mock()
     args.action = "set"
     args.key = "workspaces"
     args.value = False
     self.assertFalse(self.subcommand.execute(args))
Пример #9
0
    def test_server_sends_marshaled_exception_when_callback_raises_exception(self, mock_command_response):
        request = '{"name": "foobar", "arg": {"arg1": "value"}}'

        expected = '{"error": "raise me!", "value": null}'

        command_response = Mock(CommandResponse)
        command_response.error = "raise me!"
        command_response.value = None
        mock_command_response.return_value = command_response
        callback = Mock(side_effect=BusCtlServerError())

        marshaler = Mock(Marshaler)
        server = BusCtlServer()
        server._marshaler = marshaler

        command = Mock()
        command.name = "foobar"
        marshaler.unmarshal_command.return_value = command
        marshaler.marshal_response.return_value = expected

        command_class = Mock()
        command_class.name = "foobar"

        server.add_command(command_class, callback)

        response = server._process_next_command(request)

        self.assertEqual(response, expected)
        marshaler.marshal_response.assert_called_once_with(command_response)
Пример #10
0
 def test_nested_raw_field(self):
     foo = Mock()
     bar = Mock()
     bar.value = 3
     foo.bar = bar
     field = fields.Raw()
     self.assertEquals(field.output("bar.value", foo), 3)
Пример #11
0
def mock_read_4_endpoints(path, recursive):
    assert path == ALL_ENDPOINTS_PATH
    assert recursive
    leaves = []

    specs = [
        (CALICO_V_PATH + "/host/TEST_HOST/bird_ip", "192.168.1.1"),
        (CALICO_V_PATH + "/host/TEST_HOST/bird6_ip", "fd80::4"),
        (CALICO_V_PATH + "/host/TEST_HOST/config/marker", "created"),
        (CALICO_V_PATH + "/host/TEST_HOST/workload/docker/1234/endpoint/567890abcdef",
         EP_56.to_json()),
        (CALICO_V_PATH + "/host/TEST_HOST/workload/docker/5678/endpoint/90abcdef1234",
         EP_90.to_json()),
        (CALICO_V_PATH + "/host/TEST_HOST2/bird_ip", "192.168.1.2"),
        (CALICO_V_PATH + "/host/TEST_HOST2/bird6_ip", "fd80::3"),
        (CALICO_V_PATH + "/host/TEST_HOST2/config/marker", "created"),
        (CALICO_V_PATH + "/host/TEST_HOST2/workload/docker/1234/endpoint/7890abcdef12",
         EP_78.to_json()),
        (CALICO_V_PATH + "/host/TEST_HOST2/workload/docker/5678/endpoint/1234567890ab",
         EP_12.to_json())]
    for spec in specs:
        leaf = Mock(spec=EtcdResult)
        leaf.key = spec[0]
        leaf.value = spec[1]
        leaves.append(leaf)

    result = Mock(spec=EtcdResult)
    result.leaves = iter(leaves)
    return result
Пример #12
0
    def test_process_event_nolabels(self):
        with patch.object(FabricService.objects, "get_items") as fabric_service_objects, \
                patch.object(Service.objects, "get_items") as service_objects, \
                patch.object(Switch.objects, "get_items") as switch_objects, \
                patch.object(Switch, "save") as switch_save, \
                patch.object(SwitchPort, "save") as switchport_save:
            fabric_service_objects.return_value = [self.fabric_service]
            service_objects.return_value = [self.onos, self.fabric_service]
            switch_objects.return_value = [self.switch]

            event_dict = {"status": "created"}
            event = Mock()
            event.value = json.dumps(event_dict)

            step = self.event_step(model_accessor=self.model_accessor, log=self.log)
            step.process_event(event)

            self.assertEqual(self.switch.backend_code, 1)
            self.assertEqual(self.switch.backend_status, "succeeded")

            switch_save.assert_not_called()

            self.assertEqual(self.port1.backend_code, 1)
            self.assertEqual(self.port1.backend_status, "succeeded")

            self.assertEqual(self.port2.backend_code, 1)
            self.assertEqual(self.port2.backend_status, "succeeded")

            switchport_save.assert_not_called()
Пример #13
0
    def test_to_json(self):
        host = "test_host"
        block = AllocationBlock(network, host)

        # Set up an allocation
        attr = {
            AllocationBlock.ATTR_HANDLE_ID: "test_key",
            AllocationBlock.ATTR_SECONDARY: {
                "key1": "value1",
                "key2": "value2"
            }
        }
        block.attributes.append(attr)
        block.allocations[5] = 0
        assert_equal(block.count_free_addresses(), BLOCK_SIZE - 1)

        # Read out the JSON
        json_str = block.to_json()
        json_dict = json.loads(json_str)
        assert_equal(json_dict[AllocationBlock.CIDR], str(network))
        assert_equal(json_dict[AllocationBlock.AFFINITY], "host:test_host")
        assert_dict_equal(json_dict[AllocationBlock.ATTRIBUTES][0],
                          attr)
        expected_allocations = [None] * BLOCK_SIZE
        expected_allocations[5] = 0
        assert_list_equal(json_dict[AllocationBlock.ALLOCATIONS],
                          expected_allocations)

        # Verify we can read the JSON back in.
        result = Mock(spec=EtcdResult)
        result.value = json_str
        block2 = AllocationBlock.from_etcd_result(result)
        assert_equal(block2.to_json(), json_str)
Пример #14
0
 def test_exec_config_with_set(self):
     """Test exec config with set subcommand."""
     args = Mock()
     args.action = "set"
     args.key = "logfile"
     args.value = "/tmp/yoda.log"
     self.subcommand.execute(args)
     self.assertEqual("/tmp/yoda.log", self.config["logfile"])
Пример #15
0
    def test_get_stack_parameters_dict_returns_proper_dict(self, _, get_stack_mock):
        cfn = CloudFormation()

        parameter_1 = Mock()
        parameter_1.key = "myKey1"
        parameter_1.value = "myValue1"
        parameter_2 = Mock()
        parameter_2.key = "myKey2"
        parameter_2.value = "myValue2"

        stack_mock = Mock()
        stack_mock.parameters = [parameter_1, parameter_2]
        get_stack_mock.return_value = stack_mock

        result = cfn.get_stack_parameters_dict('foo')

        self.assertDictEqual({'myKey1': 'myValue1', 'myKey2': 'myValue2'}, result)
Пример #16
0
 def test_get_cookie(self):
     morsel = Mock()
     morsel.value = "value"
     self.rh.request.cookies = {"testcookie": morsel}
     val = self.rh.get_cookie("testcookie")
     self.assertEqual(val, "value")
     val = self.rh.get_cookie("non_existent")
     self.assertEqual(val, None)
Пример #17
0
    def setup(self):
        library = self.library = ContentFeedLibrary()

        # Create a subscriber
        subscriber = self.subscriber = Mock()

        # Create a subscription
        subscription = self.subscription = Mock()
        subscription.last_sent = datetime.datetime(2011, 1, 1, 0, 0)
        subscription.feed_record.last_updated = datetime.datetime(2011, 8, 4, 6, 50)
        subscription.feed_record.feed_name = 'MockFeed'
        param1 = Mock(); param1.name = 'p1'; param1.value = '1'
        param2 = Mock(); param2.name = 'p2'; param2.value = '2'
        subscription.feed.feed_params.all = lambda: [param1, param2]

        # The subscriber is subscribed to the subscription we created
        subscriber.subscriptions.all = lambda: [subscription]
Пример #18
0
def dummy_balance_code():
    m = Mock()
    m.pk = random.randint(1, 999)
    m.value = 100
    m.code = generate_balance_code()
    m.refill_series.pk = random.randint(1, 99)
    m.refill_series.least_valid_until = date.today()
    return m
Пример #19
0
 def dispatch(self, key, action, value=None):
     """
     Send an EtcdResult to the watcher's dispatcher.
     """
     m_response = Mock(spec=EtcdResult)
     m_response.key = key
     m_response.action = action
     m_response.value = value
     self.watcher.dispatcher.handle_event(m_response)
    def test_get_vm_details(self):
        # Arrange
        image = self.mock_image()
        flavor = self.mock_flavor()
        vm = self.mock_vm()
        self.instance_service.get_instance_from_instance_id = Mock(return_value=vm)
        self.instance_service.get_image = Mock(return_value=image)
        self.instance_service.get_flavor = Mock(return_value=flavor)

        network = {'id': '300881', 'name': 'network_name_for_test', 'provider:segmentation_id': '777'}

        mock_client = Mock()
        test_neutron_network_service.neutron_client.Client = Mock(return_value=mock_client)
        mock_client.list_networks = Mock(return_value={'networks': [network]})

        param = Mock()
        param.name = 'ip_regex'
        param.value = 'bla.*'

        request = Mock()
        request.deployedAppJson.name = 'OpenStack App for Tests'
        request.deployedAppJson.vmdetails.uid = '240975'
        request.deployedAppJson.vmdetails.vmCustomParams = [param]
        request.appRequestJson.deploymentService.model = 'OpenStack'
        request.appRequestJson.deploymentService.attributes = [Mock()]

        cancellation_context = Mock(is_cancelled=False)
        management_vlan_id = Mock()

        # Act
        result = self.vm_details_operation.get_vm_details(openstack_session=self.openstack_session,
                                                          requests=[request],
                                                          cancellation_context=cancellation_context,
                                                          logger=Mock(),
                                                          management_vlan_id=management_vlan_id)

        # Assert
        self.assertEqual(len(result), 1)
        vm_details = result[0]
        self.assertEqual(next(x.value for x in vm_details.vmInstanceData if x.key == 'Image'), 'Image Name')
        self.assertEqual(next(x.value for x in vm_details.vmInstanceData if x.key == 'Flavour'), 'Flavor Name')
        self.assertEqual(next(x.value for x in vm_details.vmInstanceData if x.key == 'Availability Zone'), 'Av Zone')
        self.assertEqual(next(x.value for x in vm_details.vmInstanceData if x.key == 'Disk Size'), '320 GB')
        self.assertEqual(next(x.value for x in vm_details.vmInstanceData if x.key == 'Memory'), '256 GB')
        self.assertEqual(next(x.value for x in vm_details.vmInstanceData if x.key == 'CPU'), '2 vCPU')

        self.assertEqual(len(vm_details.vmNetworkData), 1)
        nic = vm_details.vmNetworkData[0]
        self.assertEqual(nic.isPredefined, False)
        self.assertEqual(nic.networkId, '777')

        self.assertEqual(len(nic.networkData), 3)
        self.assertEqual(nic.privateIpAddress, '192.168.1.1')
        self.assertEqual(next(x.value for x in nic.networkData if x.key == 'IP'), '192.168.1.1')
        self.assertEqual(next(x.value for x in nic.networkData if x.key == 'VLAN Name'), 'network_name_for_test')
 def test_get_network(self):
     """
     Test get_network() returns correct data.
     :return:
     """
     etcd_entry = Mock()
     etcd_entry.value = TEST_JSON
     self.etcd_client.read.return_value = etcd_entry
     self.assertDictEqual(self.datastore.get_network(TEST_NETWORK_ID),
                          TEST_DATA)
     self.etcd_client.read.assert_called_once_with(TEST_NETWORK_DIR)
Пример #22
0
    def _get_registered_scheduler_driver_master(self):
        driver = Mock()
        framework_id = Mock()
        framework_id.value = 'framework_id'
        master_info = Mock()
        master_info.hostname = 'localhost'
        master_info.port = 1234

        my_scheduler = scheduler.scale_scheduler.ScaleScheduler(None)
        my_scheduler.registered(driver,framework_id,master_info)
        return my_scheduler, driver, master_info
Пример #23
0
def dynamodb_resource():
    """A mocked version of boto3 DynamoDB resource."""
    mock_item = Mock()
    mock_item.value = "encrypted"
    mock_item.get = Mock(return_value=None)
    rv = {"Item": mock_item}
    mocked_table = Mock()
    mocked_table.get_item = Mock(return_value=rv)
    mocked = Mock()
    mocked.Table = Mock(return_value=mocked_table)
    return mocked
Пример #24
0
    def test_from_etcd_result_no_unallocated(self):
        """
        Test the from_etcd_result processing when the allocation order is
        missing (this is allowed since it is a new field).
        """
        result = Mock(spec=EtcdResult)

        # Build a JSON object for the Block
        attr0 = {
            AllocationBlock.ATTR_HANDLE_ID: "test_key1",
            AllocationBlock.ATTR_SECONDARY: {
                "key1": "value11",
                "key2": "value21"
            }
        }
        attr1 = {
            AllocationBlock.ATTR_HANDLE_ID: "test_key2",
            AllocationBlock.ATTR_SECONDARY: {
                "key1": "value12",
                "key2": "value22"
            }
        }
        allocations = [None] * BLOCK_SIZE
        allocations[0] = 0
        allocations[1] = 0
        allocations[4] = 1
        json_dict = {
            AllocationBlock.CIDR: str(network),
            AllocationBlock.AFFINITY: "host:Sammy Davis, Jr.",
            AllocationBlock.STRICT_AFFINITY: True,
            AllocationBlock.ALLOCATIONS: allocations,
            AllocationBlock.ATTRIBUTES: [attr0, attr1]
        }
        result.value = json.dumps(json_dict)

        block = AllocationBlock.from_etcd_result(result)
        assert_equal(block.count_free_addresses(), BLOCK_SIZE - 3)
        assert_equal(block.db_result, result)
        assert_equal(block.cidr, network)
        assert_equal(block.host_affinity, "Sammy Davis, Jr.")
        assert_true(block.strict_affinity)
        assert_list_equal(block.allocations[:5], [0, 0, None, None, 1])
        assert_dict_equal(block.attributes[0], attr0)
        assert_dict_equal(block.attributes[1], attr1)

        # Verify the allocation order is correctly calculated from the
        # unassigned entries.
        unallocated = [o for o in range(BLOCK_SIZE)
                              if o not in (0, 1, 4)]
        assert_list_equal(block.unallocated, unallocated)

        # Verify we can get JSON back out.
        json_dict[AllocationBlock.UNALLOCATED] = unallocated
        assert_equal(json.dumps(json_dict), block.to_json())
Пример #25
0
 def test_Query(self):
     self.db.provenance.find.return_value = ['record1']
     self.setupRepo()
     q = Mock()
     field1 = Mock()
     field1.name = 'color'
     field1.value = 'red'
     field1.all = False
     q.getFields.return_value = [field1]
     out = self.repo.inquire(q)
     self.db.provenance.find.assert_called_with({'color':'red'})
     self.fileFactory.fromProvenance.assert_called_with('record1')
    def test_should_return_number_of_cores_when_in_resources(self):
        resource_1 = Mock()
        resource_1.key = "weLoveCamelCase"
        resource_2 = Mock()
        resource_2.key = "numCpuCores"
        resource_2.value = 42
        resource_3 = Mock()
        resource_3.key = "someOtherKey"

        resources = [resource_1, resource_2, resource_3]
        self.raw_esx.licensableResource.resource = resources

        self.assertEquals(self.wrapped_esx.get_number_of_cores(), 42)
Пример #27
0
    def test_from_etcd_result(self):

        block_dict = {
            "10.23.24.0/24": 50,
            "10.23.35.0/24": 60
        }
        json_dict = {
            AllocationHandle.HANDLE_ID: "test_id2",
            AllocationHandle.BLOCK: block_dict
        }
        m_result = Mock(spec=EtcdResult)
        m_result.value = json.dumps(json_dict)

        handle = AllocationHandle.from_etcd_result(m_result)

        assert_dict_equal(block_dict, handle.block)
        assert_equal(m_result, handle.db_result)

        # Convert to JSON and back
        m_result.value = handle.to_json()
        handle2 = AllocationHandle.from_etcd_result(m_result)
        assert_equal(block_dict, handle2.block)
Пример #28
0
        def mock_read(path):
            result = Mock(spec=EtcdResult)
            if path == TEST_PROFILE_PATH:
                return result
            elif path == TEST_PROFILE_PATH + "tags":
                result.value = '["TAG1", "TAG2", "TAG3"]'
                return result
            elif path == TEST_PROFILE_PATH + "rules":
                result.value = """
{
  "id": "TEST",
  "inbound_rules": [
    {"action": "allow", "src_net": "192.168.1.0/24", "src_ports": [200,2001]}
  ],
  "outbound_rules": [
    {"action": "allow", "src_tag": "TEST", "src_ports": [200,2001]}
  ]
}
"""
                return result
            else:
                raise EtcdKeyNotFound()
Пример #29
0
def test_log_if_changed():
    artifact = Mock()
    artifact.value = 'test'
    # change
    h.log_if_changed(artifact, 'value', 'changed', 'updated value')
    assert artifact.value == 'changed'
    assert len(AuditLogMock.logs) == 1
    assert AuditLogMock.logs[0] == 'updated value'

    # don't change
    h.log_if_changed(artifact, 'value', 'changed', 'updated value')
    assert artifact.value == 'changed'
    assert len(AuditLogMock.logs) == 1
    assert AuditLogMock.logs[0] == 'updated value'
Пример #30
0
def mock_read_2_pools(path):
    """
    EtcdClient mock side effect for read with 2 IPv4 pools.
    """
    result = Mock(spec=EtcdResult)
    assert path == IPV4_POOLS_PATH
    children = []
    for i, net in enumerate(["192.168.3.0/24", "192.168.5.0/24"]):
        node = Mock(spec=EtcdResult)
        node.value = net
        node.key = IPV4_POOLS_PATH + str(i)
        children.append(node)
    result.children = iter(children)
    return result