Exemple #1
0
    def test_record_progress_only_after_source_finished(self):
        first_file = self.model.get_current_filename()

        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    has_length(0))

        self.model.accept_current_item()
        assert_that(self.concurrent_progress_manager.is_done(first_file),
                    equal_to(False))
        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    has_length(0))

        self.model.next_item()
        self.model.accept_current_item()
        assert_that(self.concurrent_progress_manager.is_done(first_file),
                    equal_to(False))
        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    has_length(0))

        self.model.next_item()
        self.model.accept_current_item()
        assert_that(self.concurrent_progress_manager.is_done(first_file),
                    equal_to(False))
        assert_that(self.concurrent_progress_manager.get_processed_indices(first_file),
                    contains_inanyorder(0))
    def test_access_mode(self):
        self.edit({
            "vlans": {
                "vlan": [
                    {"name": "VLAN2995"},
                    {"vlan-id": "2995"}]},
            "interfaces": {
                "interface": [
                    {"name": "ge-0/0/3"},
                    {"unit": [
                        {"name": "0"},
                        {"family": {
                            "ethernet-switching": {
                                "interface-mode": "access",
                                "vlan": [
                                    {"members": "2995"},
                                ]}}}]}]}})
        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/3"}}}}
        }))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(1))

        int003 = result.xpath("data/configuration/interfaces/interface")[0]

        assert_that(int003.xpath("name")[0].text, equal_to("ge-0/0/3"))
        assert_that(int003.xpath("unit/family/ethernet-switching/*"), has_length(2))
        assert_that(int003.xpath("unit/family/ethernet-switching/interface-mode")[0].text,
                    equal_to("access"))
        assert_that(int003.xpath("unit/family/ethernet-switching/vlan/members"), has_length(1))
        assert_that(int003.xpath("unit/family/ethernet-switching/vlan/members")[0].text, equal_to("2995"))

        self.cleanup(vlan("VLAN2995"), interface("ge-0/0/3", ["interface-mode", "vlan"]))
Exemple #3
0
def test_good_gotoassignment_do_not_follow_imports():
  app = TestApp( handlers.app )
  filepath = fixture_filepath( 'follow_imports', 'importer.py' )
  request_data = {
      'source': open( filepath ).read(),
      'line': 3,
      'col': 9,
      'source_path': filepath
  }
  expected_definition = {
      'module_path': filepath,
      'name': 'imported_function',
      'in_builtin_module': False,
      'line': 1,
      'column': 21,
      'docstring': '',
      'description': 'from imported '
      'import imported_function',
      'is_keyword': False
  }

  definitions = app.post_json( '/gotoassignment',
                               request_data ).json[ 'definitions' ]

  assert_that( definitions, has_length( 1 ) )
  assert_that( definitions, has_item( expected_definition ) )

  request_data[ 'follow_imports' ] = False

  definitions = app.post_json( '/gotoassignment',
                               request_data ).json[ 'definitions' ]

  assert_that( definitions, has_length( 1 ) )
  assert_that( definitions, has_item( expected_definition ) )
    def test_display_interface_trunk_native_vlan_and_no_ethernet_switching(self):
        self.edit({
            "vlans": [
                {"vlan": [
                    {"name": "VLAN2996"},
                    {"vlan-id": "2996"}]}
            ],
            "interfaces": {
                "interface": [
                    {"name": "ge-0/0/3"},
                    {"native-vlan-id": "2996"}
                    ]}})
        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/3"}}}}
        }))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(1))

        int003 = result.xpath("data/configuration/interfaces/interface")[0]
        assert_that(int003.xpath("name")[0].text, equal_to("ge-0/0/3"))
        assert_that(int003.xpath("native-vlan-id")[0].text, equal_to("2996"))

        self.cleanup(vlan("VLAN2996"), interface("ge-0/0/3"))
        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"vlans": {}}}
        }))
        assert_that(result.xpath("data/configuration/vlans/vlan"), has_length(0))
    def test_create_vlan(self):
        self.nc.edit_config(target='candidate', config=dict_2_etree({"config": {"configuration": {
            "vlans": {
                "vlan": [
                    {"name": "VLAN2999"},
                    {"description": "WHAAT"},
                    {"vlan-id": "2995"}
                ]
            }
        }}}))

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"vlans": {}}}
        }))

        assert_that(result.xpath("data/*"), has_length(1))
        assert_that(result.xpath("data/configuration/*"), has_length(1))
        assert_that(result.xpath("data/configuration/vlans/*"), has_length(1))
        assert_that(result.xpath("data/configuration/vlans/vlan/*"), has_length(3))

        vlan2995 = result.xpath("data/configuration/vlans/vlan")[0]

        assert_that(vlan2995.xpath("name")[0].text, equal_to("VLAN2999"))
        assert_that(vlan2995.xpath("description")[0].text, equal_to("WHAAT"))
        assert_that(vlan2995.xpath("vlan-id")[0].text, equal_to("2995"))

        self.cleanup(vlan("VLAN2999"))
    def test_adding_and_removing_ip_basic(self):
        self.client.add_vlan(2345)

        self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("2.2.2.2/24"))
        self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.1/24"))
        self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.2/24"))
        self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.3/24"))
        self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.4/24"))

        vlans = self.client.get_vlans()
        vlan2345 = next(vlan for vlan in vlans if vlan.number == 2345)

        assert_that(vlan2345.ips, has_length(5))
        assert_that(str(vlan2345.ips[0]), equal_to("1.1.1.1/24"))
        assert_that(str(vlan2345.ips[1]), equal_to("1.1.1.2/24"))
        assert_that(str(vlan2345.ips[2]), equal_to("1.1.1.3/24"))
        assert_that(str(vlan2345.ips[3]), equal_to("1.1.1.4/24"))
        assert_that(str(vlan2345.ips[4]), equal_to("2.2.2.2/24"))

        self.client.remove_ip_from_vlan(2345, ip_network=IPNetwork("1.1.1.1/24"))
        self.client.remove_ip_from_vlan(2345, ip_network=IPNetwork("1.1.1.3/24"))

        vlans = self.client.get_vlans()
        vlan2345 = next(vlan for vlan in vlans if vlan.number == 2345)

        assert_that(vlan2345.ips, has_length(3))
        assert_that(str(vlan2345.ips[0]), equal_to("1.1.1.2/24"))
        assert_that(str(vlan2345.ips[1]), equal_to("1.1.1.4/24"))
        assert_that(str(vlan2345.ips[2]), equal_to("2.2.2.2/24"))

        self.client.remove_vlan(2345)
