File: conftest.py

package info (click to toggle)
python-pynetbox 7.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,296 kB
  • sloc: python: 4,343; makefile: 3
file content (560 lines) | stat: -rw-r--r-- 19,338 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import atexit
import os
import subprocess as subp
import time
from http.client import RemoteDisconnected

import pytest
import requests
import yaml

import pynetbox

DOCKER_PROJECT_PREFIX = "pytest_pynetbox"


def get_netbox_docker_version_tag(netbox_version):
    """Get the repo tag to build netbox-docker in from the requested netbox version.

    Args:
        netbox_version (version.Version): The version of netbox we want to build

    Returns:
        str: The release tag for the netbox-docker repo that should be able to build
            the requested version of netbox.

    """
    major, minor = netbox_version.major, netbox_version.minor

    if (major, minor) == (4, 2):
        tag = "3.2.1"
    elif (major, minor) == (4, 3):
        tag = "3.3.0"
    elif (major, minor) == (4, 4):
        tag = "3.4.2"
    else:
        raise NotImplementedError(
            "Version %s is not currently supported" % netbox_version
        )

    return tag


@pytest.fixture(scope="session")
def git_toplevel():
    """Get the top level of the current git repo.

    Returns:
        str: The path of the top level directory of the current git repo.

    """
    try:
        subp.check_call(["which", "git"])
    except subp.CalledProcessError:
        pytest.skip(reason="git executable was not found on the host")
    return (
        subp.check_output(["git", "rev-parse", "--show-toplevel"])
        .decode("utf-8")
        .splitlines()[0]
    )


@pytest.fixture(scope="session")
def netbox_docker_repo_dirpaths(pytestconfig, git_toplevel):
    """Get the path to the netbox-docker repos we will use.

    Returns:
        dict: A map of the repo dir paths to the versions of netbox that should be run
            from that repo as:
                {
                    <path to repo dir as str>: [
                        <netbox version>,
                        ...,
                    ]
                }
    """
    try:
        subp.check_call(["which", "docker"])
    except subp.CalledProcessError:
        pytest.skip(reason="docker executable was not found on the host")
    netbox_versions_by_repo_dirpaths = {}
    for netbox_version in pytestconfig.option.netbox_versions:
        repo_version_tag = get_netbox_docker_version_tag(netbox_version=netbox_version)
        print("top: ", git_toplevel)
        repo_fpath = os.path.join(
            git_toplevel, ".netbox-docker-%s" % str(repo_version_tag)
        )
        if os.path.isdir(repo_fpath):
            subp.check_call(
                ["git", "fetch"], cwd=repo_fpath, stdout=subp.PIPE, stderr=subp.PIPE
            )
            subp.check_call(
                ["git", "reset", "--hard"],
                cwd=repo_fpath,
                stdout=subp.PIPE,
                stderr=subp.PIPE,
            )
            subp.check_call(
                ["git", "pull", "origin", "release"],
                cwd=repo_fpath,
                stdout=subp.PIPE,
                stderr=subp.PIPE,
            )
        else:
            subp.check_call(
                [
                    "git",
                    "clone",
                    "https://github.com/netbox-community/netbox-docker",
                    repo_fpath,
                ],
                cwd=git_toplevel,
                stdout=subp.PIPE,
                stderr=subp.PIPE,
            )

        subp.check_call(
            ["git", "checkout", repo_version_tag],
            cwd=repo_fpath,
            stdout=subp.PIPE,
            stderr=subp.PIPE,
        )

        try:
            netbox_versions_by_repo_dirpaths[repo_fpath].append(netbox_version)
        except KeyError:
            netbox_versions_by_repo_dirpaths[repo_fpath] = [netbox_version]

    return netbox_versions_by_repo_dirpaths


@pytest.fixture(scope="session")
def docker_compose_project_name(pytestconfig):
    """Get the project name to use for docker containers.

    This will return a consistently generated project name so we can kill stale
    containers after the test run is finished.
    """
    return "%s_%s" % (DOCKER_PROJECT_PREFIX, int(time.time()))


