示例#1
0
 def test_diff(self):
     test_values = {
         "id": 123,
         "custom_fields": {
             "foo": "bar"
         },
         "string_field": "foobar",
         "int_field": 1,
         "nested_dict": {
             "id": 222,
             "name": "bar"
         },
         "tags": ["foo", "bar"],
         "int_list": [123, 321, 231],
         "local_context_data": {
             "data": ["one"]
         },
     }
     test = Record(test_values, None, None)
     test.tags.append("baz")
     test.nested_dict = 1
     test.string_field = "foobaz"
     test.local_context_data["data"].append("two")
     self.assertEqual(
         test._diff(),
         {"tags", "nested_dict", "string_field", "local_context_data"})
示例#2
0
 def test_serialize_list_of_records(self):
     test_values = {
         "id":
         123,
         "tagged_vlans": [
             {
                 "id": 1,
                 "url": "http://localhost:8000/api/ipam/vlans/1/",
                 "vid": 1,
                 "name": "test1",
                 "display_name": "test1",
             },
             {
                 "id": 2,
                 "url": "http://localhost:8000/api/ipam/vlans/2/",
                 "vid": 2,
                 "name": "test 2",
                 "display_name": "test2",
             },
         ],
     }
     test_obj = Record(test_values, Mock(base_url="test", version="2.8"),
                       None)
     test = test_obj.serialize()
     self.assertEqual(test["tagged_vlans"], [1, 2])
示例#3
0
 def test_choices_idempotence_v28(self):
     test_values = {
         "id": 123,
         "choices_test": {"value": "test", "label": "test",},
     }
     test = Record(test_values, None, None)
     test.choices_test = "test"
     self.assertFalse(test._diff())
示例#4
0
 def test_endpoint_from_url(self):
     test = Record(
         {
             "id": 123,
             "name": "test",
             "url": "http://localhost:8080/api/test-app/test-endpoint/1/",
         },
         Mock(),
         None,
     )
     ret = test._endpoint_from_url(test.url)
     self.assertEqual(ret.name, "test-endpoint")
示例#5
0
 def test_endpoint_from_url_with_directory_in_base_url(self):
     api = Mock()
     api.base_url = "http://localhost:8080/testing/api"
     test = Record(
         {
             "id": 123,
             "name": "test",
             "url": "http://localhost:8080/testing/api/test-app/test-endpoint/1/",
         },
         api,
         None,
     )
     ret = test._endpoint_from_url(test.url)
     self.assertEqual(ret.name, "test-endpoint")
示例#6
0
 def test_endpoint_from_url_with_plugins(self):
     api = Mock()
     api.base_url = "http://localhost:8080/api"
     api.external_proxy = False
     test = Record(
         {
             "id": 123,
             "name": "test",
             "url": "http://localhost:8080/api/plugins/test-app/test-endpoint/1/",
         },
         api,
         None,
     )
     ret = test._endpoint_from_url(test.url)
     self.assertEqual(ret.name, "test-endpoint")
示例#7
0
 def test_endpoint_from_url_with_plugins_and_directory_in_base_url_behind_external_proxy(self):
     api = Mock()
     api.base_url = "http://example.com/testing/api"
     api.external_proxy = True
     test = Record(
         {
             "id": 123,
             "name": "test",
             "url": "http://localhost:8080/testing/api/plugins/test-app/test-endpoint/1/",
         },
         api,
         None,
     )
     ret = test._endpoint_from_url(test.url)
     self.assertEqual(ret.name, "test-endpoint")
示例#8
0
 def test_nested_write_with_directory_in_base_url(self):
     app = Mock()
     app.token = "abc123"
     app.base_url = "http://localhost:8080/testing/api"
     endpoint = Mock()
     endpoint.name = "test-endpoint"
     test = Record(
         {
             "id": 123,
             "name": "test",
             "child": {
                 "id":
                 321,
                 "name":
                 "test123",
                 "url":
                 "http://localhost:8080/testing/api/test-app/test-endpoint/321/",
             },
         },
         app,
         endpoint,
     )
     test.child.name = "test321"
     test.child.save()
     self.assertEqual(
         app.http_session.patch.call_args[0][0],
         "http://localhost:8080/testing/api/test-app/test-endpoint/321/",
     )