Exemple #7
0
    def test_month_and_group_query_with_start_and_end_at(self):
        self.mock_storage.execute_query.return_value = [
            {'some_group': 'val1', '_month_start_at': d(2013, 1, 1), '_count': 1},
            {'some_group': 'val1', '_month_start_at': d(2013, 2, 1), '_count': 5},
            {'some_group': 'val2', '_month_start_at': d(2013, 3, 1), '_count': 2},
            {'some_group': 'val2', '_month_start_at': d(2013, 4, 1), '_count': 6},
            {'some_group': 'val2', '_month_start_at': d(2013, 7, 1), '_count': 6},
        ]

        data = self.data_set.execute_query(
            Query.create(period=MONTH,
                         group_by=['some_group'],
                         start_at=d(2013, 1, 1),
                         end_at=d(2013, 4, 2)))
        assert_that(data,
                    has_item(has_entries({"values": has_length(4)})))
        assert_that(data,
                    has_item(has_entries({"values": has_length(4)})))

        first_group = data[0]["values"]
        assert_that(first_group, has_item(has_entries({
            "_start_at": d_tz(2013, 3, 1)})))
        assert_that(first_group, has_item(has_entries({
            "_start_at": d_tz(2013, 4, 1)})))

        first_group = data[1]["values"]
        assert_that(first_group, has_item(has_entries({
            "_start_at": d_tz(2013, 1, 1)})))
        assert_that(first_group, has_item(has_entries({
            "_start_at": d_tz(2013, 2, 1)})))
    def test_filtering_with_a_value(self):
        content = dict_2_etree({
            "data": {
                "configuration": [
                    {"element": {
                        "element-key": "MY-KEY",
                        "attribute": {"sub-attribute": {}}
                    }},
                    {"element": {
                        "element-key": "MY-OTHER-KEY",
                        "other-attribute": {"sub-attribute": {}}
                    }},
                ]
            }
        })

        content_filter = dict_2_etree({
            "filter": {
                "configuration": {
                    "element": {
                        "element-key": "MY-KEY"
                    },
                }
            }
        })

        filter_content(content, content_filter)

        assert_that(content.xpath("//data/configuration/element"), has_length(1))
        assert_that(content.xpath("//data/configuration/element/*"), has_length(2))
        assert_that(content.xpath("//data/configuration/element/attribute/*"), has_length(1))
    def test_adding_and_removing_ip_basic(self):
        self.post("/switches/{switch}/vlans", data={"number": 2345})

        self.post("/switches/{switch}/vlans/2345/ips", data={"address": "2.2.2.2", "mask": "24"})
        self.post("/switches/{switch}/vlans/2345/ips", data={"address": "1.1.1.1", "mask": "24"})
        self.post("/switches/{switch}/vlans/2345/ips", data={"address": "1.1.1.2", "mask": "24"})
        self.post("/switches/{switch}/vlans/2345/ips", data={"address": "1.1.1.3", "mask": "24"})
        self.post("/switches/{switch}/vlans/2345/ips", data={"address": "1.1.1.4", "mask": "24"})

        vlans = self.get("/switches/{switch}/vlans")
        vlan2345 = next(vlan for vlan in vlans if vlan["number"] == 2345)

        assert_that(vlan2345["ips"], has_length(5))
        assert_that(vlan2345["ips"][0], equal_to({"address": "1.1.1.1", "mask": 24}))
        assert_that(vlan2345["ips"][1], equal_to({"address": "1.1.1.2", "mask": 24}))
        assert_that(vlan2345["ips"][2], equal_to({"address": "1.1.1.3", "mask": 24}))
        assert_that(vlan2345["ips"][3], equal_to({"address": "1.1.1.4", "mask": 24}))
        assert_that(vlan2345["ips"][4], equal_to({"address": "2.2.2.2", "mask": 24}))

        self.delete("/switches/{switch}/vlans/2345/ips/1.1.1.1/24")
        self.delete("/switches/{switch}/vlans/2345/ips/1.1.1.3/24")

        vlans = self.get("/switches/{switch}/vlans")
        vlan2345 = next(vlan for vlan in vlans if vlan["number"] == 2345)

        assert_that(vlan2345["ips"], has_length(3))
        assert_that(vlan2345["ips"][0], equal_to({"address": "1.1.1.2", "mask": 24}))
        assert_that(vlan2345["ips"][1], equal_to({"address": "1.1.1.4", "mask": 24}))
        assert_that(vlan2345["ips"][2], equal_to({"address": "2.2.2.2", "mask": 24}))

        self.delete("/switches/{switch}/vlans/2345")
    def test_set_interface_disabling(self):
        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}}))

        int002 = result.xpath("data/configuration/interfaces/interface")[0]
        assert_that(int002.xpath("disable"), has_length(0))

        self.edit({"interfaces": {"interface": [{"name": "ge-0/0/2"}, {"disable": ""}]}})
        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}}))

        int002 = result.xpath("data/configuration/interfaces/interface")[0]
        assert_that(int002.xpath("disable"), has_length(1))

        self.edit({"interfaces": {
            "interface": [{"name": "ge-0/0/2"}, {"disable": {XML_ATTRIBUTES: {"operation": "delete"}}}]}})
        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}}))

        int002 = result.xpath("data/configuration/interfaces/interface")[0]
        assert_that(int002.xpath("disable"), has_length(0))