def clean_netbox_docker_tmpfiles():
    """Clean up any temporary files created in the netbox-docker repo."""
    dirpath, dirnames, filenames = next(os.walk("./"))
    for filename in filenames:
        if filename.startswith("docker-compose-v"):
            os.remove(filename)


def clean_docker_objects():
    """Clean up any docker objects created via these tests."""
    # clean up any containers
    for line in subp.check_output(["docker", "ps", "-a"]).decode("utf-8").splitlines():
        words = line.split()
        if not words:
            continue

        if words[-1].startswith(DOCKER_PROJECT_PREFIX):
            subp.check_call(
                ["docker", "rm", "-f", words[0]], stdout=subp.PIPE, stderr=subp.PIPE
            )

    # clean up any volumes
    for line in (
        subp.check_output(["docker", "volume", "list"]).decode("utf-8").splitlines()
    ):
        words = line.split()
        if not words:
            continue

        if words[-1].startswith(DOCKER_PROJECT_PREFIX):
            subp.check_call(
                ["docker", "volume", "rm", "-f", words[-1]],
                stdout=subp.PIPE,
                stderr=subp.PIPE,
            )

    # clean up any networks
    for line in (
        subp.check_output(["docker", "network", "list"]).decode("utf-8").splitlines()
    ):
        words = line.split()
        if not words:
            continue

        if words[1].startswith(DOCKER_PROJECT_PREFIX):
            subp.check_call(
                ["docker", "network", "rm", words[1]],
                stdout=subp.PIPE,
                stderr=subp.PIPE,
            )


