Example #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)
Example #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")
Example #3
0
    def test_on_snapshot_loaded(self):
        m_response = Mock()

        endpoint_on_host = Mock()
        endpoint_on_host.key = "/calico/v1/host/hostname/workload/" "orch/wlid/endpoint/epid"
        endpoint_on_host.value = ENDPOINT_STR

        bad_endpoint_on_host = Mock()
        bad_endpoint_on_host.key = "/calico/v1/host/hostname/workload/" "orch/wlid/endpoint/epid2"
        bad_endpoint_on_host.value = ENDPOINT_STR[:10]

        endpoint_not_on_host = Mock()
        endpoint_not_on_host.key = "/calico/v1/host/other/workload/" "orch/wlid/endpoint/epid"
        endpoint_not_on_host.value = ENDPOINT_STR

        still_ready = Mock()
        still_ready.key = "/calico/v1/Ready"
        still_ready.value = "true"

        m_response.children = [endpoint_on_host, bad_endpoint_on_host, endpoint_not_on_host, still_ready]
        with patch.object(self.watcher, "clean_up_endpoint_statuses") as m_clean:
            self.watcher._on_snapshot_loaded(m_response)

        # Cleanup should only get the endpoints on our host.
        m_clean.assert_called_once_with(set([EndpointId("hostname", "orch", "wlid", "epid")]))
 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.assertEquals(expected, unique_list_items(input_list, lambda x: x.value))
Example #5
0
    def test_from_etcd_result(self):
        """
        Mainline test of from_etcd_result()
        """

        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[2] = 1
        unallocated = list(range(3, BLOCK_SIZE))
        json_dict = {
            AllocationBlock.CIDR: str(network),
            AllocationBlock.AFFINITY: "host:Sammy Davis, Jr.",
            AllocationBlock.ALLOCATIONS: allocations,
            AllocationBlock.ATTRIBUTES: [attr0, attr1],
            AllocationBlock.UNALLOCATED: unallocated,
        }
        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_list_equal(block.allocations[:3], [0, 0, 1])
        assert_dict_equal(block.attributes[0], attr0)
        assert_dict_equal(block.attributes[1], attr1)

        # Verify we can get JSON back out.
        json_str = block.to_json()
        assert_equal(result.value, json_str)

        # Modify the allocation order in the JSON so that it does not match
        # the allocations, and check the various unallocated asserts.
        # Check repeats
        json_dict[AllocationBlock.UNALLOCATED] = unallocated + [3]
        result.value = json.dumps(json_dict)
        self.assertRaises(AssertionError, AllocationBlock.from_etcd_result, result)
        # Check invalid entry
        json_dict[AllocationBlock.UNALLOCATED] = unallocated + [0]
        result.value = json.dumps(json_dict)
        self.assertRaises(AssertionError, AllocationBlock.from_etcd_result, result)
        # Check missing entry
        json_dict[AllocationBlock.UNALLOCATED] = unallocated[1:]
        result.value = json.dumps(json_dict)
        self.assertRaises(AssertionError, AllocationBlock.from_etcd_result, result)
 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
 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
Example #8
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)
Example #9
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")
Example #10
0
    def test_update_result_from_pre_unallocated(self):
        """
        Test mainline update_result() processing.

        This includes a check to ensure that updating a block that is stored
        without the allocation order is then correctly updated to include the
        allocation order.
        """

        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[2] = 1
        json_dict = {
            AllocationBlock.CIDR: str(network),
            AllocationBlock.AFFINITY: "",  # Test a block with no affinity
            AllocationBlock.STRICT_AFFINITY: False,
            AllocationBlock.ALLOCATIONS: allocations,
            AllocationBlock.ATTRIBUTES: [attr0, attr1],
        }
        result.value = json.dumps(json_dict)

        block = AllocationBlock.from_etcd_result(result)

        # Verify the block has no affinity
        assert_equal(block.host_affinity, None)

        # Verify that the allocation order is correctly initialised.
        unallocated = list(range(3, BLOCK_SIZE))
        assert_list_equal(block.unallocated, unallocated)

        # Modify the block (and the expected allocation order)
        block.allocations[3] = 1
        block.unallocated.remove(3)
        unallocated.remove(3)

        # Get the update.  It should be the same result object, but with the
        # value set to the new JSON.
        block_json_str = block.to_json()
        updated = block.update_result()
        assert_equal(updated, result)
        assert_equal(result.value, block_json_str)

        # Verify the update appears in the JSON and that the JSON now includes
        # the allocation order.
        json_dict[AllocationBlock.UNALLOCATED] = unallocated
        block_json_dict = json.loads(block_json_str)
        json_dict[AllocationBlock.ALLOCATIONS][3] = 1
        assert_dict_equal(block_json_dict, json_dict)
Example #11
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)
Example #12
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)
Example #13
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))
Example #14
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)
Example #15
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)
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
Example #17
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)
Example #18
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)
Example #19
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
Example #20
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"])
Example #21
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 mock_read_get_endpoint(path, recursive=None):
     assert recursive
     assert path == TEST_ENDPOINT_PATH
     leaf = Mock(spec=EtcdResult)
     leaf.key = TEST_ENDPOINT_PATH
     leaf.value = ep.to_json()
     result = Mock(spec=EtcdResult)
     result.leaves = iter([leaf])
     return result
 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)
Example #24
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
Example #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")
Example #26
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]
    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)
        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()
def mock_read_no_node_bgppeers(path):
    """
    EtcdClient mock side effect for read with no IPv4 BGP Peers
    """
    result = Mock(spec=EtcdResult)
    assert path == TEST_NODE_BGP_PEERS_PATH

    # Bug in etcd seems to return the parent when enumerating children if there
    # are no children.  We handle this in the datastore.
    node = Mock(spec=EtcdResult)
    node.value = None
    node.key = TEST_NODE_BGP_PEERS_PATH
    result.children = iter([node])
    return result
def mock_read_2_pools(path):
    """
    EtcdClient mock side effect for read with 2 IPv4 pools.
    """
    result = Mock(spec=EtcdResult)
    assert_equal(path, IPV4_POOLS_PATH)
    children = []
    for net in ["192.168.3.0/24", "192.168.5.0/24"]:
        node = Mock(spec=EtcdResult)
        node.value = '{"cidr": "%s"}' % net
        node.key = IPV4_POOLS_PATH + "/" + net.replace("/", "-")
        children.append(node)
    result.children = iter(children)
    return result