Exemple #11
0
    def test_removing_nested_module(self):
        dashboard = DashboardFactory(title='test dashboard')
        dashboard.owners.add(self.user)
        parent = ModuleFactory(dashboard=dashboard, title='parent')
        child = ModuleFactory(
            parent=parent, dashboard=dashboard, title='module to remove')
        child_of_child = ModuleFactory(
            title='child of child', parent=child, dashboard=dashboard)
        dashboard_data = dashboard.serialize()
        dashboard_data['modules'][0]['order'] = 1
        dashboard_data['modules'][0]['type_id'] = parent.type_id
        child_data = dashboard_data['modules'][0]['modules'][0]
        child_of_child_data = child_data['modules'][0]
        child_of_child_data['order'] = 2
        child_of_child_data['type_id'] = child_of_child.type_id
        dashboard_data['modules'][0]['modules'] = [child_of_child_data]

        resp = self.client.put(
            '/dashboard/{}'.format(dashboard.id),
            json.dumps(dashboard_data, cls=JsonEncoder),
            content_type="application/json",
            HTTP_AUTHORIZATION='Bearer correct-token')

        assert_that(resp.status_code, equal_to(200))
        parent_json = json.loads(resp.content)['modules'][0]
        child_json = parent_json['modules'][0]
        assert_that(parent_json['title'], equal_to('parent'))
        assert_that(child_json['title'], equal_to('child of child'))
        assert_that(child_json['modules'], has_length(0))
        assert_that(Module.objects.filter(id=child.id), has_length(0))
        assert_that(Module.objects.get(id=child_of_child.id).parent,
                    equal_to(parent))
    def test_set_interface_description(self):
        self.edit({
            "interfaces": {
                "interface": [
                    {"name": "ge-0/0/2"},
                    {"description": "Hey there beautiful"}]}})

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}
        }))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(1))

        int002 = result.xpath("data/configuration/interfaces/interface")[0]

        assert_that(int002.xpath("name")[0].text, equal_to("ge-0/0/2"))
        assert_that(int002.xpath("description")[0].text, equal_to("Hey there beautiful"))

        self.edit({
            "interfaces": {
                "interface": [
                    {"name": "ge-0/0/2"},
                    {"description": {XML_ATTRIBUTES: {"operation": "delete"}}}]}})

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}
        }))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(0))
    def test_lock_edit_candidate_add_vlan_and_commit(self):
        with self.nc.locked(target='candidate'):
            result = self.nc.edit_config(target='candidate', config=dict_2_etree({
                "config": {
                    "configuration": {
                        "vlans": {
                            "vlan": {
                                "name": "VLAN2999",
                            }
                        }
                    }
                }}))
            assert_that(result.xpath("//rpc-reply/ok"), has_length(1))

            result = self.nc.commit()
            assert_that(result.xpath("//rpc-reply/ok"), has_length(1))

        result = self.nc.get_config(source="running")

        assert_that(result.xpath("data/configuration/vlans/vlan"), has_length(1))

        self.edit({
            "vlans": {
                "vlan": {
                    XML_ATTRIBUTES: {"operation": "delete"},
                    "name": "VLAN2999"
                }
            }
        })

        self.nc.commit()

        result = self.nc.get_config(source="running")
        assert_that(result.xpath("data/configuration/vlans/vlan"), has_length(0))
Exemple #14
0
    def test_write_progress_two_simultaneous_managers(self):
        assert_that(self.progress_manager.get_done(tasks.CANDS_TASK),
                    has_length(0))
        assert_that(self.progress_manager.get_done(tasks.REALS_TASK),
                    has_length(0))

        processed1 = "xxx2.reals.astrom"
        self.progress_manager.lock(processed1)
        self.progress_manager.record_done(processed1)

        assert_that(self.progress_manager.get_done(tasks.CANDS_TASK),
                    has_length(0))
        assert_that(self.progress_manager.get_done(tasks.REALS_TASK),
                    contains(processed1))

        # Create a second simultaneous manager
        manager2 = self.create_concurrent_progress_manager()
        processed2 = "xxx3.reals.astrom"
        self.progress_manager.lock(processed2)
        manager2.record_done(processed2)

        # Make sure second manager sees both entries
        assert_that(manager2.get_done(tasks.CANDS_TASK),
                    has_length(0))
        assert_that(manager2.get_done(tasks.REALS_TASK),
                    contains_inanyorder(processed1, processed2))

        # Make sure original manager sees both entries
        assert_that(self.progress_manager.get_done(tasks.CANDS_TASK),
                    has_length(0))
        assert_that(self.progress_manager.get_done(tasks.REALS_TASK),
                    contains_inanyorder(processed1, processed2))
Exemple #15
0
    def test_parse_file2_had_neg_crval2(self):
        astrom_data = self.parse(TEST_FILE_2)

        assert_that(astrom_data.sources, has_length(1))
        assert_that(astrom_data.observations, has_length(3))

        obs_names = [obs.rawname for obs in astrom_data.observations]
        assert_that(obs_names, contains("1616681p22", "1616692p22", "1616703p22"))