示例#9
0
    def test_bulk_update_records(self):
        with patch("pynetbox.core.query.Request._make_call",
                   return_value=Mock()) as mock:
            from pynetbox.core.response import Record

            ids = [1, 3, 5]
            mock.return_value = True
            api = Mock(base_url="http://localhost:8000/api")
            app = Mock(name="test")
            test_obj = Endpoint(api, app, "test")
            objects = [
                Record(
                    {
                        "id": i,
                        "name": "dummy" + str(i),
                        "unchanged": "yes"
                    },
                    api,
                    test_obj,
                ) for i in ids
            ]
            for o in objects:
                o.name = "fluffy" + str(o.id)
            mock.return_value = [o.serialize() for o in objects]
            test = test_obj.update(objects)
            mock.assert_called_with(verb="patch",
                                    data=[{
                                        "id": i,
                                        "name": "fluffy" + str(i)
                                    } for i in ids])
            self.assertTrue(test)
示例#10
0
 def test_diff_append_records_list(self):
     test_values = {
         "id":
         123,
         "tagged_vlans": [{
             "id": 1,
             "url": "http://localhost:8000/api/ipam/vlans/1/",
             "vid": 1,
             "name": "test1",
             "display_name": "test1",
         }],
     }
     test_obj = Record(test_values, Mock(base_url="test"), None)
     test_obj.tagged_vlans.append(1)
     test = test_obj._diff()
     self.assertFalse(test)
示例#11
0
 def test_dict(self):
     test_values = {
         "id": 123,
         "custom_fields": {"foo": "bar"},
         "string_field": "foobar",
         "int_field": 1,
         "nested_dict": {"id": 222, "name": "bar"},
         "tags": ["foo", "bar"],
         "int_list": [123, 321, 231],
         "empty_list": [],
         "record_list": [
             {
                 "id": 123,
                 "name": "Test",
                 "str_attr": "foo",
                 "int_attr": 123,
                 "custom_fields": {"foo": "bar"},
                 "tags": ["foo", "bar"],
             },
             {
                 "id": 321,
                 "name": "Test 1",
                 "str_attr": "bar",
                 "int_attr": 321,
                 "custom_fields": {"foo": "bar"},
                 "tags": ["foo", "bar"],
             },
         ],
     }
     test = Record(test_values, None, None)
     self.assertEqual(dict(test), test_values)
示例#12
0
 def test_nested_write(self):
     api = Mock()
     api.token = "abc123"
     api.base_url = "http://localhost:8080/api"
     api.external_proxy = False
     endpoint = Mock()
     endpoint.name = "test-endpoint"
     test = Record(
         {
             "id": 123,
             "name": "test",
             "child": {
                 "id": 321,
                 "name": "test123",
                 "url": "http://localhost:8080/api/test-app/test-endpoint/321/",
             },
         },
         api,
         endpoint,
     )
     test.child.name = "test321"
     test.child.save()
     self.assertEqual(
         api.http_session.patch.call_args[0][0],
         "http://localhost:8080/api/test-app/test-endpoint/321/",
     )
示例#13
0
 def test_nested_write_with_directory_in_base_url_behind_external_proxy(self):
     api = Mock()
     api.token = "abc123"
     api.base_url = "http://example.com/netbox/testing/api"
     api.external_proxy = True
     endpoint = Mock()
     endpoint.name = "test-endpoint"
     test = Record(
         {
             "id": 123,
             "name": "test",
             "child": {
                 "id": 321,
                 "name": "test123",
                 "url": "http://localhost:8080/testing/api/test-app/test-endpoint/321/",
             },
         },
         api,
         endpoint,
     )
     test.child.name = "test321"
     test.child.save()
     self.assertEqual(
         api.http_session.patch.call_args[0][0],
         "http://example.com/netbox/testing/api/test-app/test-endpoint/321/",
     )