# TODO: this function could be split up
@pytest.fixture(scope="session")
def docker_compose_file(pytestconfig, netbox_docker_repo_dirpaths):
    """Return paths to the compose files needed to create test containers.

    We can create container sets for multiple versions of netbox here by returning a
    list of paths to multiple compose files.
    """
    clean_netbox_docker_tmpfiles()
    clean_docker_objects()

    compose_files = []

    for (
        netbox_docker_repo_dirpath,
        netbox_versions,
    ) in netbox_docker_repo_dirpaths.items():
        compose_source_fpath = os.path.join(
            netbox_docker_repo_dirpath, "docker-compose.yml"
        )

        for netbox_version in netbox_versions:
            # check for updates to the local netbox images
            subp.check_call(
                ["docker", "pull", "netboxcommunity/netbox:v%s" % (netbox_version)],
                stdout=subp.PIPE,
                stderr=subp.PIPE,
            )

            docker_netbox_version = str(netbox_version).replace(".", "_")
            # load the compose file yaml
            compose_data = yaml.safe_load(open(compose_source_fpath, "r").read())

            # add the custom network for this version
            docker_network_name = "%s_v%s" % (
                DOCKER_PROJECT_PREFIX,
                docker_netbox_version,
            )
            compose_data["networks"] = {docker_network_name: {}}
            # https://docs.docker.com/compose/compose-file/compose-file-v3/#network-configuration-reference
            if "version" not in compose_data or compose_data["version"] >= "3.5":
                compose_data["networks"][docker_network_name][
                    "name"
                ] = docker_network_name

            # prepend the netbox version to each of the service names and anything else
            # needed to make the continers unique to the netbox version
            new_services = {}
            for service_name in compose_data["services"].keys():
                new_service_name = "netbox_v%s_%s" % (
                    docker_netbox_version,
                    service_name,
                )
                new_services[new_service_name] = compose_data["services"][service_name]

                if service_name in ["netbox", "netbox-worker"]:
                    # set the netbox image version
                    new_services[new_service_name]["image"] = (
                        "netboxcommunity/netbox:v%s" % netbox_version
                    )

                    new_services[new_service_name]["environment"] = {
                        "SKIP_SUPERUSER": "false",
                        "SUPERUSER_API_TOKEN": "0123456789abcdef0123456789abcdef01234567",
                        "SUPERUSER_EMAIL": "admin@example.com",
                        "SUPERUSER_NAME": "admin",
                        "SUPERUSER_PASSWORD": "admin",
                    }

                if service_name == "netbox":
                    # ensure the netbox container listens on a random port
                    new_services[new_service_name]["ports"] = ["8080"]

                    # Increase health check timeouts for GitHub Actions runners
                    # which may have more resource constraints
                    new_services[new_service_name]["healthcheck"] = {
                        "test": "curl -f http://localhost:8080/login/ || exit 1",
                        "start_period": "180s",  # Increased from 90s
                        "timeout": "10s",  # Increased from 3s
                        "interval": "15s",
                        "retries": 5,
                    }

                # set the network and an alias to the proper short name of the container
                # within that network
                new_services[new_service_name]["networks"] = {
                    docker_network_name: {"aliases": [service_name]}
                }

                # fix the naming of any dependencies
                if "depends_on" in new_services[new_service_name]:
                    new_service_dependencies = []
                    for dependent_service_name in new_services[new_service_name][
                        "depends_on"
                    ]:
                        new_service_dependencies.append(
                            "netbox_v%s_%s"
                            % (
                                docker_netbox_version,
                                dependent_service_name,
                            )
                        )
                    new_services[new_service_name][
                        "depends_on"
                    ] = new_service_dependencies

                # make any internal named volumes unique to the netbox version
                if "volumes" in new_services[new_service_name]:
                    new_volumes = []
                    for volume_config in new_services[new_service_name]["volumes"]:
                        source = volume_config.split(":")[0]
                        if "/" in source:
                            if volume_config.startswith("./"):
                                # Set the full path to the volume source. Without this
                                # some of the containers would be spun up from the
                                # wrong source directories.
                                volume_source, volume_dest = volume_config.split(
                                    ":", maxsplit=1
                                )
                                volume_source = os.path.join(
                                    netbox_docker_repo_dirpath, volume_source[2::]
                                )
                                new_volumes.append(
                                    ":".join([volume_source, volume_dest])
                                )
                            else:
                                new_volumes.append(volume_config)
                        else:
                            new_volumes.append(
                                "%s_v%s_%s"
                                % (
                                    DOCKER_PROJECT_PREFIX,
                                    docker_netbox_version,
                                    volume_config,
                                )
                            )
                    new_services[new_service_name]["volumes"] = new_volumes

            # replace the services config with the renamed versions
            compose_data["services"] = new_services

            # prepend local volume names
            new_volumes = {}
            for volume_name, volume_config in compose_data["volumes"].items():
                new_volumes[
                    "%s_v%s_%s"
                    % (
                        DOCKER_PROJECT_PREFIX,
                        docker_netbox_version,
                        volume_name,
                    )
                ] = volume_config
            compose_data["volumes"] = new_volumes

            compose_output_fpath = os.path.join(
                netbox_docker_repo_dirpath,
                "docker-compose-v%s.yml" % netbox_version,
            )
            with open(compose_output_fpath, "w") as fdesc:
                fdesc.write(yaml.dump(compose_data))

            compose_files.append(compose_output_fpath)

    # set post=run cleanup hooks if requested
    if pytestconfig.option.cleanup:
        atexit.register(clean_docker_objects)
        atexit.register(clean_netbox_docker_tmpfiles)

    return compose_files


def netbox_is_responsive(url):
    """Check if the HTTP service is up and responsive."""
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return True
    except (
        ConnectionError,
        ConnectionResetError,
        requests.exceptions.ConnectionError,
        RemoteDisconnected,
    ):
        return False


def id_netbox_service(fixture_value):
    """Create and ID representation for a netbox service fixture param.

    Returns:
        str: Identifiable representation of the service, as best we can

    """
    return "netbox v%s" % fixture_value