def test_check_authors_author_present_pygit2(repository_with_author_commits):
    """Test checking present authors, with pygit2."""
    pytest.importorskip("pygit2")
    options = dict(authors=["AUTHORS.rst", ],
                   path=repository_with_author_commits)
    errors = check_author('John Doe <*****@*****.**>', **options)
    assert_that(errors, has_length(0))
    errors = check_author('Jane Doe <*****@*****.**>', **options)
    assert_that(errors, has_length(0))
 def test_table_parameterized(self, query_result_example, query_results):
     if 'results' in query_result_example:
         assert_that(query_results.table,
                     has_length(len(
                         query_result_example['results']['bindings'])))
     else:
         assert_that(query_results.table[0],
                     has_key('boolean'))
         assert_that(query_results.table, has_length(1))
    def test_get_running_config(self):
        result = self.nc.get_config(source="running")

        conf = result._NCElement__result.xml
        assert_that(conf, contains_regex(
                '<configuration xmlns="http://xml.juniper.net/xnm/1.1/xnm" junos:commit-localtime="[^"]*" junos:commit-seconds="[^"]*" junos:commit-user="******"]*">'))

        assert_that(result.xpath("data/configuration/interfaces/interface/unit/family/ethernet-switching"),
                    has_length(4))
        assert_that(result.xpath("data/configuration/vlans/vlan"), has_length(0))
Exemple #19
0
    def test_adding_items(self):
        """
        Test basic case of adding items on the level
        """
        assert_that(list(get_items(self.level)), has_length(greater_than(3)))
        assert_that(list(get_items(self.level)), has_length(less_than(6)))

        assert_that(self.level, does_have_item('dagger',
                                               greater_than_or_equal_to(3)))
        assert_that(self.level, does_have_item('red potion', 1))
def test_check_authors_file_missing_gitpython(repository_with_author_commits):
    """Test checking missing authors, with GitPython."""
    pytest.importorskip("git")
    options = dict(authors=["AUTHORS.md", ],
                   path=repository_with_author_commits)
    errors = check_author('John Doe <*****@*****.**>', **options)
    assert_that(errors, has_length(1))
    assert_that(errors[0], contains_string('A101'))
    errors = check_author('Jimmy Doe <*****@*****.**>', **options)
    assert_that(errors, has_length(1))
    assert_that(errors[0], contains_string('A101'))
def test_check_authors_author_excluded_pygit2(repository_with_author_commits):
    """Test checking missing authors, with pygit2."""
    pytest.importorskip("pygit2")
    options = dict(authors=["AUTHORS.rst", ],
                   exclude_author_names=['Jimmy Doe <*****@*****.**>'],
                   path=repository_with_author_commits)
    errors = check_author('Jimmy Doe <*****@*****.**>', **options)
    assert_that(errors, has_length(0))
    errors = check_author('Jackie Doe <*****@*****.**>', **options)
    assert_that(errors, has_length(1))
    assert_that(errors[0], contains_string('A102'))
def test_overwrites_existing_attached_pictures(mp3):
    filename = mp3(APIC_FRONT=("image/jpeg", "", b"front-cover.jpg"))
    metadata = Metadata()

    container.save(filename, metadata)
    assert_that(container.load(filename).images, has_length(0), "removed images")

    metadata.addImage(mime="image/jpeg", data=b"salers.jpg", desc="Front")
    container.save(filename, metadata)

    assert_that(container.load(filename).images, has_length(1), "updated images")
    def test_display_interface_with_description_and_trunk_native_vlan(self):
        self.edit({
            "vlans": [
                {"vlan": [
                    {"name": "VLAN2995"},
                    {"vlan-id": "2995"}]},
                {"vlan": [
                    {"name": "VLAN2996"},
                    {"vlan-id": "2996"}]},
                {"vlan": [
                    {"name": "VLAN2997"},
                    {"vlan-id": "2997"}]},
            ],
            "interfaces": {
                "interface": [
                    {"name": "ge-0/0/3"},
                    {"description": "I see what you did there!"},
                    {"native-vlan-id": "2996"},
                    {"unit": [
                        {"name": "0"},
                        {"family": {
                            "ethernet-switching": {
                                "interface-mode": "trunk",
                                "vlan": [
                                    {"members": "2995"},
                                    {"members": "2997"},
                                ]}}}]}]}})
        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/3"}}}}
        }))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(1))

        int003 = result.xpath("data/configuration/interfaces/interface")[0]
        assert_that(int003.xpath("name")[0].text, equal_to("ge-0/0/3"))
        assert_that(int003.xpath("native-vlan-id")[0].text, equal_to("2996"))
        assert_that(int003.xpath("description")[0].text, equal_to("I see what you did there!"))

        assert_that(int003.xpath("unit/family/ethernet-switching/vlan/members")), has_length(2)

        members = int003.xpath("unit/family/ethernet-switching/vlan/members")
        assert_that(members[0].text, equal_to("2995"))
        assert_that(members[1].text, equal_to("2997"))

        self.cleanup(vlan("VLAN2995"), vlan("VLAN2996"), vlan("VLAN2997"),
                     interface("ge-0/0/3", ["interface-mode", "vlan"]))
        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"vlans": {}}}
        }))
        assert_that(result.xpath("data/configuration/vlans/vlan"), has_length(0))
def test_load_single_file():
    """
    Registry can load a single file.
    """
    registry = Registry()

    schema_ids = registry.load(schema_for("data/name.json"))

    assert_that(schema_ids, has_length(1))
    assert_that(schema_ids, has_item(NAME_ID))

    assert_that(registry, has_length(1))
    assert_that(registry, has_key(NAME_ID))
Exemple #25
0
    def test_create_minimal_parameters(self):
        sip = SIPEndpoint()

        created_sip = dao.create(sip)
        row = self.session.query(SIPEndpoint).first()

        assert_that(created_sip.id, equal_to(row.id))
        assert_that(created_sip.name, has_length(8))
        assert_that(created_sip.username, none())
        assert_that(created_sip.secret, has_length(8))
        assert_that(created_sip.type, equal_to('friend'))
        assert_that(created_sip.host, equal_to('dynamic'))
        assert_that(created_sip.category, equal_to('user'))
