diff --git a/.github/workflows/py2pr.yml b/.github/workflows/py2pr.yml new file mode 100644 index 00000000..93ecc98f --- /dev/null +++ b/.github/workflows/py2pr.yml @@ -0,0 +1,26 @@ +name: PR Test + +on: [pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python: [2.7] + + steps: + - uses: actions/checkout@v2 + + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + + - name: Install pynetbox and testing packages. + run: pip install . mock + + - name: Run Tests + run: python -m unittest discover + diff --git a/.github/workflows/pr.yml b/.github/workflows/py3pr.yml similarity index 66% rename from .github/workflows/pr.yml rename to .github/workflows/py3pr.yml index c42d8d29..2e5ecdfd 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/py3pr.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python: [2.7, 3.6] + python: [3.6, 3.8] steps: - uses: actions/checkout@v2 @@ -19,13 +19,11 @@ jobs: python-version: ${{ matrix.python }} - name: Install pynetbox and testing packages. - run: pip install . pycodestyle mock + run: pip install . black pytest - name: Run Linter - run: | - pycodestyle pynetbox - pycodestyle --ignore=E501 tests + run: black --check . - name: Run Tests - run: python -m unittest discover + run: pytest diff --git a/docs/conf.py b/docs/conf.py index c1d27184..05b09fce 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,7 +19,8 @@ import os import sys from pkg_resources import get_distribution -sys.path.insert(0, os.path.abspath('../')) + +sys.path.insert(0, os.path.abspath("../")) # -- General configuration ------------------------------------------------ @@ -31,33 +32,33 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = ['sphinx.ext.autodoc'] +extensions = ["sphinx.ext.autodoc"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'pynetbox' -copyright = u'2017, DigitalOcean' -author = u'Zach Moody' +project = u"pynetbox" +copyright = u"2017, DigitalOcean" +author = u"Zach Moody" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # The full version, including alpha/beta/rc tags. -release = get_distribution('pynetbox').version +release = get_distribution("pynetbox").version # # The short X.Y version. -version = '.'.join(release.split('.')[:2]) +version = ".".join(release.split(".")[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -69,10 +70,10 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -96,18 +97,14 @@ # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] -html_sidebars = {'**': [ - 'globaltoc.html', - 'relations.html', - 'sourcelink.html', - 'searchbox.html' - ] +html_sidebars = { + "**": ["globaltoc.html", "relations.html", "sourcelink.html", "searchbox.html"] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. -htmlhelp_basename = 'pynetboxdoc' +htmlhelp_basename = "pynetboxdoc" # -- Options for LaTeX output --------------------------------------------- @@ -116,15 +113,12 @@ # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. # # 'preamble': '', - # Latex figure (float) alignment # # 'figure_align': 'htbp', @@ -134,8 +128,7 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'pynetbox.tex', u'pynetbox Documentation', - u'Zach Moody', 'manual'), + (master_doc, "pynetbox.tex", u"pynetbox Documentation", u"Zach Moody", "manual"), ] @@ -143,10 +136,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'pynetbox', u'pynetbox Documentation', - [author], 1) -] +man_pages = [(master_doc, "pynetbox", u"pynetbox Documentation", [author], 1)] # -- Options for Texinfo output ------------------------------------------- @@ -155,7 +145,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'pynetbox', u'pynetbox Documentation', - author, 'pynetbox', 'A python library for NetBox.', - 'Miscellaneous'), + ( + master_doc, + "pynetbox", + u"pynetbox Documentation", + author, + "pynetbox", + "A python library for NetBox.", + "Miscellaneous", + ), ] diff --git a/pynetbox/api.py b/pynetbox/api.py index 8a9d7064..74193d1b 100644 --- a/pynetbox/api.py +++ b/pynetbox/api.py @@ -62,12 +62,7 @@ class Api(object): """ def __init__( - self, - url, - token=None, - private_key=None, - private_key_file=None, - threading=False, + self, url, token=None, private_key=None, private_key_file=None, threading=False, ): if private_key and private_key_file: raise ValueError( @@ -81,8 +76,10 @@ def __init__( self.session_key = None self.http_session = requests.Session() if threading and sys.version_info.major == 2: - raise NotImplementedError("Threaded pynetbox calls not supported \ - in Python 2") + raise NotImplementedError( + "Threaded pynetbox calls not supported \ + in Python 2" + ) self.threading = threading if self.private_key_file: @@ -119,8 +116,7 @@ def version(self): >>> """ version = Request( - base=self.base_url, - http_session=self.http_session, + base=self.base_url, http_session=self.http_session, ).get_version() return version @@ -143,6 +139,5 @@ def openapi(self): >>> """ return Request( - base=self.base_url, - http_session=self.http_session, + base=self.base_url, http_session=self.http_session, ).get_openapi() diff --git a/pynetbox/core/app.py b/pynetbox/core/app.py index d4196ff6..c51e7ed8 100644 --- a/pynetbox/core/app.py +++ b/pynetbox/core/app.py @@ -27,6 +27,7 @@ class App(object): :raises: :py:class:`.RequestError` if requested endpoint doesn't exist. """ + def __init__(self, api, name): self.api = api self.name = name @@ -38,18 +39,14 @@ def __init__(self, api, name): "ipam": ipam, "circuits": circuits, "virtualization": virtualization, - "extras": extras + "extras": extras, } def _setmodel(self): self.model = App.models[self.name] if self.name in App.models else None def __getstate__(self): - return { - 'api': self.api, - 'name': self.name, - '_choices': self._choices - } + return {"api": self.api, "name": self.name, "_choices": self._choices} def __setstate__(self, d): self.__dict__.update(d) @@ -68,7 +65,7 @@ def _set_session_key(self): base=self.api.base_url, token=self.api.token, private_key=self.api.private_key, - http_session=self.api.http_session + http_session=self.api.http_session, ).get_session_key() def choices(self): @@ -106,10 +103,7 @@ def custom_choices(self): 'Testfield2': {'Othervalue2': 4, 'Othervalue1': 3}} """ custom_field_choices = Request( - base="{}/{}/_custom_field_choices/".format( - self.api.base_url, - self.name, - ), + base="{}/{}/_custom_field_choices/".format(self.api.base_url, self.name,), token=self.api.token, private_key=self.api.private_key, http_session=self.api.http_session, diff --git a/pynetbox/core/endpoint.py b/pynetbox/core/endpoint.py index bd694924..a88b722c 100644 --- a/pynetbox/core/endpoint.py +++ b/pynetbox/core/endpoint.py @@ -21,10 +21,7 @@ def response_loader(req, return_obj, endpoint): if isinstance(req, list): - return [ - return_obj(i, endpoint.api, endpoint) - for i in req - ] + return [return_obj(i, endpoint.api, endpoint) for i in req] return return_obj(req, endpoint.api, endpoint) @@ -57,9 +54,7 @@ def __init__(self, api, app, name, model=None): self.token = api.token self.session_key = api.session_key self.url = "{base_url}/{app}/{endpoint}".format( - base_url=self.base_url, - app=app.name, - endpoint=self.name, + base_url=self.base_url, app=app.name, endpoint=self.name, ) self._choices = None @@ -211,9 +206,7 @@ def filter(self, *args, **kwargs): kwargs.update({"q": args[0]}) if not kwargs: - raise ValueError( - "filter must be passed kwargs. Perhaps use all() instead." - ) + raise ValueError("filter must be passed kwargs. Perhaps use all() instead.") if any(i in RESERVED_KWARGS for i in kwargs): raise ValueError( "A reserved {} kwarg was passed. Please remove it " @@ -330,17 +323,15 @@ def choices(self): http_session=self.api.http_session, ).options() try: - post_data = req['actions']['POST'] + post_data = req["actions"]["POST"] except KeyError: raise ValueError( - "Unexpected format in the OPTIONS response at {}".format( - self.url - ) + "Unexpected format in the OPTIONS response at {}".format(self.url) ) self._choices = {} for prop in post_data: - if 'choices' in post_data[prop]: - self._choices[prop] = post_data[prop]['choices'] + if "choices" in post_data[prop]: + self._choices[prop] = post_data[prop]["choices"] return self._choices @@ -405,9 +396,7 @@ class DetailEndpoint(object): def __init__(self, parent_obj, name, custom_return=None): self.parent_obj = parent_obj self.custom_return = custom_return - self.url = "{}/{}/{}/".format( - parent_obj.endpoint.url, parent_obj.id, name - ) + self.url = "{}/{}/{}/".format(parent_obj.endpoint.url, parent_obj.id, name) self.request_kwargs = dict( base=self.url, token=parent_obj.api.token, @@ -431,9 +420,7 @@ def list(self, **kwargs): req = Request(**self.request_kwargs).get(add_params=kwargs) if self.custom_return: - return response_loader( - req, self.custom_return, self.parent_obj.endpoint - ) + return response_loader(req, self.custom_return, self.parent_obj.endpoint) return req def create(self, data=None): @@ -452,14 +439,10 @@ def create(self, data=None): data = data or {} req = Request(**self.request_kwargs).post(data) if self.custom_return: - return response_loader( - req, self.custom_return, self.parent_obj.endpoint - ) + return response_loader(req, self.custom_return, self.parent_obj.endpoint) return req class RODetailEndpoint(DetailEndpoint): def create(self, data): - raise NotImplementedError( - "Writes are not supported for this endpoint." - ) + raise NotImplementedError("Writes are not supported for this endpoint.") diff --git a/pynetbox/core/query.py b/pynetbox/core/query.py index fcb26336..f4222a2d 100644 --- a/pynetbox/core/query.py +++ b/pynetbox/core/query.py @@ -58,9 +58,7 @@ def __init__(self, message): req = message if req.status_code == 404: - message = "The requested url: {} could not be found.".format( - req.url - ) + message = "The requested url: {} could not be found.".format(req.url) else: try: message = "The request failed with code {} {}: {}".format( @@ -113,8 +111,7 @@ def __init__(self, message): req = message message = ( - "The server returned invalid (non-json) data. Maybe not " - "a NetBox server?" + "The server returned invalid (non-json) data. Maybe not " "a NetBox server?" ) super(ContentError, self).__init__(message) @@ -200,10 +197,7 @@ def get_version(self): headers = { "Content-Type": "application/json;", } - req = requests.get( - self.normalize_url(self.base), - headers=headers, - ) + req = requests.get(self.normalize_url(self.base), headers=headers,) if req.ok: return req.headers.get("API-Version", "") else: @@ -242,9 +236,7 @@ def normalize_url(self, url): return url - def _make_call( - self, verb="get", url_override=None, add_params=None, data=None - ): + def _make_call(self, verb="get", url_override=None, add_params=None, data=None): if verb in ("post", "put"): headers = {"Content-Type": "application/json;"} else: @@ -263,8 +255,7 @@ def _make_call( params.update(add_params) req = getattr(self.http_session, verb)( - url_override or self.url, headers=headers, - params=params, json=data + url_override or self.url, headers=headers, params=params, json=data ) if req.status_code == 204 and verb == "post": @@ -318,10 +309,12 @@ def req_all(): # passed in here because results from detail routes aren't # paginated, thus far. if first_run: - req = self._make_call(add_params={ - "limit": req["count"], - "offset": len(req["results"]) - }) + req = self._make_call( + add_params={ + "limit": req["count"], + "offset": len(req["results"]), + } + ) else: req = self._make_call(url_override=req["next"]) first_run = False diff --git a/pynetbox/core/response.py b/pynetbox/core/response.py index 7f34f6a8..52856853 100644 --- a/pynetbox/core/response.py +++ b/pynetbox/core/response.py @@ -56,14 +56,14 @@ def get_return(lookup, return_fields=None): def flatten_custom(custom_dict): return { - k: v if not isinstance(v, dict) else v["value"] - for k, v in custom_dict.items() + k: v if not isinstance(v, dict) else v["value"] for k, v in custom_dict.items() } class JsonField(object): """Explicit field type for values that are not to be converted to a Record object""" + _json_field = True @@ -167,8 +167,8 @@ def __init__(self, values, api, endpoint): self.api = api self.default_ret = Record self.endpoint = ( - self._endpoint_from_url(values['url']) - if values and 'url' in values + self._endpoint_from_url(values["url"]) + if values and "url" in values else endpoint ) if values: @@ -208,9 +208,7 @@ def __getitem__(self, item): return item def __str__(self): - return ( - getattr(self, "name", None) or getattr(self, "label", None) or "" - ) + return getattr(self, "name", None) or getattr(self, "label", None) or "" def __repr__(self): return str(self) @@ -225,7 +223,7 @@ def __key__(self): if hasattr(self, "id"): return (self.endpoint.name, self.id) else: - return (self.endpoint.name) + return self.endpoint.name def __hash__(self): return hash(self.__key__()) @@ -343,14 +341,11 @@ def serialize(self, nested=False, init=False): ret[i] = flatten_custom(current_val) else: if isinstance(current_val, Record): - current_val = getattr(current_val, "serialize")( - nested=True - ) + current_val = getattr(current_val, "serialize")(nested=True) if isinstance(current_val, list): current_val = [ - v.id if isinstance(v, Record) else v - for v in current_val + v.id if isinstance(v, Record) else v for v in current_val ] if i in LIST_AS_SET: current_val = list(set(current_val)) @@ -365,9 +360,7 @@ def fmt_dict(k, v): return k, ",".join(map(str, v)) return k, v - current = Hashabledict( - {fmt_dict(k, v) for k, v in self.serialize().items()} - ) + current = Hashabledict({fmt_dict(k, v) for k, v in self.serialize().items()}) init = Hashabledict( {fmt_dict(k, v) for k, v in self.serialize(init=True).items()} ) diff --git a/pynetbox/models/ipam.py b/pynetbox/models/ipam.py index 6fb1b385..d2511aba 100644 --- a/pynetbox/models/ipam.py +++ b/pynetbox/models/ipam.py @@ -86,9 +86,7 @@ def available_prefixes(self): u'10.1.1.56/29' """ - return DetailEndpoint( - self, "available-prefixes", custom_return=Prefixes - ) + return DetailEndpoint(self, "available-prefixes", custom_return=Prefixes) class Aggregates(Record): diff --git a/setup.py b/setup.py index f01b5456..92daf485 100644 --- a/setup.py +++ b/setup.py @@ -1,29 +1,25 @@ from setuptools import setup, find_packages setup( - name='pynetbox', - description='NetBox API client library', - url='https://github.com/digitalocean/pynetbox', - author='Zach Moody', - author_email='zmoody@do.co', - license='Apache2', + name="pynetbox", + description="NetBox API client library", + url="https://github.com/digitalocean/pynetbox", + author="Zach Moody", + author_email="zmoody@do.co", + license="Apache2", include_package_data=True, use_scm_version=True, - setup_requires=['setuptools_scm'], + setup_requires=["setuptools_scm"], packages=find_packages(), - install_requires=[ - 'requests>=2.20.0,<3.0', - 'six==1.*', - ], + install_requires=["requests>=2.20.0,<3.0", "six==1.*",], zip_safe=False, - keywords=['netbox'], + keywords=["netbox"], classifiers=[ - 'Intended Audience :: Developers', - 'Development Status :: 5 - Production/Stable', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', + "Intended Audience :: Developers", + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", ], - ) diff --git a/tests/test_api.py b/tests/test_api.py index 5554c072..59d6a65f 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -12,8 +12,8 @@ host = "http://localhost:8000" def_kwargs = { - 'token': 'abc123', - 'private_key_file': 'tests/fixtures/api/get_session_key.json', + "token": "abc123", + "private_key_file": "tests/fixtures/api/get_session_key.json", } # Keys are app names, values are arbitrarily selected endpoints @@ -21,64 +21,46 @@ # and circuits because it does not. We don't add other apps/endpoints # beyond 'circuits' as they all use the same code as each other endpoints = { - 'dcim': 'devices', - 'ipam': 'prefixes', - 'circuits': 'circuits', + "dcim": "devices", + "ipam": "prefixes", + "circuits": "circuits", } class ApiTestCase(unittest.TestCase): - @patch( - 'pynetbox.core.query.requests.sessions.Session.post', - return_value=Response(fixture='api/get_session_key.json') + "pynetbox.core.query.requests.sessions.Session.post", + return_value=Response(fixture="api/get_session_key.json"), ) def test_get(self, *_): - api = pynetbox.api( - host, - **def_kwargs - ) + api = pynetbox.api(host, **def_kwargs) self.assertTrue(api) @patch( - 'pynetbox.core.query.requests.sessions.Session.post', - return_value=Response(fixture='api/get_session_key.json') + "pynetbox.core.query.requests.sessions.Session.post", + return_value=Response(fixture="api/get_session_key.json"), ) def test_sanitize_url(self, *_): - api = pynetbox.api( - 'http://localhost:8000/', - **def_kwargs - ) + api = pynetbox.api("http://localhost:8000/", **def_kwargs) self.assertTrue(api) - self.assertEqual(api.base_url, 'http://localhost:8000/api') + self.assertEqual(api.base_url, "http://localhost:8000/api") class ApiVersionTestCase(unittest.TestCase): - class ResponseHeadersWithVersion: headers = {"API-Version": "1.999"} ok = True - @patch( - 'requests.get', - return_value=ResponseHeadersWithVersion() - ) + @patch("requests.get", return_value=ResponseHeadersWithVersion()) def test_api_version(self, *_): - api = pynetbox.api( - host, - ) + api = pynetbox.api(host,) self.assertEqual(api.version, "1.999") class ResponseHeadersWithoutVersion: headers = {} ok = True - @patch( - 'requests.get', - return_value=ResponseHeadersWithoutVersion() - ) + @patch("requests.get", return_value=ResponseHeadersWithoutVersion()) def test_api_version_not_found(self, *_): - api = pynetbox.api( - host, - ) + api = pynetbox.api(host,) self.assertEqual(api.version, "") diff --git a/tests/test_app.py b/tests/test_app.py index 237ad38a..632ee82f 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -12,24 +12,20 @@ host = "http://localhost:8000" def_kwargs = { - 'token': 'abc123', + "token": "abc123", } class AppCustomChoicesTestCase(unittest.TestCase): - @patch( - 'pynetbox.core.query.Request.get', + "pynetbox.core.query.Request.get", return_value={ "Testfield1": {"TF1_1": 1, "TF1_2": 2}, "Testfield2": {"TF2_1": 3, "TF2_2": 4}, - } + }, ) def test_custom_choices(self, *_): - api = pynetbox.api( - host, - **def_kwargs - ) + api = pynetbox.api(host, **def_kwargs) choices = api.extras.custom_choices() self.assertEqual(len(choices), 2) self.assertEqual(sorted(choices.keys()), ["Testfield1", "Testfield2"]) diff --git a/tests/test_circuits.py b/tests/test_circuits.py index abc63ce3..e0ceb924 100644 --- a/tests/test_circuits.py +++ b/tests/test_circuits.py @@ -9,39 +9,31 @@ else: from mock import patch -api = pynetbox.api( - "http://localhost:8000", -) +api = pynetbox.api("http://localhost:8000",) nb = api.circuits -HEADERS = { - 'accept': 'application/json;' -} +HEADERS = {"accept": "application/json;"} class Generic(object): class Tests(unittest.TestCase): - name = '' + name = "" ret = pynetbox.core.response.Record - app = 'circuits' + app = "circuits" def test_get_all(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: ret = getattr(nb, self.name).all() self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -50,20 +42,16 @@ def test_get_all(self): def test_filter(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: - ret = getattr(nb, self.name).filter(name='test') + ret = getattr(nb, self.name).filter(name="test") self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={"name": "test"}, json=None, @@ -72,19 +60,17 @@ def test_filter(self): def test_get(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name[:-1] - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format(self.app, self.name[:-1]) + ), ) as mock: ret = getattr(nb, self.name).get(1) self.assertTrue(ret) self.assertTrue(isinstance(ret, self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -93,32 +79,32 @@ def test_get(self): class CircuitsTestCase(Generic.Tests): - name = 'circuits' + name = "circuits" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='circuits/circuit.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="circuits/circuit.json"), ) def test_repr(self, _): test = nb.circuits.get(1) - self.assertEqual(str(test), '123456') + self.assertEqual(str(test), "123456") class ProviderTestCase(Generic.Tests): - name = 'providers' + name = "providers" class CircuitTypeTestCase(Generic.Tests): - name = 'circuit_types' + name = "circuit_types" class CircuitTerminationsTestCase(Generic.Tests): - name = 'circuit_terminations' + name = "circuit_terminations" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='circuits/circuit_termination.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="circuits/circuit_termination.json"), ) def test_repr(self, _): test = nb.circuit_terminations.get(1) - self.assertEqual(str(test), '123456') + self.assertEqual(str(test), "123456") diff --git a/tests/test_dcim.py b/tests/test_dcim.py index 34c5327b..47119ea5 100644 --- a/tests/test_dcim.py +++ b/tests/test_dcim.py @@ -10,41 +10,34 @@ from mock import patch -api = pynetbox.api( - "http://localhost:8000", - token="abc123", -) +api = pynetbox.api("http://localhost:8000", token="abc123",) nb = api.dcim HEADERS = { - 'accept': 'application/json;', - 'authorization': 'Token abc123', + "accept": "application/json;", + "authorization": "Token abc123", } class Generic(object): class Tests(unittest.TestCase): - name = '' + name = "" ret = pynetbox.core.response.Record - app = 'dcim' + app = "dcim" def test_get_all(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: ret = getattr(nb, self.name).all() self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -53,20 +46,16 @@ def test_get_all(self): def test_filter(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: - ret = getattr(nb, self.name).filter(name='test') + ret = getattr(nb, self.name).filter(name="test") self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={"name": "test"}, json=None, @@ -75,11 +64,10 @@ def test_filter(self): def test_get(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name[:-1] - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format(self.app, self.name[:-1]) + ), ) as mock: ret = getattr(nb, self.name).get(1) self.assertTrue(ret) @@ -87,9 +75,8 @@ def test_get(self): self.assertTrue(isinstance(str(ret), str)) self.assertTrue(isinstance(dict(ret), dict)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -98,27 +85,26 @@ def test_get(self): def test_delete(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name[:-1] - )) - ) as mock, patch('pynetbox.core.query.requests.sessions.Session.delete') as delete: + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format(self.app, self.name[:-1]) + ), + ) as mock, patch( + "pynetbox.core.query.requests.sessions.Session.delete" + ) as delete: ret = getattr(nb, self.name).get(1) self.assertTrue(ret.delete()) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, headers=HEADERS, ) delete.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -127,11 +113,10 @@ def test_delete(self): def test_compare(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name[:-1] - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format(self.app, self.name[:-1]) + ), ): ret = getattr(nb, self.name).get(1) self.assertTrue(ret) @@ -139,11 +124,10 @@ def test_compare(self): def test_serialize(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name[:-1] - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format(self.app, self.name[:-1]) + ), ): ret = getattr(nb, self.name).get(1) self.assertTrue(ret) @@ -151,11 +135,11 @@ def test_serialize(self): class DeviceTestCase(Generic.Tests): - name = 'devices' + name = "devices" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='dcim/device.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="dcim/device.json"), ) def test_get(self, mock): ret = getattr(nb, self.name).get(1) @@ -167,9 +151,8 @@ def test_get(self, mock): self.assertTrue(isinstance(ret.custom_fields, dict)) self.assertTrue(isinstance(ret.local_context_data, dict)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -177,181 +160,157 @@ def test_get(self, mock): ) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='dcim/devices.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="dcim/devices.json"), ) def test_multi_filter(self, mock): - ret = getattr(nb, self.name).filter(role=['test', 'test1'], site='TEST#1') + ret = getattr(nb, self.name).filter(role=["test", "test1"], site="TEST#1") self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), - params={'role': ['test', 'test1'], 'site': 'TEST#1'}, + params={"role": ["test", "test1"], "site": "TEST#1"}, json=None, headers=HEADERS, ) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='dcim/device.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="dcim/device.json"), ) def test_modify(self, *_): ret = nb.devices.get(1) - ret.serial = '123123123123' + ret.serial = "123123123123" ret_serialized = ret.serialize() self.assertTrue(ret_serialized) self.assertFalse(ret._compare()) - self.assertEqual(ret_serialized['serial'], '123123123123') + self.assertEqual(ret_serialized["serial"], "123123123123") @patch( - 'pynetbox.core.query.requests.sessions.Session.post', - return_value=Response(fixture='dcim/device.json') + "pynetbox.core.query.requests.sessions.Session.post", + return_value=Response(fixture="dcim/device.json"), ) def test_create(self, *_): data = { - 'name': 'test-device', - 'site': 1, - 'device_type': 1, - 'device_role': 1, + "name": "test-device", + "site": 1, + "device_type": 1, + "device_role": 1, } ret = nb.devices.create(**data) self.assertTrue(ret) @patch( - 'pynetbox.core.query.requests.sessions.Session.post', - return_value=Response(fixture='dcim/device_bulk_create.json') + "pynetbox.core.query.requests.sessions.Session.post", + return_value=Response(fixture="dcim/device_bulk_create.json"), ) def test_create_device_bulk(self, *_): data = [ - { - 'name': 'test-device', - 'site': 1, - 'device_type': 1, - 'device_role': 1, - }, - { - 'name': 'test-device1', - 'site': 1, - 'device_type': 1, - 'device_role': 1, - }, + {"name": "test-device", "site": 1, "device_type": 1, "device_role": 1,}, + {"name": "test-device1", "site": 1, "device_type": 1, "device_role": 1,}, ] ret = nb.devices.create(data) self.assertTrue(ret) self.assertTrue(len(ret), 2) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='dcim/device.json'), - Response(fixture='dcim/rack.json'), - ] + Response(fixture="dcim/device.json"), + Response(fixture="dcim/rack.json"), + ], ) def test_get_recurse(self, *_): - '''Test that automatic recursion works, and that nested items + """Test that automatic recursion works, and that nested items are converted to Response() objects. - ''' + """ ret = getattr(nb, self.name).get(1) self.assertTrue(ret) self.assertTrue(isinstance(ret, self.ret)) - self.assertTrue(isinstance( - ret.rack.role, - self.ret - )) + self.assertTrue(isinstance(ret.rack.role, self.ret)) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='dcim/device.json'), - Response(fixture='dcim/napalm.json'), - ] + Response(fixture="dcim/device.json"), + Response(fixture="dcim/napalm.json"), + ], ) def test_get_napalm(self, mock): test = nb.devices.get(1) - ret = test.napalm.list(method='get_facts') + ret = test.napalm.list(method="get_facts") mock.assert_called_with( - 'http://localhost:8000/api/dcim/devices/1/napalm/', + "http://localhost:8000/api/dcim/devices/1/napalm/", params={"method": "get_facts"}, json=None, headers=HEADERS, ) self.assertTrue(ret) - self.assertTrue(ret['get_facts']) + self.assertTrue(ret["get_facts"]) class SiteTestCase(Generic.Tests): - name = 'sites' + name = "sites" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='dcim/site.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="dcim/site.json"), ) def test_modify_custom(self, *_): - '''Test modifying a custom field. - ''' + """Test modifying a custom field. + """ ret = getattr(nb, self.name).get(1) - ret.custom_fields['test_custom'] = "Testing" + ret.custom_fields["test_custom"] = "Testing" self.assertFalse(ret._compare()) self.assertTrue(ret.serialize()) - self.assertEqual( - ret.custom_fields['test_custom'], 'Testing' - ) + self.assertEqual(ret.custom_fields["test_custom"], "Testing") @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='dcim/site.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="dcim/site.json"), ) def test_custom_selection_serializer(self, _): - '''Tests serializer with custom selection fields. - ''' + """Tests serializer with custom selection fields. + """ ret = getattr(nb, self.name).get(1) - ret.custom_fields['test_custom'] = "Testing" + ret.custom_fields["test_custom"] = "Testing" test = ret.serialize() - self.assertEqual( - test['custom_fields']['test_selection'], - 2 - ) + self.assertEqual(test["custom_fields"]["test_selection"], 2) @patch( - 'pynetbox.core.query.requests.sessions.Session.post', - return_value=Response(fixture='dcim/site.json') + "pynetbox.core.query.requests.sessions.Session.post", + return_value=Response(fixture="dcim/site.json"), ) def test_create(self, *_): - data = { - 'name': 'TEST1', - 'custom_fields': { - 'test_custom': 'Testing' - } - } + data = {"name": "TEST1", "custom_fields": {"test_custom": "Testing"}} ret = nb.sites.create(**data) self.assertTrue(ret) class InterfaceTestCase(Generic.Tests): - name = 'interfaces' + name = "interfaces" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='dcim/interface.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="dcim/interface.json"), ) def test_modify(self, *_): ret = nb.interfaces.get(1) - ret.description = 'Testing' + ret.description = "Testing" ret_serialized = ret.serialize() self.assertTrue(ret) - self.assertEqual(ret_serialized['description'], 'Testing') - self.assertEqual(ret_serialized['form_factor'], 1400) + self.assertEqual(ret_serialized["description"], "Testing") + self.assertEqual(ret_serialized["form_factor"], 1400) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='dcim/{}.json'.format(name + '_1')), - Response(fixture='dcim/{}.json'.format(name + '_2')), - ] + Response(fixture="dcim/{}.json".format(name + "_1")), + Response(fixture="dcim/{}.json".format(name + "_2")), + ], ) def test_get_all(self, mock): ret = getattr(nb, self.name).all() @@ -360,7 +319,7 @@ def test_get_all(self, mock): self.assertTrue(isinstance(ret[0], self.ret)) self.assertEqual(len(ret), 71) mock.assert_called_with( - 'http://localhost:8000/api/dcim/interfaces/', + "http://localhost:8000/api/dcim/interfaces/", params={"limit": 221, "offset": 50}, json=None, headers=HEADERS, @@ -368,125 +327,121 @@ def test_get_all(self, mock): class RackTestCase(Generic.Tests): - name = 'racks' + name = "racks" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='dcim/rack.json'), - Response(fixture='dcim/rack_u.json'), - ] + Response(fixture="dcim/rack.json"), + Response(fixture="dcim/rack_u.json"), + ], ) def test_get_units(self, mock): test = nb.racks.get(1) ret = test.units.list() mock.assert_called_with( - 'http://localhost:8000/api/dcim/racks/1/units/', + "http://localhost:8000/api/dcim/racks/1/units/", params={}, json=None, headers=HEADERS, ) self.assertTrue(ret) - self.assertTrue( - isinstance(ret[0].device, pynetbox.models.dcim.Devices) - ) + self.assertTrue(isinstance(ret[0].device, pynetbox.models.dcim.Devices)) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='dcim/rack.json'), - Response(fixture='dcim/rack_u.json'), - ] + Response(fixture="dcim/rack.json"), + Response(fixture="dcim/rack_u.json"), + ], ) def test_get_elevation(self, mock): test = nb.racks.get(1) ret = test.elevation.list() mock.assert_called_with( - 'http://localhost:8000/api/dcim/racks/1/elevation/', + "http://localhost:8000/api/dcim/racks/1/elevation/", params={}, json=None, headers=HEADERS, ) self.assertTrue(ret) - self.assertTrue( - isinstance(ret[0].device, pynetbox.models.dcim.Devices) - ) + self.assertTrue(isinstance(ret[0].device, pynetbox.models.dcim.Devices)) class RackRoleTestCase(Generic.Tests): - name = 'rack_roles' + name = "rack_roles" class RegionTestCase(Generic.Tests): - name = 'regions' + name = "regions" class RackGroupsTestCase(Generic.Tests): - name = 'rack_groups' + name = "rack_groups" class RackReservationsTestCase(Generic.Tests): - name = 'rack_reservations' + name = "rack_reservations" class ManufacturersTestCase(Generic.Tests): - name = 'manufacturers' + name = "manufacturers" class DeviceTypeTestCase(Generic.Tests): - name = 'device_types' + name = "device_types" class ConsolePortTemplateTestCase(Generic.Tests): - name = 'console_port_templates' + name = "console_port_templates" class ConsoleServerPortTemplateTestCase(Generic.Tests): - name = 'console_server_port_templates' + name = "console_server_port_templates" class PowerPortTemplateTestCase(Generic.Tests): - name = 'power_port_templates' + name = "power_port_templates" class PowerOutletTemplateTestCase(Generic.Tests): - name = 'power_outlet_templates' + name = "power_outlet_templates" class InterfaceTemplateTestCase(Generic.Tests): - name = 'interface_templates' + name = "interface_templates" class DeviceBayTemplateTestCase(Generic.Tests): - name = 'device_bay_templates' + name = "device_bay_templates" class DeviceRolesTestCase(Generic.Tests): - name = 'device_roles' + name = "device_roles" class PlatformsTestCase(Generic.Tests): - name = 'platforms' + name = "platforms" class ConsolePortsTestCase(Generic.Tests): - name = 'console_ports' + name = "console_ports" class ConsoleServerPortsTestCase(Generic.Tests): - name = 'console_server_ports' + name = "console_server_ports" class PowerPortsTestCase(Generic.Tests): - name = 'power_ports' + name = "power_ports" class PowerOutletsTestCase(Generic.Tests): - name = 'power_outlets' + name = "power_outlets" class DeviceBaysTestCase(Generic.Tests): - name = 'device_bays' + name = "device_bays" # class InventoryItemsTestCase(Generic.Tests): @@ -494,7 +449,7 @@ class DeviceBaysTestCase(Generic.Tests): class InterfaceConnectionsTestCase(Generic.Tests): - name = 'interface_connections' + name = "interface_connections" # class ConnectedDevicesTestCase(Generic.Tests): @@ -502,23 +457,19 @@ class InterfaceConnectionsTestCase(Generic.Tests): class VirtualChassisTestCase(Generic.Tests): - name = 'virtual_chassis_devices' + name = "virtual_chassis_devices" class Choices(unittest.TestCase): - def test_get(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - 'dcim', - 'choices' - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format("dcim", "choices")), ) as mock: ret = nb.choices() self.assertTrue(ret) mock.assert_called_with( - 'http://localhost:8000/api/dcim/_choices/', + "http://localhost:8000/api/dcim/_choices/", params={}, json=None, headers=HEADERS, @@ -526,50 +477,49 @@ def test_get(self): class CablesTestCase(Generic.Tests): - name = 'cables' + name = "cables" def test_get_circuit(self): - response_obj = Response(content={ - "id": 1, - "termination_a_type": "circuits.circuittermination", - "termination_a_id": 1, - "termination_a": { + response_obj = Response( + content={ "id": 1, - "url": "http://localhost:8000/api/circuits/circuit-terminations/1/", - "circuit": { - "id": 346, - "url": "http://localhost:8000/api/circuits/circuits/1/", - "cid": "TEST123321" + "termination_a_type": "circuits.circuittermination", + "termination_a_id": 1, + "termination_a": { + "id": 1, + "url": "http://localhost:8000/api/circuits/circuit-terminations/1/", + "circuit": { + "id": 346, + "url": "http://localhost:8000/api/circuits/circuits/1/", + "cid": "TEST123321", + }, + "term_side": "A", }, - "term_side": "A", - }, - "termination_b_type": "dcim.interface", - "termination_b_id": 2, - "termination_b": { - "id": 2, - "url": "http://localhost:8000/api/dcim/interfaces/2/", - "device": { + "termination_b_type": "dcim.interface", + "termination_b_id": 2, + "termination_b": { "id": 2, - "url": "http://localhost:8000/api/dcim/devices/2/", - "name": "tst1-test2", - "display_name": "tst1-test2" + "url": "http://localhost:8000/api/dcim/interfaces/2/", + "device": { + "id": 2, + "url": "http://localhost:8000/api/dcim/devices/2/", + "name": "tst1-test2", + "display_name": "tst1-test2", + }, + "name": "xe-0/0/0", + "cable": 1, }, - "name": "xe-0/0/0", - "cable": 1 - }, - "type": None, - "status": { - "value": True, - "label": "Connected" - }, - "label": "", - "color": "", - "length": None, - "length_unit": None - }) + "type": None, + "status": {"value": True, "label": "Connected"}, + "label": "", + "color": "", + "length": None, + "length_unit": None, + } + ) with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=response_obj + "pynetbox.core.query.requests.sessions.Session.get", + return_value=response_obj, ) as mock: ret = getattr(nb, self.name).get(1) self.assertTrue(ret) @@ -577,9 +527,8 @@ def test_get_circuit(self): self.assertTrue(isinstance(str(ret), str)) self.assertTrue(isinstance(dict(ret), dict)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), headers=HEADERS, params={}, diff --git a/tests/test_ipam.py b/tests/test_ipam.py index e381d9fa..8cc12004 100644 --- a/tests/test_ipam.py +++ b/tests/test_ipam.py @@ -12,47 +12,40 @@ from mock import patch -api = pynetbox.api( - "http://localhost:8000", - token="abc123", -) +api = pynetbox.api("http://localhost:8000", token="abc123",) nb = api.ipam HEADERS = { - 'accept': 'application/json;', - 'authorization': 'Token abc123', + "accept": "application/json;", + "authorization": "Token abc123", } POST_HEADERS = { - 'Content-Type': 'application/json;', - 'authorization': 'Token abc123', + "Content-Type": "application/json;", + "authorization": "Token abc123", } class Generic(object): class Tests(unittest.TestCase): - name = '' + name = "" name_singular = None ret = pynetbox.core.response.Record - app = 'ipam' + app = "ipam" def test_get_all(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: ret = getattr(nb, self.name).all() self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -61,20 +54,16 @@ def test_get_all(self): def test_filter(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: - ret = getattr(nb, self.name).filter(name='test') + ret = getattr(nb, self.name).filter(name="test") self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={"name": "test"}, json=None, @@ -83,11 +72,12 @@ def test_filter(self): def test_get(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name_singular or self.name[:-1] - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format( + self.app, self.name_singular or self.name[:-1] + ) + ), ) as mock: ret = getattr(nb, self.name).get(1) self.assertTrue(ret) @@ -95,9 +85,8 @@ def test_get(self): self.assertTrue(isinstance(dict(ret), dict)) self.assertTrue(isinstance(str(ret), str)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -106,28 +95,28 @@ def test_get(self): class PrefixTestCase(Generic.Tests): - name = 'prefixes' - name_singular = 'prefix' + name = "prefixes" + name_singular = "prefix" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='ipam/prefix.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="ipam/prefix.json"), ) def test_modify(self, *_): ret = nb.prefixes.get(1) - ret.prefix = '10.1.2.0/24' + ret.prefix = "10.1.2.0/24" ret_serialized = ret.serialize() self.assertTrue(ret_serialized) self.assertFalse(ret._compare()) - self.assertEqual(ret_serialized['prefix'], '10.1.2.0/24') + self.assertEqual(ret_serialized["prefix"], "10.1.2.0/24") @patch( - 'pynetbox.core.query.requests.sessions.Session.put', - return_value=Response(fixture='ipam/prefix.json') + "pynetbox.core.query.requests.sessions.Session.put", + return_value=Response(fixture="ipam/prefix.json"), ) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='ipam/prefix.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="ipam/prefix.json"), ) def test_idempotence(self, *_): ret = nb.prefixes.get(1) @@ -135,17 +124,17 @@ def test_idempotence(self, *_): self.assertFalse(test) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='ipam/prefix.json'), - Response(fixture='ipam/available-ips.json'), - ] + Response(fixture="ipam/prefix.json"), + Response(fixture="ipam/available-ips.json"), + ], ) def test_get_available_ips(self, mock): pfx = nb.prefixes.get(1) ret = pfx.available_ips.list() mock.assert_called_with( - 'http://localhost:8000/api/ipam/prefixes/1/available-ips/', + "http://localhost:8000/api/ipam/prefixes/1/available-ips/", params={}, json=None, headers=HEADERS, @@ -154,21 +143,19 @@ def test_get_available_ips(self, mock): self.assertEqual(len(ret), 3) @patch( - 'pynetbox.core.query.requests.sessions.Session.post', - return_value=Response(fixture='ipam/available-ips-post.json') + "pynetbox.core.query.requests.sessions.Session.post", + return_value=Response(fixture="ipam/available-ips-post.json"), ) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='ipam/prefix.json'), + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="ipam/prefix.json"), ) def test_create_available_ips(self, _, post): - create_parms = dict( - status=2, - ) + create_parms = dict(status=2,) pfx = nb.prefixes.get(1) ret = pfx.available_ips.create(create_parms) post.assert_called_with( - 'http://localhost:8000/api/ipam/prefixes/1/available-ips/', + "http://localhost:8000/api/ipam/prefixes/1/available-ips/", params={}, headers=POST_HEADERS, json=create_parms, @@ -177,17 +164,17 @@ def test_create_available_ips(self, _, post): self.assertTrue(isinstance(ret, pynetbox.models.ipam.IpAddresses)) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='ipam/prefix.json'), - Response(fixture='ipam/available-prefixes.json'), - ] + Response(fixture="ipam/prefix.json"), + Response(fixture="ipam/available-prefixes.json"), + ], ) def test_get_available_prefixes(self, mock): pfx = nb.prefixes.get(1) ret = pfx.available_prefixes.list() mock.assert_called_with( - 'http://localhost:8000/api/ipam/prefixes/1/available-prefixes/', + "http://localhost:8000/api/ipam/prefixes/1/available-prefixes/", params={}, json=None, headers=HEADERS, @@ -195,21 +182,19 @@ def test_get_available_prefixes(self, mock): self.assertTrue(ret) @patch( - 'pynetbox.core.query.requests.sessions.Session.post', - return_value=Response(fixture='ipam/available-prefixes-post.json') + "pynetbox.core.query.requests.sessions.Session.post", + return_value=Response(fixture="ipam/available-prefixes-post.json"), ) @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='ipam/prefix.json'), + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="ipam/prefix.json"), ) def test_create_available_prefixes(self, _, post): - create_parms = dict( - prefix_length=30, - ) + create_parms = dict(prefix_length=30,) pfx = nb.prefixes.get(1) ret = pfx.available_prefixes.create(create_parms) post.assert_called_with( - 'http://localhost:8000/api/ipam/prefixes/1/available-prefixes/', + "http://localhost:8000/api/ipam/prefixes/1/available-prefixes/", params={}, headers=POST_HEADERS, json=create_parms, @@ -219,50 +204,50 @@ def test_create_available_prefixes(self, _, post): class IPAddressTestCase(Generic.Tests): - name = 'ip_addresses' - name_singular = 'ip_address' + name = "ip_addresses" + name_singular = "ip_address" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='ipam/ip_address.json') + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="ipam/ip_address.json"), ) def test_modify(self, *_): ret = nb.prefixes.get(1) - ret.description = 'testing' + ret.description = "testing" ret_serialized = ret.serialize() self.assertTrue(ret_serialized) self.assertFalse(ret._compare()) - self.assertEqual(ret_serialized['address'], '10.0.255.1/32') - self.assertEqual(ret_serialized['description'], 'testing') + self.assertEqual(ret_serialized["address"], "10.0.255.1/32") + self.assertEqual(ret_serialized["description"], "testing") class RoleTestCase(Generic.Tests): - name = 'roles' + name = "roles" class RIRTestCase(Generic.Tests): - name = 'rirs' + name = "rirs" class AggregatesTestCase(Generic.Tests): - name = 'aggregates' + name = "aggregates" class VlanTestCase(Generic.Tests): - name = 'vlans' + name = "vlans" @patch( - 'pynetbox.core.query.requests.sessions.Session.get', + "pynetbox.core.query.requests.sessions.Session.get", side_effect=[ - Response(fixture='ipam/vlan.json'), - Response(fixture='dcim/interface.json'), - ] + Response(fixture="ipam/vlan.json"), + Response(fixture="dcim/interface.json"), + ], ) def test_vlan_in_interface(self, mock): vlan = nb.vlans.get(3) interface = api.dcim.interfaces.get(1) mock.assert_called_with( - 'http://localhost:8000/api/dcim/interfaces/1/', + "http://localhost:8000/api/dcim/interfaces/1/", params={}, json=None, headers=HEADERS, @@ -273,11 +258,11 @@ def test_vlan_in_interface(self, mock): class VlanGroupsTestCase(Generic.Tests): - name = 'vlan_groups' + name = "vlan_groups" class VRFTestCase(Generic.Tests): - name = 'vrfs' + name = "vrfs" # class ServicesTestCase(Generic.Tests): diff --git a/tests/test_query.py b/tests/test_query.py index 6d30388a..60165180 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -5,11 +5,6 @@ class TestQuery(unittest.TestCase): - def test_url_param_builder(self): - test_params = OrderedDict([ - ('abc', '123'), - ('xyz', '321'), - ('enc', '#12'), - ]) - self.assertEqual(url_param_builder(test_params), '?abc=123&xyz=321&enc=%2312') + test_params = OrderedDict([("abc", "123"), ("xyz", "321"), ("enc", "#12"),]) + self.assertEqual(url_param_builder(test_params), "?abc=123&xyz=321&enc=%2312") diff --git a/tests/test_tenancy.py b/tests/test_tenancy.py index 94401d78..7a006894 100644 --- a/tests/test_tenancy.py +++ b/tests/test_tenancy.py @@ -10,39 +10,31 @@ from mock import patch -api = pynetbox.api( - "http://localhost:8000", -) +api = pynetbox.api("http://localhost:8000",) nb = api.tenancy -HEADERS = { - 'accept': 'application/json;' -} +HEADERS = {"accept": "application/json;"} class Generic(object): class Tests(unittest.TestCase): - name = '' + name = "" ret = pynetbox.core.response.Record - app = 'tenancy' + app = "tenancy" def test_get_all(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: ret = getattr(nb, self.name).all() self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -51,20 +43,16 @@ def test_get_all(self): def test_filter(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: - ret = getattr(nb, self.name).filter(name='test') + ret = getattr(nb, self.name).filter(name="test") self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={"name": "test"}, json=None, @@ -73,19 +61,17 @@ def test_filter(self): def test_get(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name[:-1] - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format(self.app, self.name[:-1]) + ), ) as mock: ret = getattr(nb, self.name).get(1) self.assertTrue(ret) self.assertTrue(isinstance(ret, self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -94,8 +80,8 @@ def test_get(self): class TenantsTestCase(Generic.Tests): - name = 'tenants' + name = "tenants" class TenantGroupsTestCase(Generic.Tests): - name = 'tenant_groups' + name = "tenant_groups" diff --git a/tests/test_virtualization.py b/tests/test_virtualization.py index c61dbf35..8749b9ec 100644 --- a/tests/test_virtualization.py +++ b/tests/test_virtualization.py @@ -10,39 +10,31 @@ from mock import patch -api = pynetbox.api( - "http://localhost:8000", -) +api = pynetbox.api("http://localhost:8000",) nb = api.virtualization -HEADERS = { - 'accept': 'application/json;' -} +HEADERS = {"accept": "application/json;"} class Generic(object): class Tests(unittest.TestCase): - name = '' + name = "" ret = pynetbox.core.response.Record - app = 'virtualization' + app = "virtualization" def test_get_all(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: ret = getattr(nb, self.name).all() self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -51,20 +43,16 @@ def test_get_all(self): def test_filter(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response(fixture="{}/{}.json".format(self.app, self.name)), ) as mock: - ret = getattr(nb, self.name).filter(name='test') + ret = getattr(nb, self.name).filter(name="test") self.assertTrue(ret) self.assertTrue(isinstance(ret, list)) self.assertTrue(isinstance(ret[0], self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/".format( + self.app, self.name.replace("_", "-") ), params={"name": "test"}, json=None, @@ -73,19 +61,17 @@ def test_filter(self): def test_get(self): with patch( - 'pynetbox.core.query.requests.sessions.Session.get', - return_value=Response(fixture='{}/{}.json'.format( - self.app, - self.name[:-1] - )) + "pynetbox.core.query.requests.sessions.Session.get", + return_value=Response( + fixture="{}/{}.json".format(self.app, self.name[:-1]) + ), ) as mock: ret = getattr(nb, self.name).get(1) self.assertTrue(ret) self.assertTrue(isinstance(ret, self.ret)) mock.assert_called_with( - 'http://localhost:8000/api/{}/{}/1/'.format( - self.app, - self.name.replace('_', '-') + "http://localhost:8000/api/{}/{}/1/".format( + self.app, self.name.replace("_", "-") ), params={}, json=None, @@ -94,20 +80,20 @@ def test_get(self): class ClusterTypesTestCase(Generic.Tests): - name = 'cluster_types' + name = "cluster_types" class ClusterGroupsTestCase(Generic.Tests): - name = 'cluster_groups' + name = "cluster_groups" class ClustersTestCase(Generic.Tests): - name = 'clusters' + name = "clusters" class VirtualMachinesTestCase(Generic.Tests): - name = 'virtual_machines' + name = "virtual_machines" class InterfacesTestCase(Generic.Tests): - name = 'interfaces' + name = "interfaces" diff --git a/tests/unit/test_endpoint.py b/tests/unit/test_endpoint.py index 4ce10de9..abdc9605 100644 --- a/tests/unit/test_endpoint.py +++ b/tests/unit/test_endpoint.py @@ -11,14 +11,11 @@ class EndPointTestCase(unittest.TestCase): - def test_filter(self): - with patch( - "pynetbox.core.query.Request.get", return_value=Mock() - ) as mock: + with patch("pynetbox.core.query.Request.get", return_value=Mock()) as mock: api = Mock(base_url="http://localhost:8000/api") app = Mock(name="test") - mock.return_value = [{'id': 123}, {'id': 321}] + mock.return_value = [{"id": 123}, {"id": 321}] test_obj = Endpoint(api, app, "test") test = test_obj.filter(test="test") self.assertEqual(len(test), 2) @@ -40,9 +37,7 @@ def test_filter_reserved_kwargs(self): test_obj.filter(id=1) def test_choices(self): - with patch( - "pynetbox.core.query.Request.options", return_value=Mock() - ) as mock: + with patch("pynetbox.core.query.Request.options", return_value=Mock()) as mock: api = Mock(base_url="http://localhost:8000/api") app = Mock(name="test") mock.return_value = { diff --git a/tests/unit/test_query.py b/tests/unit/test_query.py index 604d93db..4f7fc173 100644 --- a/tests/unit/test_query.py +++ b/tests/unit/test_query.py @@ -40,8 +40,7 @@ def test_get_count(self): def test_get_count_no_filters(self): test_obj = Request( - http_session=Mock(), - base="http://localhost:8001/api/dcim/devices", + http_session=Mock(), base="http://localhost:8001/api/dcim/devices", ) test_obj.http_session.get.return_value.json.return_value = { "count": 42, diff --git a/tests/unit/test_request.py b/tests/unit/test_request.py index 7edbabdb..89bcabdc 100644 --- a/tests/unit/test_request.py +++ b/tests/unit/test_request.py @@ -11,11 +11,10 @@ class RequestTestCase(unittest.TestCase): - def test_get_openapi(self): test = Request("http://localhost:8080/api", Mock()) test.get_openapi() test.http_session.get.assert_called_with( "http://localhost:8080/api/docs/?format=openapi", - headers={'Content-Type': 'application/json;'}, + headers={"Content-Type": "application/json;"}, ) diff --git a/tests/unit/test_response.py b/tests/unit/test_response.py index d22ef36e..c93452c5 100644 --- a/tests/unit/test_response.py +++ b/tests/unit/test_response.py @@ -115,10 +115,7 @@ def test_dict(self): def test_choices_idempotence_prev27(self): test_values = { "id": 123, - "choices_test": { - "value": 1, - "label": "test", - }, + "choices_test": {"value": 1, "label": "test",}, } test = Record(test_values, None, None) test.choices_test = 1 @@ -127,11 +124,7 @@ def test_choices_idempotence_prev27(self): def test_choices_idempotence_v27(self): test_values = { "id": 123, - "choices_test": { - "value": "test", - "label": "test", - "id": 1, - }, + "choices_test": {"value": "test", "label": "test", "id": 1,}, } test = Record(test_values, None, None) test.choices_test = "test" @@ -140,10 +133,7 @@ def test_choices_idempotence_v27(self): def test_choices_idempotence_v28(self): test_values = { "id": 123, - "choices_test": { - "value": "test", - "label": "test", - }, + "choices_test": {"value": "test", "label": "test",}, } test = Record(test_values, None, None) test.choices_test = "test" @@ -179,28 +169,39 @@ def test_compare(self): def test_nested_write(self): app = Mock() - app.token = 'abc123' - app.base_url = 'http://localhost:8080/api' + app.token = "abc123" + app.base_url = "http://localhost:8080/api" 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/', + test = Record( + { + "id": 123, + "name": "test", + "child": { + "id": 321, + "name": "test123", + "url": "http://localhost:8080/api/test-app/test-endpoint/", + }, }, - }, app, endpoint) - test.child.name = 'test321' + app, + endpoint, + ) + test.child.name = "test321" test.child.save() - self.assertEqual(app.http_session.patch.call_args[0][0], "http://localhost:8080/api/test-app/test-endpoint/") + self.assertEqual( + app.http_session.patch.call_args[0][0], + "http://localhost:8080/api/test-app/test-endpoint/", + ) def test_endpoint_from_url(self): - test = Record({ - 'id': 123, - 'name': 'test', - 'url': 'http://localhost:8080/api/test-app/test-endpoint/1/', - }, Mock(), None) + 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") diff --git a/tests/util.py b/tests/util.py index 3e481594..6c08f576 100644 --- a/tests/util.py +++ b/tests/util.py @@ -8,7 +8,7 @@ def __init__(self, fixture=None, status_code=200, ok=True, content=None): self.ok = ok def load_fixture(self, path): - with open("tests/fixtures/{}".format(path), 'r') as f: + with open("tests/fixtures/{}".format(path), "r") as f: return f.read() def json(self):