示例#14
0
 def test_serialize_dict_tag_set(self):
     test_values = {
         "id": 123,
         "tags": [
             {"id": 1, "name": "foo",},
             {"id": 2, "name": "bar",},
             {"id": 3, "name": "baz",},
         ],
     }
     test = Record(test_values, None, None).serialize()
     self.assertEqual(len(test["tags"]), 3)
示例#15
0
 def test_attribute_access(self):
     test_values = {
         "id": 123,
         "units": 12,
         "nested_dict": {"id": 222, "name": "bar"},
         "int_list": [123, 321, 231],
     }
     test_obj = Record(test_values, None, None)
     self.assertEqual(test_obj.id, 123)
     self.assertEqual(test_obj.units, 12)
     self.assertEqual(test_obj.nested_dict.name, "bar")
     self.assertEqual(test_obj.int_list[1], 321)
     with self.assertRaises(AttributeError) as _:
         test_obj.nothing
示例#16
0
 def test_dict_access(self):
     test_values = {
         "id": 123,
         "units": 12,
         "nested_dict": {"id": 222, "name": "bar"},
         "int_list": [123, 321, 231],
     }
     test_obj = Record(test_values, None, None)
     self.assertEqual(test_obj["id"], 123)
     self.assertEqual(test_obj["units"], 12)
     self.assertEqual(test_obj["nested_dict"]["name"], "bar")
     self.assertEqual(test_obj["int_list"][1], 321)
     with self.assertRaises(KeyError) as _:
         test_obj["nothing"]
示例#17
0
文件: shell.py 项目: codeout/nbcli
            def nbmodels(display='model'):
                """List available pynetbox models"""
                modeldict = dict()

                for key, value in nbns.items():
                    if isinstance(value, Endpoint):
                        app = value.url.split('/')[-2].title()
                        if app in modeldict.keys():
                            modeldict[app].append((key, value))
                        else:
                            modeldict[app] = list()
                            modeldict[app].append((key, value))

                for app, modellist in sorted(modeldict.items()):
                    print(app + ':')
                    for model in sorted(modellist):
                        if display == 'loc':
                            obj = Record({}, model[1].api, model[1])
                            print('  ' + app_model_loc(obj))
                        elif display == 'view':
                            obj = Record({}, model[1].api, model[1])
                            print('  ' + get_view_name(obj))
                        else:
                            print('  ' + model[0])
示例#18
0
 def test_compare(self):
     endpoint1 = Mock()
     endpoint1.name = "test-endpoint"
     endpoint2 = Mock()
     endpoint2.name = "test-endpoint"
     test1 = Record({}, None, endpoint1)
     test1.id = 1
     test2 = Record({}, None, endpoint2)
     test2.id = 1
     self.assertEqual(test1, test2)
示例#19
0
 def test_hash_diff(self):
     endpoint1 = Mock()
     endpoint1.name = "test-endpoint"
     endpoint2 = Mock()
     endpoint2.name = "test-endpoint"
     test1 = Record({}, None, endpoint1)
     test1.id = 1
     test2 = Record({}, None, endpoint2)
     test2.id = 2
     self.assertNotEqual(hash(test1), hash(test2))
示例#20
0
文件: utils.py 项目: codeout/nbcli
def add_detail_endpoint(model, name, RO=False, custom_return=None):

    assert model in Record.__subclasses__(), 'model must b subclass of Record'

    @property
    def detail_ep(self):
        return DetailEndpoint(self, name, custom_return=custom_return)

    @property
    def ro_detail_ep(self):
        return RODetailEndpoint(self, name, custom_return=custom_return)

    if RO:
        setattr(model, name, ro_detail_ep)
    else:
        setattr(model, name, detail_ep)