Exemple #26
0
    def test_parse_fake_file(self):
        astrom_data = self.parse(FK_FILE)

        assert_that(astrom_data.observations, has_length(3))
        assert_that(astrom_data.get_sources(), has_length(21))

        obs0 = astrom_data.observations[0]

        assert_that(obs0.rawname, equal_to("fk1616682s00"))
        assert_that(obs0.expnum, equal_to("1616682"))
        assert_that(obs0.ftype, equal_to("s"))
        assert_that(obs0.ccdnum, equal_to("00"))
        assert_that(obs0.is_fake(), equal_to(True))
Exemple #27
0
    def test_processed_indices(self):
        assert_that(self.undertest.get_processed_indices(self.file1),
                    has_length(0))
        self.undertest.lock(self.file1)
        self.undertest.record_index(self.file1, 1)
        assert_that(self.undertest.get_processed_indices(self.file1),
                    contains_inanyorder(1))

        self.undertest.record_index(self.file1, 2)
        assert_that(self.undertest.get_processed_indices(self.file1),
                    contains_inanyorder(1, 2))

        assert_that(self.undertest.get_processed_indices(self.file2),
                    has_length(0))
Exemple #28
0
    def test_draw_one_circle(self):
        axes = self.viewer.axes

        assert_that(axes.patches, has_length(0))
        cx = 1
        cy = 2
        cr = 3
        self.viewer.draw_circle(cx, cy, cr)

        assert_that(axes.patches, has_length(1))
        circle = axes.patches[0]

        assert_that(circle.center, equal_to((cx, cy)))
        assert_that(circle.radius, equal_to(cr))
Exemple #29
0
    def test_parse_cd_values(self):
        cd = wcs.parse_cd(self.header)

        assert_that(cd, has_length(2))
        assert_that(cd[0], has_length(2))
        assert_that(cd[1], has_length(2))

        # CD1_1, CD1_2
        assert_that(cd[0],
                    contains(-5.156837193510000E-05, -3.588985558218000E-07))

        # CD2_1, CD2_2
        assert_that(cd[1],
                    contains(-1.674871346376000E-07, 5.178515755263000E-05))
    def test_set_lldp(self):
        self.edit({
            "protocols": {
                "lldp": {
                    "interface": [
                        {"name": "ge-0/0/3"},
                        {"disable": ""}]}}})

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"protocols": {"lldp": {"interface": {"name": "ge-0/0/3"}}}}}
        }))

        assert_that(result.xpath("data/configuration/protocols/lldp/interface"), has_length(1))

        interface = result.xpath("data/configuration/protocols/lldp/interface")[0]

        assert_that(interface, has_length(2))
        assert_that(interface.xpath("name")[0].text, equal_to("ge-0/0/3"))
        assert_that(len(interface.xpath("disable")), equal_to(1))

        self.edit({
            "protocols": {
                "lldp": {
                    "interface": [
                        {"name": "ge-0/0/3"},
                        {"disable": {XML_ATTRIBUTES: {"operation": "delete"}}}]}}})

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"protocols": {"lldp": {"interface": {"name": "ge-0/0/3"}}}}}
        }))
        assert_that(result.xpath("data/configuration/protocols/lldp/interface")[0], has_length(1))

        self.edit({
            "protocols": {
                "lldp": {
                    "interface": {
                        XML_ATTRIBUTES: {"operation": "delete"},
                        "name": "ge-0/0/3"}}}})

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"protocols": ""}}
        }))

        assert_that(result.xpath("data/configuration/protocols"), has_length(1))
def test_get(line):
    response = confd.lines(line['id']).get()
    assert_that(
        response.item,
        has_entries(
            context=config.CONTEXT,
            position=1,
            device_slot=1,
            name=none(),
            protocol=none(),
            device_id=none(),
            caller_id_name=none(),
            caller_id_num=none(),
            registrar='default',
            provisioning_code=has_length(6),
            provisioning_extension=has_length(6),
            endpoint_sip=none(),
            endpoint_sccp=none(),
            endpoint_custom=none(),
            extensions=empty(),
            users=empty(),
        ),
    )
Exemple #32
0
    def test_should_return_shortest_distances_and_predecessors_for_differently_weighted_graph_with_many_paths(
            self):

        dg = nx.DiGraph()
        dg.add_weighted_edges_from([(0, 1, 4), (1, 3, 1), (3, 5, 1)])
        dg.add_weighted_edges_from([(0, 2, 1), (2, 4, 1), (4, 5, 1)])

        distances, predecessors = dijkstra(graph=graph.Graph(dg),
                                           source_node=0,
                                           distance_struct=self.struct)

        assert_that(distances, has_length(6))
        assert_that(distances, has_entries({
            0: 0,
            1: 4,
            2: 1,
            3: 5,
            4: 2,
            5: 3
        }))

        assert_that(predecessors, has_length(5))
        assert_that(predecessors, has_entries({1: 0, 2: 0, 3: 1, 4: 2, 5: 4}))
Exemple #33
0
    def test_set_interface_disabling(self):
        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}}))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(0))

        self.edit({"interfaces": {"interface": [{"name": "ge-0/0/2"}, {"disable": ""}]}})
        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}}))

        int002 = result.xpath("data/configuration/interfaces/interface")[0]
        assert_that(int002.xpath("disable"), has_length(1))

        self.edit({"interfaces": {
            "interface": [{"name": "ge-0/0/2"}, {"disable": {XML_ATTRIBUTES: {"operation": "delete"}}}]}})
        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}}))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(0))
    def test_union(self):
        self.context["arg2"] = 42

        assert_that(
            self.context,
            has_length(2),
        )
        assert_that(
            list(self.context),
            contains(
                "arg2",
                "arg",
            ),
        )
Exemple #35
0
    def test_ps_cmd(self):
        ps, _ = subp.call(PS_CMD)

        assert_that(ps, not_none())
        assert_that(ps, has_length(
            6))  # TODO: Try to eliminate blank line capture from ps (at end)
        assert_that(
            ps[0],
            string_contains_in_order('php-fpm:', 'master', 'process',
                                     'php-fpm.conf'))
        for child in ps[1:-1]:
            assert_that(child,
                        string_contains_in_order('php-fpm:', 'pool', 'www'))
        assert_that(ps[-1], equal_to(''))  # Try to eliminate this in future.