@pytest.fixture(scope="session")
def docker_netbox_service(
    pytestconfig,
    docker_ip,
    docker_services,
    request,
):
    """Get the netbox service to test against.

    This function waits until the netbox container is fully up and running then does an
    initial data population with a few object types to be used in testing. Then the
    service is returned as a fixture to be called from tests.
    """
    netbox_integration_version = request.param

    netbox_service_name = "netbox_v%s_netbox" % str(netbox_integration_version).replace(
        ".", "_"
    )

    netbox_service_port = 8080
    try:
        # `port_for` takes a container port and returns the corresponding host port
        port = docker_services.port_for(netbox_service_name, netbox_service_port)
    except Exception as err:
        docker_ps_stdout = subp.check_output(["docker", "ps", "-a"]).decode("utf-8")
        exited_container_logs = []
        for line in docker_ps_stdout.splitlines():
            if "Exited" in line:
                container_id = line.split()[0]
                exited_container_logs.append(
                    "\nContainer %s logs:\n%s"
                    % (
                        container_id,
                        subp.check_output(["docker", "logs", container_id]).decode(
                            "utf-8"
                        ),
                    )
                )
        raise KeyError(
            "Unable to find a docker service matching the name %s on port %s. Running"
            " containers: %s. Original error: %s. Logs:\n%s"
            % (
                netbox_service_name,
                netbox_service_port,
                docker_ps_stdout,
                err,
                exited_container_logs,
            )
        )

    url = "http://{}:{}".format(docker_ip, port)
    docker_services.wait_until_responsive(
        timeout=300.0, pause=1, check=lambda: netbox_is_responsive(url)
    )

    return {
        "url": url,
        "netbox_version": netbox_integration_version,
    }


@pytest.fixture(scope="session")
def api(docker_netbox_service):
    return pynetbox.api(
        docker_netbox_service["url"], token="0123456789abcdef0123456789abcdef01234567"
    )


@pytest.fixture(scope="session")
def nb_version(docker_netbox_service):
    return docker_netbox_service["netbox_version"]


@pytest.fixture(scope="session")
def site(api):
    site = api.dcim.sites.create(name="test", slug="test")
    yield site
    site.delete()


@pytest.fixture(scope="session")
def manufacturer(api):
    manufacturer = api.dcim.manufacturers.create(
        name="test-manufacturer", slug="test-manufacturer"
    )
    yield manufacturer
    manufacturer.delete()


@pytest.fixture(scope="session")
def device_type(api, manufacturer):
    device_type = api.dcim.device_types.create(
        manufacturer=manufacturer.id,
        model="test-device-type",
        slug="test-device-type",
        height=1,
    )
    yield device_type
    device_type.delete()


@pytest.fixture(scope="session")
def role(api):
    role = api.dcim.device_roles.create(
        name="test-device-role",
        slug="test-device-role",
        color="000000",
    )
    yield role
    role.delete()


def create_device(api, site, device_type, role, name):
    """Helper function to create a device with proper version handling.

    Args:
        api: The API instance
        site: Site object
        device_type: DeviceType object
        role: DeviceRole object
        name: Device name

    Returns:
        Created device object
    """
    from packaging import version

    if version.parse(api.version) >= version.parse("3.6"):
        return api.dcim.devices.create(
            name=name,
            role=role.id,
            device_type=device_type.id,
            site=site.id,
        )
    else:
        return api.dcim.devices.create(
            name=name,
            device_role=role.id,
            device_type=device_type.id,
            site=site.id,
        )


def pytest_generate_tests(metafunc):
    """Dynamically parametrize some functions based on args from the cli parser."""
    if "docker_netbox_service" in metafunc.fixturenames:
        # parametrize the requested versions of netbox to the docker_netbox_services fixture
        # so that it will return a fixture for each of the versions requested
        # individually rather than one fixture with multiple versions within it
        metafunc.parametrize(
            "docker_netbox_service",
            metafunc.config.getoption("netbox_versions"),
            ids=id_netbox_service,
            indirect=True,
        )


@pytest.fixture(scope="session")
def docker_cleanup(pytestconfig):
    """Override the docker cleanup command for the containsers used in testing."""
    # pytest-docker does not always clean up after itself properly, and sometimes it
    # will fail during cleanup because there is still a connection to one of the
    # running containers. Here we will disable the builtin cleanup of containers via the
    # pytest-docker module and implement our own instead.
    # This is only relevant until https://github.com/avast/pytest-docker/pull/33 gets
    # resolved.

    # There is not a great way to skip the shutdown step, so in this case to skip
    # it we will just pass the "version" arg so the containers are left alone
    command_args = "version"

    return command_args