示例#21
0
 def test_nested_write(self):
     app = Mock()
     app.token = 'abc123'
     endpoint = Mock()
     endpoint.name = "test-endpoint"
     test = Record({
         'id': 123,
         'name': 'test',
         'child': {
             'id': 321,
             'name': 'test123',
             'url': 'http://localhost:8080/test',
         },
     }, app, endpoint)
     test.child.name = 'test321'
     test.child.save()
     self.assertEqual(app.http_session.patch.call_args[0][0], "http://localhost:8080/test/")
示例#22
0
    def create_token(self, username, password):
        """Creates an API token using a valid NetBox username and password.
        Saves the created token automatically in the API object.

        Requires NetBox 3.0.0 or newer.

        :Returns: The token as a ``Record`` object.
        :Raises: :py:class:`.RequestError` if the request is not successful.

        :Example:

        >>> import pynetbox
        >>> nb = pynetbox.api("https://netbox-server")
        >>> token = nb.create_token("admin", "netboxpassword")
        >>> nb.token
        '96d02e13e3f1fdcd8b4c089094c0191dcb045bef'
        >>> from pprint import pprint
        >>> pprint(dict(token))
        {'created': '2021-11-27T11:26:49.360185+02:00',
         'description': '',
         'display': '045bef (admin)',
         'expires': None,
         'id': 2,
         'key': '96d02e13e3f1fdcd8b4c089094c0191dcb045bef',
         'url': 'https://netbox-server/api/users/tokens/2/',
         'user': {'display': 'admin',
                  'id': 1,
                  'url': 'https://netbox-server/api/users/users/1/',
                  'username': '******'},
         'write_enabled': True}
        >>>
        """
        resp = Request(
            base="{}/users/tokens/provision/".format(self.base_url),
            http_session=self.http_session,
        ).post(data={
            "username": username,
            "password": password
        })
        # Save the newly created API token, otherwise populating the Record
        # object details will fail
        self.token = resp["key"]
        return Record(resp, self, None)
示例#23
0
    def test_serialize_tag_list_order(self):
        """Add tests to ensure we're preserving tag order

        This test could still give false-negatives, but making the tag list
        longer helps mitigate that.
        """

        test_tags = [
            "one",
            "two",
            "three",
            "four",
            "five",
            "six",
            "seven",
            "eight",
            "nine",
            "ten",
        ]
        test = Record({"id": 123, "tags": test_tags}, None, None).serialize()
        self.assertEqual(test["tags"], test_tags)
示例#24
0
    def test_delete_with_objects(self):
        with patch("pynetbox.core.query.Request._make_call",
                   return_value=Mock()) as mock:
            from pynetbox.core.response import Record

            ids = [1, 3, 5]
            mock.return_value = True
            api = Mock(base_url="http://localhost:8000/api")
            app = Mock(name="test")
            test_obj = Endpoint(api, app, "test")
            objects = [
                Record({
                    "id": i,
                    "name": "dummy" + str(i)
                }, api, test_obj) for i in ids
            ]
            test = test_obj.delete(objects)
            mock.assert_called_with(verb="delete",
                                    data=[{
                                        "id": i
                                    } for i in ids])
            self.assertTrue(test)
示例#25
0
 def test_serialize_string_tag_set(self):
     test_values = {"id": 123, "tags": ["foo", "bar", "foo"]}
     test = Record(test_values, None, None).serialize()
     self.assertEqual(len(test["tags"]), 2)
示例#26
0
 def test_serialize_list_of_ints(self):
     test_values = {"id": 123, "units": [12]}
     test_obj = Record(test_values, None, None)
     test = test_obj.serialize()
     self.assertEqual(test["units"], [12])
示例#27
0
 def test_hash(self):
     endpoint = Mock()
     endpoint.name = "test-endpoint"
     test = Record({}, None, endpoint)
     self.assertIsInstance(hash(test), int)