Exemple #36
0
def test_create_line_with_minimal_parameters():
    expected = has_entries({'callerid': none(),
                            'context': config.CONTEXT,
                            'device_slot': 1,
                            'provisioning_extension': has_length(6),
                            'secret': not_none(),
                            'username': not_none()}
                           )

    response = confd.lines_sip.post(context=config.CONTEXT,
                                    device_slot=1)

    response.assert_created('lines_sip')
    assert_that(response.item, expected)
    def test_summarise_claims(self):
        claimant_data_1 = {'foo': 'bar', 'nino': 'XX223344X'}
        employee_record_1 = {'employer_id': 1}

        claim_id = add_claim(claimant_data_1, employee_record_1)
        api.submit(claim_id)

        claims_summary = api.summarise_claims()

        assert_that(claims_summary, has_length(1))
        assert_that(claims_summary[0], has_entry('nino', 'XX223344X'))
        assert_that(claims_summary[0], has_entry('date_submitted',
                                                 is_not(None)))
        assert_that(claims_summary[0], has_entry('discrepancy', is_(False)))
Exemple #38
0
    def test_multiple_toppings(self):
        with SessionContext(self.graph), transaction():
            self.first_topping.create()
            self.second_topping.create()

        uri = "/api/v1/topping"

        response = self.client.get(uri,
                                   query_string=dict(pizza_id=str(
                                       self.new_pizza.id), ))

        assert_that(response.status_code, is_(equal_to(200)))
        data = response.json
        assert_that(data["items"], has_length(2))
Exemple #39
0
    def should_not_see_db_entry(self, table, filter_):
        """Проверяет отсутствие записей в таблице данных table удовлетворяющей условию filter_

        Args:
            table: представление таблицы БД
            (см. http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Table)
            filter_: фильтр
            (см. http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=query#sqlalchemy.orm.query.Query.filter)
        """
        assert_that(
            self.query_all(table, filter_), has_length(0),
            str(table) + u' не должна содержать запись ' +
            str(filter_.__getattribute__('left')) + ':' +
            str(filter_.__getattribute__('right').value))
Exemple #40
0
    def test_unit_add_documents_no_documents_returns_error(self):
        u = User.objects.create(is_active=True,
                                username="******")
        unit = Unit.objects.create(unit_address_1="u", owner=u)

        c = Client()
        c.force_login(u)

        response = c.post(reverse("unit-add-documents", args=[unit.slug]),
                          {"s3_images": ""})
        assert_that(response.status_code, equal_to(200))
        self.assertContains(response, "Please select at least one image.")
        unit.refresh_from_db()
        assert_that(unit.unitimage_set.all(), has_length(0))
    def test_set_interface_description(self):
        self.edit({
            "interfaces": {
                "interface": [
                    {"name": "ge-0/0/2"},
                    {"description": "Hey there beautiful"}]}})

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}
        }))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(1))

        int002 = result.xpath("data/configuration/interfaces/interface")[0]

        assert_that(int002.xpath("name")[0].text, equal_to("ge-0/0/2"))
        assert_that(int002.xpath("description")[0].text, equal_to("Hey there beautiful"))

        self.edit({
            "interfaces": {
                "interface": [
                    {"name": "ge-0/0/2"},
                    {"description": {XML_ATTRIBUTES: {"operation": "delete"}}}]}})

        self.nc.commit()

        result = self.nc.get_config(source="running", filter=dict_2_etree({"filter": {
            "configuration": {"interfaces": {"interface": {"name": "ge-0/0/2"}}}}
        }))

        assert_that(result.xpath("data/configuration/interfaces/interface"), has_length(1))

        int002 = result.xpath("data/configuration/interfaces/interface")[0]

        assert_that(int002.xpath("description"), has_length(0))
Exemple #42
0
def test__return_empty_list_or_none_if_symbol_doesnt_exist():
    nonexisting_id = 'nlu/xxx'

    asset = y.portfolio_asset(name=nonexisting_id)
    assert_that(asset, none())

    assets = y.portfolio_asset(names=[nonexisting_id])
    assert_that(assets, empty())

    assets = y.portfolio_asset(names=['micex/FXRU', nonexisting_id])
    assert_that(assets, has_length(1))

    portfolio = y.portfolio(assets={
        'micex/FXRU': 1.,
        nonexisting_id: 1.
    },
                            currency='USD')
    assert len(portfolio.assets) == 1

    nonexisting_namespace = 'yyy/FXRU'

    asset = y.portfolio_asset(name=nonexisting_namespace)
    assert_that(asset, none())

    assets = y.portfolio_asset(names=[nonexisting_namespace])
    assert_that(assets, empty())

    assets = y.portfolio_asset(names=['micex/FXRU', nonexisting_namespace])
    assert_that(assets, has_length(1))

    portfolio = y.portfolio(assets={
        'micex/FXRU': 1.,
        nonexisting_namespace: 1.
    },
                            currency='USD')
    assert_that(portfolio.assets, has_length(1))
Exemple #43
0
 def compare_nodes(self, actual_node, node):
     assert_that(unqualify(node.tag), equal_to(unqualify(actual_node.tag)))
     assert_that(node, has_length(len(actual_node)))
     if node.text is not None:
         if node.text.strip() == "":
             assert_that(actual_node.text is None
                         or actual_node.text.strip() == "")
         else:
             assert_that(node.text.strip(),
                         equal_to(actual_node.text.strip()))
     for name, value in node.attrib.items():
         assert_that(actual_node.attrib, has_key(name))
         assert_that(actual_node.attrib[name], equal_to(value))
     assert_that(actual_node.nsmap, equal_to(node.nsmap))
     self.compare_children(node, actual_node)
