netbox-render 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Parag Mehta
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: netbox-render
3
+ Version: 0.1.3
4
+ Summary: NetBox plugin for subdivided device bay rack elevation rendering
5
+ Author-email: Parag Mehta <pmehta@pmehta.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/paragm/netbox-render
8
+ Project-URL: Changelog, https://github.com/paragm/netbox-render/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/paragm/netbox-render/issues
10
+ Classifier: Framework :: Django
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Requires-Python: >=3.12.0
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # netbox-render
21
+
22
+ A NetBox plugin that subdivides device bay rectangles in rack elevation SVGs to show per-bay labels, role colors, and clickable links to child devices.
23
+
24
+ ## What it does
25
+
26
+ NetBox's rack elevation view renders devices with device bays as a single opaque rectangle, showing only an occupancy count (e.g. "3/4"). Child devices installed in bays are invisible — you must click into the parent device and check its Device Bays tab to see what's installed.
27
+
28
+ This plugin patches the elevation renderer so that any device with device bays has its rectangle subdivided into one section per bay. Each section shows:
29
+
30
+ - A **sequential index number** (1, 2, 3, ...) based on bay name sort order
31
+ - The **child device name** installed in that bay, or **(empty)** if no device is installed
32
+ - **Role-based coloring** matching the child device's assigned role (front face only; rear face renders grey, consistent with stock NetBox behavior)
33
+ - A **clickable link** to the child device's detail page (empty bays are not clickable)
34
+
35
+ Devices without device bays are completely unaffected — their rendering is identical to stock NetBox.
36
+
37
+ ### Bay ordering caveat
38
+
39
+ Bay sections are numbered sequentially (1, 2, 3, ...) in the order the device's bays sort by name. NetBox device bays have no separate numeric position field, so this ordering reflects alphabetical/natural sort of bay names, **not** a silkscreen-printed slot number on the physical hardware. For example, if bays are named "Bay A", "Bay B", "Bay C", they will be numbered 1, 2, 3 in that order.
40
+
41
+ ## Compatibility
42
+
43
+ | NetBox Version | Plugin Version | Status |
44
+ |---------------|---------------|--------|
45
+ | 4.6.x | 0.1.0 | Tested |
46
+
47
+ The plugin declares `min_version = '4.6.0'` and `max_version = '4.6.99'` in its configuration. NetBox will refuse to load the plugin if the version falls outside this range, displaying a clear error at startup.
48
+
49
+ Additionally, the plugin verifies the internal method signature it patches (`RackElevationSVG._draw_device`) at startup. If the signature doesn't match what's expected, the plugin raises a `RuntimeError` with a descriptive message rather than silently producing incorrect renderings. This guards against internal API changes within the supported version range.
50
+
51
+ ## Installation
52
+
53
+ 1. Install the plugin into your NetBox virtual environment:
54
+
55
+ ```bash
56
+ pip install netbox-render
57
+ ```
58
+
59
+ Or for development:
60
+
61
+ ```bash
62
+ cd /path/to/netbox-render
63
+ pip install -e .
64
+ ```
65
+
66
+ 2. Add the plugin to your NetBox configuration (`configuration.py`):
67
+
68
+ ```python
69
+ PLUGINS = [
70
+ 'netbox_render',
71
+ ]
72
+ ```
73
+
74
+ 3. Restart NetBox:
75
+
76
+ ```bash
77
+ sudo systemctl restart netbox netbox-rq
78
+ ```
79
+
80
+ A restart is required for the plugin to take effect. This is standard behavior for all NetBox plugins and is not a bug.
81
+
82
+ ## Configuration
83
+
84
+ The plugin supports one configuration option, set through NetBox's standard `PLUGINS_CONFIG` in `configuration.py`:
85
+
86
+ ### `enable_images`
87
+
88
+ Controls whether device type images are rendered inside each bay section.
89
+
90
+ | Setting | Default | Behavior |
91
+ |---------|---------|----------|
92
+ | `enable_images` | `False` | Name-only text labels in each bay section |
93
+
94
+ To enable image rendering:
95
+
96
+ ```python
97
+ PLUGINS_CONFIG = {
98
+ 'netbox_render': {
99
+ 'enable_images': True,
100
+ },
101
+ }
102
+ ```
103
+
104
+ When enabled, each bay section with an installed child device will display the child device type's front or rear image (matching the elevation face being viewed), with a text label overlay for readability.
105
+
106
+ Changing this setting requires a NetBox restart to take effect.
107
+
108
+ ## Shelf device modeling guide
109
+
110
+ If you are new to representing shelf-mounted devices in NetBox, see [docs/shelf-devices-guide.md](docs/shelf-devices-guide.md) for a step-by-step walkthrough covering how to create shelf device types, child device types, and how this plugin improves their rack elevation rendering.
111
+
112
+ ## Known limitations
113
+
114
+ - **Bay ordering is name-based**: Section numbering reflects alphabetical/natural sort of bay names, not physical slot positions. There is no way to override this without adding fields to the NetBox data model, which is explicitly out of scope.
115
+ - **No images by default**: Device type images in bay sections are disabled by default and must be explicitly enabled via configuration.
116
+ - **Rear face coloring**: Bay sections on the rear face render as grey (the stock "blocked" pattern), consistent with how NetBox renders rear-facing devices. Only the front (mounted) face shows role-based colors.
117
+ - **Front/rear parity**: Both front and rear elevation views show the same subdivided bay breakdown. There is no face-specific filtering of bays.
118
+ - **No data model changes**: This plugin makes no migrations and adds no database fields. It is a rendering-only modification.
119
+ - **Monkeypatch approach**: Because NetBox provides no plugin hook for SVG elevation rendering, this plugin patches an internal method at runtime. The signature check at startup mitigates the risk of silent breakage, but NetBox version upgrades should always be tested with this plugin before deploying to production.
120
+
121
+ ## Validation checklist
122
+
123
+ After installing the plugin on a live NetBox instance, verify the following:
124
+
125
+ - [ ] **No-bay regression**: A device with no device bays renders exactly as it did before the plugin was installed. This is the most important check — compare the elevation visually with and without the plugin.
126
+ - [ ] **All-empty bays**: A device with device bays defined but no child devices installed renders subdivided sections, all showing "(empty)".
127
+ - [ ] **Partially filled bays**: A device with some bays filled and some empty renders a mix of named child devices and "(empty)" sections, in the correct relative order (by bay name sort).
128
+ - [ ] **Click navigation**: Clicking a subdivided section with a child device installed navigates to that child device's detail page.
129
+ - [ ] **Empty bay click**: Clicking an empty bay section does not navigate anywhere (no link).
130
+ - [ ] **Role colors (front)**: On the front face, each bay section with a child device is colored according to the child device's role color.
131
+ - [ ] **Grey rear face**: On the rear face, bay sections render as grey (blocked pattern), matching stock behavior for rear-facing devices.
132
+ - [ ] **Default config (no images)**: With `enable_images` at its default (`False`), bay sections show name-only text labels.
133
+ - [ ] **Image config override**: After setting `enable_images: True` in `PLUGINS_CONFIG` and restarting, bay sections display device type images alongside labels.
134
+ - [ ] **Version check**: The plugin starts cleanly on a compatible NetBox version (4.6.x). If tested against an incompatible version, it produces a clear startup error rather than loading silently.
135
+
136
+ ## License
137
+
138
+ Apache-2.0
@@ -0,0 +1,119 @@
1
+ # netbox-render
2
+
3
+ A NetBox plugin that subdivides device bay rectangles in rack elevation SVGs to show per-bay labels, role colors, and clickable links to child devices.
4
+
5
+ ## What it does
6
+
7
+ NetBox's rack elevation view renders devices with device bays as a single opaque rectangle, showing only an occupancy count (e.g. "3/4"). Child devices installed in bays are invisible — you must click into the parent device and check its Device Bays tab to see what's installed.
8
+
9
+ This plugin patches the elevation renderer so that any device with device bays has its rectangle subdivided into one section per bay. Each section shows:
10
+
11
+ - A **sequential index number** (1, 2, 3, ...) based on bay name sort order
12
+ - The **child device name** installed in that bay, or **(empty)** if no device is installed
13
+ - **Role-based coloring** matching the child device's assigned role (front face only; rear face renders grey, consistent with stock NetBox behavior)
14
+ - A **clickable link** to the child device's detail page (empty bays are not clickable)
15
+
16
+ Devices without device bays are completely unaffected — their rendering is identical to stock NetBox.
17
+
18
+ ### Bay ordering caveat
19
+
20
+ Bay sections are numbered sequentially (1, 2, 3, ...) in the order the device's bays sort by name. NetBox device bays have no separate numeric position field, so this ordering reflects alphabetical/natural sort of bay names, **not** a silkscreen-printed slot number on the physical hardware. For example, if bays are named "Bay A", "Bay B", "Bay C", they will be numbered 1, 2, 3 in that order.
21
+
22
+ ## Compatibility
23
+
24
+ | NetBox Version | Plugin Version | Status |
25
+ |---------------|---------------|--------|
26
+ | 4.6.x | 0.1.0 | Tested |
27
+
28
+ The plugin declares `min_version = '4.6.0'` and `max_version = '4.6.99'` in its configuration. NetBox will refuse to load the plugin if the version falls outside this range, displaying a clear error at startup.
29
+
30
+ Additionally, the plugin verifies the internal method signature it patches (`RackElevationSVG._draw_device`) at startup. If the signature doesn't match what's expected, the plugin raises a `RuntimeError` with a descriptive message rather than silently producing incorrect renderings. This guards against internal API changes within the supported version range.
31
+
32
+ ## Installation
33
+
34
+ 1. Install the plugin into your NetBox virtual environment:
35
+
36
+ ```bash
37
+ pip install netbox-render
38
+ ```
39
+
40
+ Or for development:
41
+
42
+ ```bash
43
+ cd /path/to/netbox-render
44
+ pip install -e .
45
+ ```
46
+
47
+ 2. Add the plugin to your NetBox configuration (`configuration.py`):
48
+
49
+ ```python
50
+ PLUGINS = [
51
+ 'netbox_render',
52
+ ]
53
+ ```
54
+
55
+ 3. Restart NetBox:
56
+
57
+ ```bash
58
+ sudo systemctl restart netbox netbox-rq
59
+ ```
60
+
61
+ A restart is required for the plugin to take effect. This is standard behavior for all NetBox plugins and is not a bug.
62
+
63
+ ## Configuration
64
+
65
+ The plugin supports one configuration option, set through NetBox's standard `PLUGINS_CONFIG` in `configuration.py`:
66
+
67
+ ### `enable_images`
68
+
69
+ Controls whether device type images are rendered inside each bay section.
70
+
71
+ | Setting | Default | Behavior |
72
+ |---------|---------|----------|
73
+ | `enable_images` | `False` | Name-only text labels in each bay section |
74
+
75
+ To enable image rendering:
76
+
77
+ ```python
78
+ PLUGINS_CONFIG = {
79
+ 'netbox_render': {
80
+ 'enable_images': True,
81
+ },
82
+ }
83
+ ```
84
+
85
+ When enabled, each bay section with an installed child device will display the child device type's front or rear image (matching the elevation face being viewed), with a text label overlay for readability.
86
+
87
+ Changing this setting requires a NetBox restart to take effect.
88
+
89
+ ## Shelf device modeling guide
90
+
91
+ If you are new to representing shelf-mounted devices in NetBox, see [docs/shelf-devices-guide.md](docs/shelf-devices-guide.md) for a step-by-step walkthrough covering how to create shelf device types, child device types, and how this plugin improves their rack elevation rendering.
92
+
93
+ ## Known limitations
94
+
95
+ - **Bay ordering is name-based**: Section numbering reflects alphabetical/natural sort of bay names, not physical slot positions. There is no way to override this without adding fields to the NetBox data model, which is explicitly out of scope.
96
+ - **No images by default**: Device type images in bay sections are disabled by default and must be explicitly enabled via configuration.
97
+ - **Rear face coloring**: Bay sections on the rear face render as grey (the stock "blocked" pattern), consistent with how NetBox renders rear-facing devices. Only the front (mounted) face shows role-based colors.
98
+ - **Front/rear parity**: Both front and rear elevation views show the same subdivided bay breakdown. There is no face-specific filtering of bays.
99
+ - **No data model changes**: This plugin makes no migrations and adds no database fields. It is a rendering-only modification.
100
+ - **Monkeypatch approach**: Because NetBox provides no plugin hook for SVG elevation rendering, this plugin patches an internal method at runtime. The signature check at startup mitigates the risk of silent breakage, but NetBox version upgrades should always be tested with this plugin before deploying to production.
101
+
102
+ ## Validation checklist
103
+
104
+ After installing the plugin on a live NetBox instance, verify the following:
105
+
106
+ - [ ] **No-bay regression**: A device with no device bays renders exactly as it did before the plugin was installed. This is the most important check — compare the elevation visually with and without the plugin.
107
+ - [ ] **All-empty bays**: A device with device bays defined but no child devices installed renders subdivided sections, all showing "(empty)".
108
+ - [ ] **Partially filled bays**: A device with some bays filled and some empty renders a mix of named child devices and "(empty)" sections, in the correct relative order (by bay name sort).
109
+ - [ ] **Click navigation**: Clicking a subdivided section with a child device installed navigates to that child device's detail page.
110
+ - [ ] **Empty bay click**: Clicking an empty bay section does not navigate anywhere (no link).
111
+ - [ ] **Role colors (front)**: On the front face, each bay section with a child device is colored according to the child device's role color.
112
+ - [ ] **Grey rear face**: On the rear face, bay sections render as grey (blocked pattern), matching stock behavior for rear-facing devices.
113
+ - [ ] **Default config (no images)**: With `enable_images` at its default (`False`), bay sections show name-only text labels.
114
+ - [ ] **Image config override**: After setting `enable_images: True` in `PLUGINS_CONFIG` and restarting, bay sections display device type images alongside labels.
115
+ - [ ] **Version check**: The plugin starts cleanly on a compatible NetBox version (4.6.x). If tested against an incompatible version, it produces a clear startup error rather than loading silently.
116
+
117
+ ## License
118
+
119
+ Apache-2.0
@@ -0,0 +1,25 @@
1
+ from netbox.plugins import PluginConfig
2
+
3
+ from .version import __version__
4
+
5
+
6
+ class NetBoxRenderConfig(PluginConfig):
7
+ name = 'netbox_render'
8
+ verbose_name = 'Device Bay Rack Elevation Rendering'
9
+ description = 'Subdivides device bay rectangles in rack elevation SVGs to show per-bay labels and links'
10
+ version = __version__
11
+ author = 'Parag Mehta'
12
+ author_email = 'pmehta@pmehta.com'
13
+ min_version = '4.6.0'
14
+ max_version = '4.6.99'
15
+ default_settings = {
16
+ 'enable_images': False,
17
+ }
18
+
19
+ def ready(self):
20
+ super().ready()
21
+ from .elevation_patch import apply_elevation_patch
22
+ apply_elevation_patch()
23
+
24
+
25
+ config = NetBoxRenderConfig
@@ -0,0 +1,148 @@
1
+ import logging
2
+
3
+ from django.conf import settings
4
+ from svgwrite.container import Hyperlink
5
+ from svgwrite.masking import ClipPath
6
+ from svgwrite.shapes import Line, Rect
7
+ from svgwrite.text import Text
8
+
9
+ from dcim.svg.racks import RackElevationSVG, get_device_description, truncate_text
10
+ from utilities.html import foreground_color
11
+
12
+ from .version_check import verify_patch_target
13
+
14
+ logger = logging.getLogger('netbox_render')
15
+
16
+ _original_draw_device = None
17
+
18
+
19
+ def _get_plugin_setting(key, default=None):
20
+ return settings.PLUGINS_CONFIG.get('netbox_render', {}).get(key, default)
21
+
22
+
23
+ def _patched_draw_device(self, device, coords, size, color=None, image=None):
24
+ try:
25
+ bay_list = list(
26
+ device.devicebays
27
+ .select_related('installed_device__role', 'installed_device__device_type')
28
+ .order_by('name')
29
+ )
30
+ except Exception as e:
31
+ logger.error("netbox_render: failed to query devicebays for %s (pk=%s): %s", device, device.pk, e)
32
+ return _original_draw_device(self, device, coords, size, color=color, image=image)
33
+
34
+ n_bays = len(bay_list)
35
+ logger.debug(
36
+ "netbox_render: device=%s pk=%s devicebays=%d coords=%s size=%s",
37
+ device, device.pk, n_bays, coords, size,
38
+ )
39
+ if n_bays == 0:
40
+ return _original_draw_device(self, device, coords, size, color=color, image=image)
41
+
42
+ enable_images = _get_plugin_setting('enable_images', False)
43
+ x, y = coords
44
+ width, total_height = size
45
+ bay_height = total_height / n_bays
46
+
47
+ for i, bay in enumerate(bay_list):
48
+ index = i + 1
49
+ child = bay.installed_device
50
+ bay_y = y + i * bay_height
51
+ bay_coords = (x, bay_y)
52
+ bay_size = (width, bay_height)
53
+
54
+ if child:
55
+ bay_color = child.role.color if color is not None else None
56
+ label = f"{index}: {child.name or str(child.device_type)}"
57
+ description = get_device_description(child)
58
+ device_url = f'{self.base_url}{child.get_absolute_url()}'
59
+ else:
60
+ bay_color = None
61
+ label = f"{index}: (empty)"
62
+ description = f"Bay {bay.name}: empty"
63
+ device_url = None
64
+
65
+ text_color = f'#{foreground_color(bay_color)}' if bay_color else '#000000'
66
+ text_coords = (
67
+ x + width / 2,
68
+ bay_y + bay_height / 2,
69
+ )
70
+
71
+ is_shaded = self.highlight_devices and (not child or child not in self.highlight_devices)
72
+ css_extra = ' shaded' if is_shaded else ''
73
+
74
+ if bay_height < 15:
75
+ display_name = str(index)
76
+ else:
77
+ display_name = truncate_text(label, width)
78
+
79
+ clip_id = f"clip-bay-{device.pk}-{i}"
80
+ clip_path = ClipPath(id=clip_id)
81
+ clip_path.add(Rect(bay_coords, bay_size))
82
+ self.drawing.defs.add(clip_path)
83
+
84
+ container = self.drawing
85
+
86
+ if device_url:
87
+ link = Hyperlink(href=device_url, target="_parent")
88
+ link.set_desc(description)
89
+ container = link
90
+
91
+ if bay_color:
92
+ container.add(Rect(bay_coords, bay_size, style=f'fill: #{bay_color}', class_=f'slot{css_extra}'))
93
+ else:
94
+ container.add(Rect(bay_coords, bay_size, class_=f'slot blocked{css_extra}'))
95
+
96
+ if i > 0:
97
+ container.add(Line(
98
+ start=(x, bay_y),
99
+ end=(x + width, bay_y),
100
+ stroke='#000000',
101
+ stroke_width=0.5,
102
+ stroke_opacity=0.3,
103
+ ))
104
+
105
+ container.add(
106
+ Text(display_name, insert=text_coords, fill=text_color,
107
+ clip_path=f"url(#{clip_id})", class_=f'label{css_extra}')
108
+ )
109
+
110
+ if enable_images and child and self.include_images:
111
+ child_image = child.device_type.front_image if color is not None else child.device_type.rear_image
112
+ if child_image:
113
+ from svgwrite.image import Image
114
+ url = f'{self.base_url}{child_image.url}' if child_image.url.startswith('/') else child_image.url
115
+ img = Image(
116
+ href=url,
117
+ insert=bay_coords,
118
+ size=bay_size,
119
+ class_=f'device-image{css_extra}',
120
+ )
121
+ img.fit(scale='slice')
122
+ container.add(img)
123
+ container.add(
124
+ Text(label, insert=text_coords, stroke='black', stroke_width='0.2em',
125
+ stroke_linejoin='round', class_=f'device-image-label{css_extra}')
126
+ )
127
+ container.add(
128
+ Text(label, insert=text_coords, fill='white',
129
+ class_=f'device-image-label{css_extra}')
130
+ )
131
+
132
+ if device_url:
133
+ self.drawing.add(link)
134
+ # empty bays with no link are already added directly to self.drawing via container
135
+
136
+
137
+ def apply_elevation_patch():
138
+ global _original_draw_device
139
+
140
+ if _original_draw_device is not None:
141
+ return
142
+
143
+ verify_patch_target()
144
+
145
+ _original_draw_device = RackElevationSVG._draw_device
146
+ RackElevationSVG._draw_device = _patched_draw_device
147
+
148
+ logger.info("netbox_render: rack elevation patch applied successfully")
@@ -0,0 +1 @@
1
+ __version__ = "0.1.3"
@@ -0,0 +1,17 @@
1
+ import inspect
2
+
3
+
4
+ EXPECTED_PARAMS = ['self', 'device', 'coords', 'size', 'color', 'image']
5
+
6
+
7
+ def verify_patch_target():
8
+ from dcim.svg.racks import RackElevationSVG
9
+
10
+ sig = inspect.signature(RackElevationSVG._draw_device)
11
+ actual_params = list(sig.parameters.keys())
12
+ if actual_params != EXPECTED_PARAMS:
13
+ raise RuntimeError(
14
+ f"netbox_render: RackElevationSVG._draw_device signature mismatch. "
15
+ f"Expected {EXPECTED_PARAMS}, got {actual_params}. "
16
+ f"This NetBox version may be incompatible — the plugin cannot safely patch elevation rendering."
17
+ )
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: netbox-render
3
+ Version: 0.1.3
4
+ Summary: NetBox plugin for subdivided device bay rack elevation rendering
5
+ Author-email: Parag Mehta <pmehta@pmehta.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/paragm/netbox-render
8
+ Project-URL: Changelog, https://github.com/paragm/netbox-render/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/paragm/netbox-render/issues
10
+ Classifier: Framework :: Django
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Requires-Python: >=3.12.0
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # netbox-render
21
+
22
+ A NetBox plugin that subdivides device bay rectangles in rack elevation SVGs to show per-bay labels, role colors, and clickable links to child devices.
23
+
24
+ ## What it does
25
+
26
+ NetBox's rack elevation view renders devices with device bays as a single opaque rectangle, showing only an occupancy count (e.g. "3/4"). Child devices installed in bays are invisible — you must click into the parent device and check its Device Bays tab to see what's installed.
27
+
28
+ This plugin patches the elevation renderer so that any device with device bays has its rectangle subdivided into one section per bay. Each section shows:
29
+
30
+ - A **sequential index number** (1, 2, 3, ...) based on bay name sort order
31
+ - The **child device name** installed in that bay, or **(empty)** if no device is installed
32
+ - **Role-based coloring** matching the child device's assigned role (front face only; rear face renders grey, consistent with stock NetBox behavior)
33
+ - A **clickable link** to the child device's detail page (empty bays are not clickable)
34
+
35
+ Devices without device bays are completely unaffected — their rendering is identical to stock NetBox.
36
+
37
+ ### Bay ordering caveat
38
+
39
+ Bay sections are numbered sequentially (1, 2, 3, ...) in the order the device's bays sort by name. NetBox device bays have no separate numeric position field, so this ordering reflects alphabetical/natural sort of bay names, **not** a silkscreen-printed slot number on the physical hardware. For example, if bays are named "Bay A", "Bay B", "Bay C", they will be numbered 1, 2, 3 in that order.
40
+
41
+ ## Compatibility
42
+
43
+ | NetBox Version | Plugin Version | Status |
44
+ |---------------|---------------|--------|
45
+ | 4.6.x | 0.1.0 | Tested |
46
+
47
+ The plugin declares `min_version = '4.6.0'` and `max_version = '4.6.99'` in its configuration. NetBox will refuse to load the plugin if the version falls outside this range, displaying a clear error at startup.
48
+
49
+ Additionally, the plugin verifies the internal method signature it patches (`RackElevationSVG._draw_device`) at startup. If the signature doesn't match what's expected, the plugin raises a `RuntimeError` with a descriptive message rather than silently producing incorrect renderings. This guards against internal API changes within the supported version range.
50
+
51
+ ## Installation
52
+
53
+ 1. Install the plugin into your NetBox virtual environment:
54
+
55
+ ```bash
56
+ pip install netbox-render
57
+ ```
58
+
59
+ Or for development:
60
+
61
+ ```bash
62
+ cd /path/to/netbox-render
63
+ pip install -e .
64
+ ```
65
+
66
+ 2. Add the plugin to your NetBox configuration (`configuration.py`):
67
+
68
+ ```python
69
+ PLUGINS = [
70
+ 'netbox_render',
71
+ ]
72
+ ```
73
+
74
+ 3. Restart NetBox:
75
+
76
+ ```bash
77
+ sudo systemctl restart netbox netbox-rq
78
+ ```
79
+
80
+ A restart is required for the plugin to take effect. This is standard behavior for all NetBox plugins and is not a bug.
81
+
82
+ ## Configuration
83
+
84
+ The plugin supports one configuration option, set through NetBox's standard `PLUGINS_CONFIG` in `configuration.py`:
85
+
86
+ ### `enable_images`
87
+
88
+ Controls whether device type images are rendered inside each bay section.
89
+
90
+ | Setting | Default | Behavior |
91
+ |---------|---------|----------|
92
+ | `enable_images` | `False` | Name-only text labels in each bay section |
93
+
94
+ To enable image rendering:
95
+
96
+ ```python
97
+ PLUGINS_CONFIG = {
98
+ 'netbox_render': {
99
+ 'enable_images': True,
100
+ },
101
+ }
102
+ ```
103
+
104
+ When enabled, each bay section with an installed child device will display the child device type's front or rear image (matching the elevation face being viewed), with a text label overlay for readability.
105
+
106
+ Changing this setting requires a NetBox restart to take effect.
107
+
108
+ ## Shelf device modeling guide
109
+
110
+ If you are new to representing shelf-mounted devices in NetBox, see [docs/shelf-devices-guide.md](docs/shelf-devices-guide.md) for a step-by-step walkthrough covering how to create shelf device types, child device types, and how this plugin improves their rack elevation rendering.
111
+
112
+ ## Known limitations
113
+
114
+ - **Bay ordering is name-based**: Section numbering reflects alphabetical/natural sort of bay names, not physical slot positions. There is no way to override this without adding fields to the NetBox data model, which is explicitly out of scope.
115
+ - **No images by default**: Device type images in bay sections are disabled by default and must be explicitly enabled via configuration.
116
+ - **Rear face coloring**: Bay sections on the rear face render as grey (the stock "blocked" pattern), consistent with how NetBox renders rear-facing devices. Only the front (mounted) face shows role-based colors.
117
+ - **Front/rear parity**: Both front and rear elevation views show the same subdivided bay breakdown. There is no face-specific filtering of bays.
118
+ - **No data model changes**: This plugin makes no migrations and adds no database fields. It is a rendering-only modification.
119
+ - **Monkeypatch approach**: Because NetBox provides no plugin hook for SVG elevation rendering, this plugin patches an internal method at runtime. The signature check at startup mitigates the risk of silent breakage, but NetBox version upgrades should always be tested with this plugin before deploying to production.
120
+
121
+ ## Validation checklist
122
+
123
+ After installing the plugin on a live NetBox instance, verify the following:
124
+
125
+ - [ ] **No-bay regression**: A device with no device bays renders exactly as it did before the plugin was installed. This is the most important check — compare the elevation visually with and without the plugin.
126
+ - [ ] **All-empty bays**: A device with device bays defined but no child devices installed renders subdivided sections, all showing "(empty)".
127
+ - [ ] **Partially filled bays**: A device with some bays filled and some empty renders a mix of named child devices and "(empty)" sections, in the correct relative order (by bay name sort).
128
+ - [ ] **Click navigation**: Clicking a subdivided section with a child device installed navigates to that child device's detail page.
129
+ - [ ] **Empty bay click**: Clicking an empty bay section does not navigate anywhere (no link).
130
+ - [ ] **Role colors (front)**: On the front face, each bay section with a child device is colored according to the child device's role color.
131
+ - [ ] **Grey rear face**: On the rear face, bay sections render as grey (blocked pattern), matching stock behavior for rear-facing devices.
132
+ - [ ] **Default config (no images)**: With `enable_images` at its default (`False`), bay sections show name-only text labels.
133
+ - [ ] **Image config override**: After setting `enable_images: True` in `PLUGINS_CONFIG` and restarting, bay sections display device type images alongside labels.
134
+ - [ ] **Version check**: The plugin starts cleanly on a compatible NetBox version (4.6.x). If tested against an incompatible version, it produces a clear startup error rather than loading silently.
135
+
136
+ ## License
137
+
138
+ Apache-2.0
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ netbox_render/__init__.py
5
+ netbox_render/elevation_patch.py
6
+ netbox_render/version.py
7
+ netbox_render/version_check.py
8
+ netbox_render.egg-info/PKG-INFO
9
+ netbox_render.egg-info/SOURCES.txt
10
+ netbox_render.egg-info/dependency_links.txt
11
+ netbox_render.egg-info/top_level.txt
12
+ tests/test_elevation_patch.py
@@ -0,0 +1 @@
1
+ netbox_render
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "netbox-render"
7
+ dynamic = ["version"]
8
+ description = "NetBox plugin for subdivided device bay rack elevation rendering"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12.0"
11
+ license = "Apache-2.0"
12
+ authors = [
13
+ {name = "Parag Mehta", email = "pmehta@pmehta.com"},
14
+ ]
15
+ classifiers = [
16
+ "Framework :: Django",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/paragm/netbox-render"
25
+ Changelog = "https://github.com/paragm/netbox-render/blob/main/CHANGELOG.md"
26
+ Issues = "https://github.com/paragm/netbox-render/issues"
27
+
28
+ [tool.setuptools.dynamic]
29
+ version = {attr = "netbox_render.version.__version__"}
30
+
31
+ [tool.setuptools.packages.find]
32
+ include = ["netbox_render*"]
33
+ exclude = ["tests*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,319 @@
1
+ import sys
2
+ import unittest
3
+ from unittest.mock import MagicMock, patch
4
+
5
+ mock_netbox_plugins = MagicMock()
6
+ mock_plugin_config = type('PluginConfig', (), {
7
+ 'name': '', 'verbose_name': '', 'description': '', 'version': '',
8
+ 'author': '', 'author_email': '', 'min_version': None, 'max_version': None,
9
+ 'default_settings': {}, 'required_settings': [],
10
+ })
11
+ mock_netbox_plugins.PluginConfig = mock_plugin_config
12
+
13
+ sys.modules.setdefault('netbox', MagicMock())
14
+ sys.modules.setdefault('netbox.plugins', mock_netbox_plugins)
15
+ sys.modules.setdefault('netbox.config', MagicMock())
16
+ sys.modules.setdefault('dcim', MagicMock())
17
+ sys.modules.setdefault('dcim.svg', MagicMock())
18
+ sys.modules.setdefault('dcim.svg.racks', MagicMock())
19
+ sys.modules.setdefault('utilities', MagicMock())
20
+ sys.modules.setdefault('utilities.html', MagicMock())
21
+ sys.modules.setdefault('django', MagicMock())
22
+ sys.modules.setdefault('django.conf', MagicMock())
23
+ sys.modules.setdefault('svgwrite', MagicMock())
24
+ sys.modules.setdefault('svgwrite.container', MagicMock())
25
+ sys.modules.setdefault('svgwrite.masking', MagicMock())
26
+ sys.modules.setdefault('svgwrite.shapes', MagicMock())
27
+ sys.modules.setdefault('svgwrite.text', MagicMock())
28
+
29
+ from netbox_render.version_check import EXPECTED_PARAMS
30
+
31
+
32
+ class TestBaySubdivisionGeometry(unittest.TestCase):
33
+
34
+ def test_even_subdivision(self):
35
+ x, y = 50, 100
36
+ width, total_height = 200, 120
37
+ n_bays = 4
38
+ bay_height = total_height / n_bays
39
+
40
+ for i in range(n_bays):
41
+ bay_coords = (x, y + i * bay_height)
42
+ bay_size = (width, bay_height)
43
+ self.assertEqual(bay_coords[0], 50)
44
+ self.assertEqual(bay_coords[1], 100 + i * 30)
45
+ self.assertEqual(bay_size, (200, 30.0))
46
+
47
+ def test_single_bay(self):
48
+ x, y = 50, 100
49
+ width, total_height = 200, 60
50
+ bay_height = total_height / 1
51
+
52
+ bay_coords = (x, y)
53
+ bay_size = (width, bay_height)
54
+ self.assertEqual(bay_coords, (50, 100))
55
+ self.assertEqual(bay_size, (200, 60.0))
56
+
57
+ def test_odd_number_of_bays(self):
58
+ x, y = 50, 100
59
+ width, total_height = 200, 90
60
+ n_bays = 3
61
+ bay_height = total_height / n_bays
62
+
63
+ coords = [(x, y + i * bay_height) for i in range(n_bays)]
64
+ self.assertAlmostEqual(coords[0][1], 100.0)
65
+ self.assertAlmostEqual(coords[1][1], 130.0)
66
+ self.assertAlmostEqual(coords[2][1], 160.0)
67
+
68
+ def test_text_coords_centered(self):
69
+ x, y = 50, 100
70
+ width, bay_height = 200, 30
71
+ text_coords = (x + width / 2, y + bay_height / 2)
72
+ self.assertEqual(text_coords, (150.0, 115.0))
73
+
74
+
75
+ class TestBayLabeling(unittest.TestCase):
76
+
77
+ def test_label_with_child_device(self):
78
+ label = f"{1}: Server-01"
79
+ self.assertEqual(label, "1: Server-01")
80
+
81
+ def test_label_empty_bay(self):
82
+ label = f"{3}: (empty)"
83
+ self.assertEqual(label, "3: (empty)")
84
+
85
+ def test_truncated_label_for_small_bay(self):
86
+ bay_height = 10
87
+ index = 2
88
+ display = str(index) if bay_height < 15 else f"{index}: Some-Device-Name"
89
+ self.assertEqual(display, "2")
90
+
91
+ def test_full_label_for_normal_bay(self):
92
+ bay_height = 30
93
+ index = 2
94
+ display = str(index) if bay_height < 15 else f"{index}: Some-Device-Name"
95
+ self.assertEqual(display, "2: Some-Device-Name")
96
+
97
+ def test_label_uses_device_type_when_no_name(self):
98
+ index = 1
99
+ child_name = None
100
+ device_type = "PowerEdge C6420"
101
+ label = f"{index}: {child_name or device_type}"
102
+ self.assertEqual(label, "1: PowerEdge C6420")
103
+
104
+
105
+ class TestVersionCheck(unittest.TestCase):
106
+
107
+ def test_expected_params_constant(self):
108
+ self.assertEqual(
109
+ EXPECTED_PARAMS,
110
+ ['self', 'device', 'coords', 'size', 'color', 'image'],
111
+ )
112
+
113
+ def test_verify_raises_on_signature_mismatch(self):
114
+ mock_class = MagicMock()
115
+ mock_method = MagicMock()
116
+ mock_method.__name__ = '_draw_device'
117
+
118
+ import inspect
119
+ mock_params = {
120
+ 'self': inspect.Parameter('self', inspect.Parameter.POSITIONAL_OR_KEYWORD),
121
+ 'device': inspect.Parameter('device', inspect.Parameter.POSITIONAL_OR_KEYWORD),
122
+ 'coords': inspect.Parameter('coords', inspect.Parameter.POSITIONAL_OR_KEYWORD),
123
+ 'size': inspect.Parameter('size', inspect.Parameter.POSITIONAL_OR_KEYWORD),
124
+ }
125
+ wrong_sig = inspect.Signature(parameters=list(mock_params.values()))
126
+
127
+ with patch('netbox_render.version_check.inspect.signature', return_value=wrong_sig):
128
+ mock_racks = MagicMock()
129
+ mock_racks.RackElevationSVG._draw_device = mock_method
130
+ with patch.dict('sys.modules', {'dcim.svg.racks': mock_racks}):
131
+ from importlib import reload
132
+ import netbox_render.version_check as vc
133
+ reload(vc)
134
+ with self.assertRaises(RuntimeError) as ctx:
135
+ vc.verify_patch_target()
136
+ self.assertIn('signature mismatch', str(ctx.exception))
137
+
138
+
139
+ class TestShouldSubdivide(unittest.TestCase):
140
+
141
+ def test_device_without_bays_delegates(self):
142
+ """A device whose devicebays queryset returns empty should delegate to original."""
143
+ # Covered by TestPatchedDrawDevice.test_no_bays_delegates_to_original
144
+ pass
145
+
146
+ def test_device_with_all_empty_bays_subdivides(self):
147
+ """A device with bays defined but no children should still subdivide."""
148
+ # Covered by TestPatchedDrawDevice.test_empty_bays_add_elements_without_hyperlink
149
+ pass
150
+
151
+
152
+ class TestColorBehavior(unittest.TestCase):
153
+
154
+ def test_front_face_uses_child_role_color(self):
155
+ parent_color = 'aa1409'
156
+ child_role_color = '4caf50'
157
+ bay_color = child_role_color if parent_color is not None else None
158
+ self.assertEqual(bay_color, '4caf50')
159
+
160
+ def test_rear_face_passes_no_color(self):
161
+ parent_color = None
162
+ child_role_color = '4caf50'
163
+ bay_color = child_role_color if parent_color is not None else None
164
+ self.assertIsNone(bay_color)
165
+
166
+ def test_empty_bay_has_no_color(self):
167
+ child = None
168
+ bay_color = None
169
+ self.assertIsNone(bay_color)
170
+
171
+
172
+ class TestPatchedDrawDevice(unittest.TestCase):
173
+ """Integration tests that exercise the actual _patched_draw_device function."""
174
+
175
+ def setUp(self):
176
+ import netbox_render.elevation_patch as ep
177
+ self.ep = ep
178
+
179
+ self.mock_original = MagicMock()
180
+ ep._original_draw_device = self.mock_original
181
+
182
+ self.mock_drawing = MagicMock()
183
+ self.mock_defs = MagicMock()
184
+ self.mock_drawing.defs = self.mock_defs
185
+
186
+ self.svg_instance = MagicMock()
187
+ self.svg_instance.drawing = self.mock_drawing
188
+ self.svg_instance.base_url = 'http://netbox.local'
189
+ self.svg_instance.highlight_devices = []
190
+ self.svg_instance.include_images = False
191
+
192
+ def _make_device(self, bays=None):
193
+ device = MagicMock()
194
+ device.pk = 42
195
+ bay_list = bays if bays is not None else []
196
+ qs = MagicMock()
197
+ qs.select_related.return_value = qs
198
+ qs.order_by.return_value = qs
199
+ qs.__iter__ = MagicMock(return_value=iter(bay_list))
200
+ qs.__len__ = MagicMock(return_value=len(bay_list))
201
+ device.devicebays = qs
202
+ return device
203
+
204
+ def _make_bay(self, name, child_name=None, role_color='4caf50'):
205
+ bay = MagicMock()
206
+ bay.name = name
207
+ if child_name:
208
+ child = MagicMock()
209
+ child.name = child_name
210
+ child.role.color = role_color
211
+ child.get_absolute_url.return_value = f'/dcim/devices/{child_name}/'
212
+ child.device_type.front_image = None
213
+ child.device_type.rear_image = None
214
+ bay.installed_device = child
215
+ else:
216
+ bay.installed_device = None
217
+ return bay
218
+
219
+ def test_no_bays_delegates_to_original(self):
220
+ device = self._make_device()
221
+ coords = (50, 100)
222
+ size = (200, 60)
223
+
224
+ self.ep._patched_draw_device(self.svg_instance, device, coords, size, color='aa1409')
225
+
226
+ self.mock_original.assert_called_once_with(
227
+ self.svg_instance, device, coords, size, color='aa1409', image=None
228
+ )
229
+ self.mock_drawing.add.assert_not_called()
230
+
231
+ def test_subdivides_bays_with_children(self):
232
+ bays = [
233
+ self._make_bay('Bay 1', child_name='Server-01', role_color='4caf50'),
234
+ self._make_bay('Bay 2', child_name='Server-02', role_color='ff5722'),
235
+ ]
236
+ device = self._make_device(bays=bays)
237
+
238
+ with patch.object(self.ep, '_get_plugin_setting', return_value=False):
239
+ self.ep._patched_draw_device(
240
+ self.svg_instance, device, (50, 100), (200, 60), color='aa1409'
241
+ )
242
+
243
+ self.mock_original.assert_not_called()
244
+ self.assertEqual(self.mock_drawing.add.call_count, 2)
245
+ self.assertTrue(self.mock_defs.add.call_count >= 2)
246
+
247
+ def test_empty_bays_add_elements_without_hyperlink(self):
248
+ bays = [
249
+ self._make_bay('Bay 1'),
250
+ ]
251
+ device = self._make_device(bays=bays)
252
+
253
+ with patch.object(self.ep, '_get_plugin_setting', return_value=False):
254
+ self.ep._patched_draw_device(
255
+ self.svg_instance, device, (50, 100), (200, 30), color='aa1409'
256
+ )
257
+
258
+ self.mock_original.assert_not_called()
259
+ # Empty bays add Rect + Text directly to drawing (no Hyperlink wrapper)
260
+ self.assertEqual(self.mock_drawing.add.call_count, 2)
261
+
262
+ def test_mixed_bays_front_face(self):
263
+ bays = [
264
+ self._make_bay('Bay 1', child_name='Server-01', role_color='4caf50'),
265
+ self._make_bay('Bay 2'),
266
+ self._make_bay('Bay 3', child_name='Server-03', role_color='ff5722'),
267
+ ]
268
+ device = self._make_device(bays=bays)
269
+
270
+ with patch.object(self.ep, '_get_plugin_setting', return_value=False):
271
+ self.ep._patched_draw_device(
272
+ self.svg_instance, device, (50, 100), (200, 90), color='aa1409'
273
+ )
274
+
275
+ self.mock_original.assert_not_called()
276
+ # Bay 1 (filled): 1 drawing.add(link)
277
+ # Bay 2 (empty, i=1): 3 drawing.add(Rect, Line, Text)
278
+ # Bay 3 (filled): 1 drawing.add(link)
279
+ self.assertEqual(self.mock_drawing.add.call_count, 5)
280
+
281
+ def test_rear_face_no_color(self):
282
+ bays = [
283
+ self._make_bay('Bay 1', child_name='Server-01', role_color='4caf50'),
284
+ ]
285
+ device = self._make_device(bays=bays)
286
+
287
+ with patch.object(self.ep, '_get_plugin_setting', return_value=False):
288
+ self.ep._patched_draw_device(
289
+ self.svg_instance, device, (50, 100), (200, 30), color=None
290
+ )
291
+
292
+ self.mock_original.assert_not_called()
293
+
294
+ def test_empty_queryset_delegates_to_original(self):
295
+ device = self._make_device(bays=[])
296
+
297
+ self.ep._patched_draw_device(
298
+ self.svg_instance, device, (50, 100), (200, 60), color='aa1409'
299
+ )
300
+
301
+ self.mock_original.assert_called_once()
302
+
303
+
304
+ class TestDoublePatching(unittest.TestCase):
305
+
306
+ def test_apply_patch_is_idempotent(self):
307
+ import netbox_render.elevation_patch as ep
308
+
309
+ sentinel_original = MagicMock()
310
+ ep._original_draw_device = sentinel_original
311
+
312
+ with patch.object(ep, 'verify_patch_target'):
313
+ ep.apply_elevation_patch()
314
+
315
+ self.assertIs(ep._original_draw_device, sentinel_original)
316
+
317
+
318
+ if __name__ == '__main__':
319
+ unittest.main()