Exemple #44
0
    def test_shouldAssesFinalStateProperlyWhenThereIsOnlyOne(self):
        state1 = StateObjectFactory(label="state1")
        state2 = StateObjectFactory(label="state2")

        workflow = WorkflowFactory(initial_state=state1,
                                   content_type=self.content_type,
                                   field_name="my_field")

        TransitionApprovalMetaFactory.create(workflow=workflow,
                                             source_state=state1,
                                             destination_state=state2,
                                             priority=0)
        assert_that(BasicTestModel.river.my_field.final_states, has_length(1))
        assert_that(list(BasicTestModel.river.my_field.final_states),
                    has_item(state2))
Exemple #45
0
    def test_browse_assets_paging_with_continue_returns_mocked_assets(self):
        mocking.add_get_mapping_for_url(
            self.mock, 'data/contents\?continue=true&perPage=2&owner=testmock',
            'pagination_continue_page_1')
        mocking.add_get_mapping_for_url(
            self.mock,
            '/data/contents\?continue=00abcdefghijklmnopqrstuvwxyz11&owner=test&perPage=2',
            'pagination_continue_page_2')
        mocking.add_get_mapping_for_url(
            self.mock,
            '/data/contents\?continue=00abcdefghijklmnopqrstuvwxyz22&owner=test&perPage=2',
            'pagination_continue_page_3')

        under_test = self.client.metadata.contents

        under_test_browse = under_test.browse(
            'testmock', query_string='continue=true&perPage=2')

        response_list = [response for response in under_test_browse]

        assert_that(response_list, has_length(3))
        assert_that(response_list[0].resources, has_length(2))
        assert_that(response_list[1].resources, has_length(2))
        assert_that(response_list[2].resources, has_length(1))
        assert_that(response_list[0].resources[0]['name'],
                    is_('001436b2-93b7-43c5-89a3-b95ceb50aa73'))
        assert_that(
            response_list[0].resources[1]['name'],
            is_('001436b2-93b7-43c5-89a3-b95ceb50aa73_aligned_primary'))
        assert_that(response_list[1].resources[0]['name'],
                    is_('001436b2-93b7-43c5-89a3-b95ceb50aa73_primary'))
        assert_that(response_list[1].resources[1]['name'],
                    is_('001436b2-93b7-43c5-89a3-b95ceb50aa73_textless'))
        assert_that(
            response_list[2].resources[0]['name'],
            is_('0065ab4e-caf9-4096-8b3b-df4a8f3f19dd_aligned_primary'))
Exemple #46
0
    def test_find_by_context(self):
        expected_context = 'hhi'

        exten = self.add_extension(context=expected_context)
        self.add_extension(context='guj')
        self.add_extension(context='asc')

        extens = extension_dao.find_by_context(expected_context)

        assert_that(extens, has_length(1))
        assert_that(
            extens,
            has_items(
                all_of(has_property('id', exten.id),
                       has_property('context', expected_context))))
 def test_get_seats_schema(self):
     response = self.client.get(self.movie_session_100_90_url + 'seats/')
     assert_that(
         response,
         has_properties(
             status_code=HTTP_200_OK,
             data=has_entries(
                 rows_number=self.movie_session_100_90.hall.rows_number,
                 seats_per_row=self.movie_session_100_90.hall.seats_per_row,
                 booked_seats=all_of(
                     has_length(1),
                     has_item(has_entries(
                         row_number=5,
                         seat_number=5,
                     ), )))))
Exemple #48
0
def test_create_line_with_minimal_parameters():
    response = confd.lines_sip.post(context=config.CONTEXT, device_slot=1)

    response.assert_created('lines_sip')
    assert_that(
        response.item,
        has_entries(
            callerid=none(),
            context=config.CONTEXT,
            device_slot=1,
            provisioning_extension=has_length(6),
            secret=not_none(),
            username=not_none(),
        ),
    )
Exemple #49
0
    def test_parse_pv_values(self):
        pv = wcs.parse_pv(self.header)

        assert_that(pv, has_length(2))
        assert_that(pv[0], has_length(11))
        assert_that(pv[1], has_length(11))

        # PV1_0 through PV1_10
        assert_that(
            pv[0],
            contains(-1.909806626877E-03, 1.00815723310, 1.983393486250E-03,
                     0.00000000000, 4.623172227977E-05, -1.020423075276E-05,
                     2.258600565396E-05, -2.354656733463E-02,
                     -1.671912720931E-04, -2.339051960031E-02,
                     -2.903290518437E-05))

        # PV2_0 through PV2_10
        assert_that(
            pv[1],
            contains(-7.294883106769E-04, 1.00392029973, 1.983331686156E-03,
                     0.00000000000, 3.022667872225E-05, 4.509364811534E-05,
                     -5.385195875663E-06, -2.333221106141E-02,
                     -1.789051786060E-04, -2.348803123711E-02,
                     -2.465552723903E-05))
Exemple #50
0
def test_warn():
    """
    Warn is deprecated in place of warning.

    """
    tree = parse(dedent("""\
        import logging

        logging.warn("Hello World!")
    """))
    visitor = LoggingVisitor()
    visitor.visit(tree)

    assert_that(visitor.violations, has_length(1))
    assert_that(visitor.violations[0][1], is_(equal_to(WARN_VIOLATION)))
Exemple #51
0
    def test_other_link(self):
        self.dashboard.add_other_link('blah', 'http://www.gov.uk')
        self.dashboard.add_other_link('blah2', 'http://www.gov.uk')
        self.dashboard.validate_and_save()
        links = self.dashboard.link_set.all()

        assert_that(links, has_length(2))
        assert_that(
            links,
            has_items(
                has_property('title', 'blah'),
                has_property('title', 'blah2'),
            ))
        assert_that(self.dashboard.link_set.first().link_type,
                    equal_to('other'))
Exemple #52
0
def test_debug_string_format():
    """
    String formatting is not ok in logging statements.

    """
    tree = parse(dedent("""\
        import logging

        logging.debug("Hello {}".format("World!"))
    """))
    visitor = LoggingVisitor()
    visitor.visit(tree)

    assert_that(visitor.violations, has_length(1))
    assert_that(visitor.violations[0][1], is_(equal_to(STRING_FORMAT_VIOLATION)))
def RunNotifyUserIfServerCrashed(ycm, test, post_vim_message):
    StopServer(ycm)

    ycm._logger = MagicMock(autospec=True)
    ycm._server_popen = MagicMock(autospec=True)
    ycm._server_popen.poll.return_value = test['return_code']

    ycm._NotifyUserIfServerCrashed()

    assert_that(ycm._logger.method_calls,
                has_length(len(test['expected_logs'])))
    ycm._logger.error.assert_has_calls(
        [call(log) for log in test['expected_logs']])
    post_vim_message.assert_has_exact_calls(
        [call(test['expected_vim_message'])])
Exemple #54
0
    def test_find_by_exten(self):
        expected_exten = '1234'

        exten = self.add_extension(exten=expected_exten)
        self.add_extension(exten='1236')
        self.add_extension(exten='8652')

        extens = extension_dao.find_by_exten(expected_exten)

        assert_that(extens, has_length(1))
        assert_that(
            extens,
            has_items(
                all_of(has_property('id', exten.id),
                       has_property('exten', expected_exten))))
Exemple #55
0
    def test_broken(self):
        # The functionality itself is broken.
        import warnings

        class UIDS(object):
            def queryObject(self, uid):
                return None

        with warnings.catch_warnings(record=True) as w:
            r = ResultSet((1, ), UIDS(), True)

        x = r.get_object(1)
        assert_that(x, is_(none()))

        assert_that(w, has_length(1))
Exemple #56
0
def test_format_percent():
    """
    Percent formatting is not ok in logging statements.

    """
    tree = parse(dedent("""\
        import logging

        logging.info("Hello %s" % "World!")
    """))
    visitor = LoggingVisitor()
    visitor.visit(tree)

    assert_that(visitor.violations, has_length(1))
    assert_that(visitor.violations[0][1], is_(equal_to(PERCENT_FORMAT_VIOLATION)))
Exemple #57
0
    def test_update_indexes_with_error(self):
        from zope.testing.loggingsupport import InstalledHandler
        handler = InstalledHandler('nti.zope_catalog.catalog')
        self.addCleanup(handler.uninstall)

        cat = self._makeOne()
        cat._PERSISTENCE_EXCEPTIONS = AttributeError

        cat['key'] = 42

        cat.updateIndexes(ignore_persistence_exceptions=True)

        assert_that(handler.records, has_length(1))
        assert_that(handler.records[0].msg,
                    is_("Error indexing object %s(%s); %s"))
    def test_connecting_2x2_grid(self):
        """
        Test that 2x2 grid is fully connected
        """
        section00 = new_section((0, 0), (5, 5), self.level, self.rng)
        section10 = new_section((6, 0), (10, 5), self.level, self.rng)
        section01 = new_section((0, 6), (5, 10), self.level, self.rng)
        section11 = new_section((6, 6), (10, 10), self.level, self.rng)

        mark_neighbours(section00, section10)
        mark_neighbours(section00, section01)
        mark_neighbours(section10, section11)
        mark_neighbours(section01, section11)

        sections = [section00, section10, section01, section11]

        connected_sections = self.connector.connect_sections(sections)

        assert_that(connected_sections, has_length(4))

        for section in connected_sections:
            assert_that(list(section_connections(section)),
                        has_length(greater_than(0)))
            assert_that(is_connected(section))
Exemple #59
0
def test_select_returns_rows(db):
    assert_that(
        db,
        given_select_returns_rows_matching(
            "SELECT * FROM sausages WHERE rating > 5;", has_length(2)),
    )
    assert_that(
        db,
        not_(
            given_select_returns_rows_matching(
                "SELECT * FROM sausages WHERE rating > 5;", has_length(99))),
    )
    assert_that(
        given_select_returns_rows_matching(
            "SELECT * FROM sausages WHERE rating > 5;", has_length(2)),
        has_string("DB connection for which statement "
                   "'SELECT * FROM sausages WHERE rating > 5;' "
                   "returns rows matching an object with length of <2>"),
    )
    assert_that(
        given_select_returns_rows_matching(
            "SELECT * FROM sausages WHERE rating > 5;", has_length(99)),
        mismatches_with(db, contains_string("with length of <2>")),
    )
Exemple #60
0
def test_events_to_date_all(
    event_class_factory,
    event_factory,
    company_factory,
    subscriptions_type_factory,
):
    start_date = date(2019, 1, 1)
    end_date = date(2019, 1, 31)
    company = company_factory()

    # By default event class if for every day
    ecs: List[models.EventClass] = event_class_factory.create_batch(
        2,
        company=company,
        date_from=start_date,
        date_to=end_date
    )

    cs: models.SubscriptionsType = subscriptions_type_factory(
        company=company,
        event_class__events=ecs,
        rounding=True,
        duration=1,
        duration_type=GRANULARITY.MONTH
    )
    event_factory(
        company=company,
        event_class=ecs[0],
        date=date(2019, 1, 1),
        canceled_at=date(2019, 1, 1)
    )
    event_factory(
        company=company,
        event_class=ecs[1],
        date=date(2019, 1, 2),
        canceled_at=date(2019, 1, 1)
    )

    cs_events = cs.events_to_date(
        from_date=start_date,
        to_date=start_date + timedelta(days=6),
        filter_runner=SubscriptionsTypeEventFilter.ALL
    )

    # Client subscription have 2 event classes, so one week count * 2 and
    # 2 canceled events

    assert_that(cs_events, has_length(14))