netbox 0.3.3

ergonomic rust client for NetBox 4.x REST API
Documentation
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! dcim endpoints for devices, racks, sites, interfaces, and inventory.
//!
//! includes cable path tracing for interfaces, console ports, and power connections.
//!
//! basic usage:
//! ```no_run
//! # use netbox::{Client, ClientConfig};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let client = Client::new(ClientConfig::new("https://netbox.example.com", "token"))?;
//! let devices = client.dcim().devices().list(None).await?;
//! println!("{}", devices.count);
//! # Ok(())
//! # }
//! ```
//!
//! cable tracing:
//! ```no_run
//! # use netbox::{Client, ClientConfig};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let client = Client::new(ClientConfig::new("https://netbox.example.com", "token"))?;
//! // trace an interface's cable path
//! let path = client.dcim().trace_interface(99).await?;
//! # Ok(())
//! # }
//! ```

use crate::Client;
use crate::error::Result;
use crate::resource::Resource;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

/// console port model.
pub type ConsolePort = crate::models::ConsolePort;
/// console server port model.
pub type ConsoleServerPort = crate::models::ConsoleServerPort;
/// interface model.
pub type Interface = crate::models::Interface;
/// power port model.
pub type PowerPort = crate::models::PowerPort;
/// power outlet model.
pub type PowerOutlet = crate::models::PowerOutlet;
/// power feed model.
pub type PowerFeed = crate::models::PowerFeed;

/// request for creating a new device (id-based references).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateDeviceRequest {
    /// device name.
    pub name: String,
    /// device type id.
    pub device_type: i32,
    /// role id.
    pub role: i32,
    /// site id.
    pub site: i32,
    /// status slug.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// serial number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serial: Option<String>,
    /// asset tag string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset_tag: Option<String>,
    /// tag IDs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<i32>>,
}

/// request for updating a device (id-based references).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateDeviceRequest {
    /// updated device name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// updated device type id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_type: Option<i32>,
    /// updated role id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<i32>,
    /// updated site id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub site: Option<i32>,
    /// updated status slug.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// updated serial number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serial: Option<String>,
    /// updated asset tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset_tag: Option<String>,
}

/// request for patching fields on a site.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchSiteFieldsRequest {
    /// custom field values.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_fields: Option<HashMap<String, Value>>,
    /// tag objects.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<crate::models::NestedTag>>,
}

/// request for patching fields on a device.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchDeviceFieldsRequest {
    /// custom field values.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_fields: Option<HashMap<String, Value>>,
    /// tag objects.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<crate::models::NestedTag>>,
    /// local context data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub local_context_data: Option<Value>,
}

/// request for patching fields on an interface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchInterfaceFieldsRequest {
    /// custom field values.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_fields: Option<HashMap<String, Value>>,
    /// tag objects.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<crate::models::NestedTag>>,
}

/// device model with config context.
pub type Device = crate::models::DeviceWithConfigContext;
/// connected device model.
pub type ConnectedDevice = crate::models::Device;

/// resource for cable terminations.
pub type CableTerminationsApi = Resource<crate::models::CableTermination>;
/// resource for cables.
pub type CablesApi = Resource<crate::models::Cable>;
/// resource for console port templates.
pub type ConsolePortTemplatesApi = Resource<crate::models::ConsolePortTemplate>;
/// resource for console ports.
pub type ConsolePortsApi = Resource<crate::models::ConsolePort>;
/// resource for console server port templates.
pub type ConsoleServerPortTemplatesApi = Resource<crate::models::ConsoleServerPortTemplate>;
/// resource for console server ports.
pub type ConsoleServerPortsApi = Resource<crate::models::ConsoleServerPort>;
/// resource for device bay templates.
pub type DeviceBayTemplatesApi = Resource<crate::models::DeviceBayTemplate>;
/// resource for device bays.
pub type DeviceBaysApi = Resource<crate::models::DeviceBay>;
/// resource for device roles.
pub type DeviceRolesApi = Resource<crate::models::DeviceRole>;
/// resource for device types.
pub type DeviceTypesApi = Resource<crate::models::DeviceType>;
/// resource for devices.
pub type DevicesApi = Resource<crate::models::DeviceWithConfigContext>;
/// resource for front port templates.
pub type FrontPortTemplatesApi = Resource<crate::models::FrontPortTemplate>;
/// resource for front ports.
pub type FrontPortsApi = Resource<crate::models::FrontPort>;
/// resource for interface templates.
pub type InterfaceTemplatesApi = Resource<crate::models::InterfaceTemplate>;
/// resource for interfaces.
pub type InterfacesApi = Resource<crate::models::Interface>;
/// resource for inventory item roles.
pub type InventoryItemRolesApi = Resource<crate::models::InventoryItemRole>;
/// resource for inventory item templates.
pub type InventoryItemTemplatesApi = Resource<crate::models::InventoryItemTemplate>;
/// resource for inventory items.
pub type InventoryItemsApi = Resource<crate::models::InventoryItem>;
/// resource for locations.
pub type LocationsApi = Resource<crate::models::Location>;
/// resource for MAC addresses.
pub type MacAddressesApi = Resource<crate::models::MacAddress>;
/// resource for manufacturers.
pub type ManufacturersApi = Resource<crate::models::Manufacturer>;
/// resource for module bay templates.
pub type ModuleBayTemplatesApi = Resource<crate::models::ModuleBayTemplate>;
/// resource for module bays.
pub type ModuleBaysApi = Resource<crate::models::ModuleBay>;
/// resource for module type profiles.
pub type ModuleTypeProfilesApi = Resource<crate::models::ModuleTypeProfile>;
/// resource for module types.
pub type ModuleTypesApi = Resource<crate::models::ModuleType>;
/// resource for modules.
pub type ModulesApi = Resource<crate::models::Module>;
/// resource for platforms.
pub type PlatformsApi = Resource<crate::models::Platform>;
/// resource for power feeds.
pub type PowerFeedsApi = Resource<crate::models::PowerFeed>;
/// resource for power outlet templates.
pub type PowerOutletTemplatesApi = Resource<crate::models::PowerOutletTemplate>;
/// resource for power outlets.
pub type PowerOutletsApi = Resource<crate::models::PowerOutlet>;
/// resource for power panels.
pub type PowerPanelsApi = Resource<crate::models::PowerPanel>;
/// resource for power port templates.
pub type PowerPortTemplatesApi = Resource<crate::models::PowerPortTemplate>;
/// resource for power ports.
pub type PowerPortsApi = Resource<crate::models::PowerPort>;
/// resource for rack reservations.
pub type RackReservationsApi = Resource<crate::models::RackReservation>;
/// resource for rack roles.
pub type RackRolesApi = Resource<crate::models::RackRole>;
/// resource for rack types.
pub type RackTypesApi = Resource<crate::models::RackType>;
/// resource for racks.
pub type RacksApi = Resource<crate::models::Rack>;
/// resource for rear port templates.
pub type RearPortTemplatesApi = Resource<crate::models::RearPortTemplate>;
/// resource for rear ports.
pub type RearPortsApi = Resource<crate::models::RearPort>;
/// resource for regions.
pub type RegionsApi = Resource<crate::models::Region>;
/// resource for site groups.
pub type SiteGroupsApi = Resource<crate::models::SiteGroup>;
/// resource for sites.
pub type SitesApi = Resource<crate::models::Site>;
/// resource for virtual chassis.
pub type VirtualChassisApi = Resource<crate::models::VirtualChassis>;
/// resource for virtual device contexts.
pub type VirtualDeviceContextsApi = Resource<crate::models::VirtualDeviceContext>;

/// api for dcim endpoints
#[derive(Clone)]
pub struct DcimApi {
    client: Client,
}

impl DcimApi {
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }

    /// fetch the device connected to a given peer device/interface.
    pub async fn connected_device(
        &self,
        peer_device: &str,
        peer_interface: &str,
    ) -> crate::error::Result<Vec<ConnectedDevice>> {
        #[derive(Serialize)]
        struct ConnectedDeviceQuery<'a> {
            peer_device: &'a str,
            peer_interface: &'a str,
        }

        let query = ConnectedDeviceQuery {
            peer_device,
            peer_interface,
        };

        self.client
            .get_with_params("dcim/connected-device/", &query)
            .await
    }

    /// returns the cable terminations resource.
    pub fn cable_terminations(&self) -> CableTerminationsApi {
        Resource::new(self.client.clone(), "dcim/cable-terminations/")
    }

    /// returns the cables resource.
    pub fn cables(&self) -> CablesApi {
        Resource::new(self.client.clone(), "dcim/cables/")
    }

    /// returns the console port templates resource.
    pub fn console_port_templates(&self) -> ConsolePortTemplatesApi {
        Resource::new(self.client.clone(), "dcim/console-port-templates/")
    }

    /// returns the console ports resource.
    pub fn console_ports(&self) -> ConsolePortsApi {
        Resource::new(self.client.clone(), "dcim/console-ports/")
    }

    /// returns the console server port templates resource.
    pub fn console_server_port_templates(&self) -> ConsoleServerPortTemplatesApi {
        Resource::new(self.client.clone(), "dcim/console-server-port-templates/")
    }

    /// returns the console server ports resource.
    pub fn console_server_ports(&self) -> ConsoleServerPortsApi {
        Resource::new(self.client.clone(), "dcim/console-server-ports/")
    }

    /// returns the device bay templates resource.
    pub fn device_bay_templates(&self) -> DeviceBayTemplatesApi {
        Resource::new(self.client.clone(), "dcim/device-bay-templates/")
    }

    /// returns the device bays resource.
    pub fn device_bays(&self) -> DeviceBaysApi {
        Resource::new(self.client.clone(), "dcim/device-bays/")
    }

    /// returns the device roles resource.
    pub fn device_roles(&self) -> DeviceRolesApi {
        Resource::new(self.client.clone(), "dcim/device-roles/")
    }

    /// returns the device types resource.
    pub fn device_types(&self) -> DeviceTypesApi {
        Resource::new(self.client.clone(), "dcim/device-types/")
    }

    /// returns the devices resource.
    pub fn devices(&self) -> DevicesApi {
        Resource::new(self.client.clone(), "dcim/devices/")
    }

    /// returns the front port templates resource.
    pub fn front_port_templates(&self) -> FrontPortTemplatesApi {
        Resource::new(self.client.clone(), "dcim/front-port-templates/")
    }

    /// returns the front ports resource.
    pub fn front_ports(&self) -> FrontPortsApi {
        Resource::new(self.client.clone(), "dcim/front-ports/")
    }

    /// returns the interface templates resource.
    pub fn interface_templates(&self) -> InterfaceTemplatesApi {
        Resource::new(self.client.clone(), "dcim/interface-templates/")
    }

    /// returns the interfaces resource.
    pub fn interfaces(&self) -> InterfacesApi {
        Resource::new(self.client.clone(), "dcim/interfaces/")
    }

    /// returns the inventory item roles resource.
    pub fn inventory_item_roles(&self) -> InventoryItemRolesApi {
        Resource::new(self.client.clone(), "dcim/inventory-item-roles/")
    }

    /// returns the inventory item templates resource.
    pub fn inventory_item_templates(&self) -> InventoryItemTemplatesApi {
        Resource::new(self.client.clone(), "dcim/inventory-item-templates/")
    }

    /// returns the inventory items resource.
    pub fn inventory_items(&self) -> InventoryItemsApi {
        Resource::new(self.client.clone(), "dcim/inventory-items/")
    }

    /// returns the locations resource.
    pub fn locations(&self) -> LocationsApi {
        Resource::new(self.client.clone(), "dcim/locations/")
    }

    /// returns the MAC addresses resource.
    pub fn mac_addresses(&self) -> MacAddressesApi {
        Resource::new(self.client.clone(), "dcim/mac-addresses/")
    }

    /// returns the manufacturers resource.
    pub fn manufacturers(&self) -> ManufacturersApi {
        Resource::new(self.client.clone(), "dcim/manufacturers/")
    }

    /// returns the module bay templates resource.
    pub fn module_bay_templates(&self) -> ModuleBayTemplatesApi {
        Resource::new(self.client.clone(), "dcim/module-bay-templates/")
    }

    /// returns the module bays resource.
    pub fn module_bays(&self) -> ModuleBaysApi {
        Resource::new(self.client.clone(), "dcim/module-bays/")
    }

    /// returns the module type profiles resource.
    pub fn module_type_profiles(&self) -> ModuleTypeProfilesApi {
        Resource::new(self.client.clone(), "dcim/module-type-profiles/")
    }

    /// returns the module types resource.
    pub fn module_types(&self) -> ModuleTypesApi {
        Resource::new(self.client.clone(), "dcim/module-types/")
    }

    /// returns the modules resource.
    pub fn modules(&self) -> ModulesApi {
        Resource::new(self.client.clone(), "dcim/modules/")
    }

    /// returns the platforms resource.
    pub fn platforms(&self) -> PlatformsApi {
        Resource::new(self.client.clone(), "dcim/platforms/")
    }

    /// returns the power feeds resource.
    pub fn power_feeds(&self) -> PowerFeedsApi {
        Resource::new(self.client.clone(), "dcim/power-feeds/")
    }

    /// returns the power outlet templates resource.
    pub fn power_outlet_templates(&self) -> PowerOutletTemplatesApi {
        Resource::new(self.client.clone(), "dcim/power-outlet-templates/")
    }

    /// returns the power outlets resource.
    pub fn power_outlets(&self) -> PowerOutletsApi {
        Resource::new(self.client.clone(), "dcim/power-outlets/")
    }

    /// returns the power panels resource.
    pub fn power_panels(&self) -> PowerPanelsApi {
        Resource::new(self.client.clone(), "dcim/power-panels/")
    }

    /// returns the power port templates resource.
    pub fn power_port_templates(&self) -> PowerPortTemplatesApi {
        Resource::new(self.client.clone(), "dcim/power-port-templates/")
    }

    /// returns the power ports resource.
    pub fn power_ports(&self) -> PowerPortsApi {
        Resource::new(self.client.clone(), "dcim/power-ports/")
    }

    /// returns the rack reservations resource.
    pub fn rack_reservations(&self) -> RackReservationsApi {
        Resource::new(self.client.clone(), "dcim/rack-reservations/")
    }

    /// returns the rack roles resource.
    pub fn rack_roles(&self) -> RackRolesApi {
        Resource::new(self.client.clone(), "dcim/rack-roles/")
    }

    /// returns the rack types resource.
    pub fn rack_types(&self) -> RackTypesApi {
        Resource::new(self.client.clone(), "dcim/rack-types/")
    }

    /// returns the racks resource.
    pub fn racks(&self) -> RacksApi {
        Resource::new(self.client.clone(), "dcim/racks/")
    }

    /// returns the rear port templates resource.
    pub fn rear_port_templates(&self) -> RearPortTemplatesApi {
        Resource::new(self.client.clone(), "dcim/rear-port-templates/")
    }

    /// returns the rear ports resource.
    pub fn rear_ports(&self) -> RearPortsApi {
        Resource::new(self.client.clone(), "dcim/rear-ports/")
    }

    /// returns the regions resource.
    pub fn regions(&self) -> RegionsApi {
        Resource::new(self.client.clone(), "dcim/regions/")
    }

    /// returns the site groups resource.
    pub fn site_groups(&self) -> SiteGroupsApi {
        Resource::new(self.client.clone(), "dcim/site-groups/")
    }

    /// returns the sites resource.
    pub fn sites(&self) -> SitesApi {
        Resource::new(self.client.clone(), "dcim/sites/")
    }

    /// returns the virtual chassis resource.
    pub fn virtual_chassis(&self) -> VirtualChassisApi {
        Resource::new(self.client.clone(), "dcim/virtual-chassis/")
    }

    /// returns the virtual device contexts resource.
    pub fn virtual_device_contexts(&self) -> VirtualDeviceContextsApi {
        Resource::new(self.client.clone(), "dcim/virtual-device-contexts/")
    }

    // Trace methods

    /// trace an interface's cable path.
    pub async fn trace_interface(&self, id: u64) -> Result<Interface> {
        self.client
            .get(&format!("dcim/interfaces/{}/trace/", id))
            .await
    }

    /// trace a console port's cable path.
    pub async fn trace_console_port(&self, id: u64) -> Result<ConsolePort> {
        self.client
            .get(&format!("dcim/console-ports/{}/trace/", id))
            .await
    }

    /// trace a console server port's cable path.
    pub async fn trace_console_server_port(&self, id: u64) -> Result<ConsoleServerPort> {
        self.client
            .get(&format!("dcim/console-server-ports/{}/trace/", id))
            .await
    }

    /// trace a power port's cable path.
    pub async fn trace_power_port(&self, id: u64) -> Result<PowerPort> {
        self.client
            .get(&format!("dcim/power-ports/{}/trace/", id))
            .await
    }

    /// trace a power outlet's cable path.
    pub async fn trace_power_outlet(&self, id: u64) -> Result<PowerOutlet> {
        self.client
            .get(&format!("dcim/power-outlets/{}/trace/", id))
            .await
    }

    /// trace a power feed's cable path.
    pub async fn trace_power_feed(&self, id: u64) -> Result<PowerFeed> {
        self.client
            .get(&format!("dcim/power-feeds/{}/trace/", id))
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ClientConfig;
    use httpmock::prelude::*;
    use serde::Serialize;
    use serde_json::json;
    use std::collections::HashMap;

    fn test_client() -> Client {
        let config = ClientConfig::new("https://netbox.example.com", "token");
        Client::new(config).unwrap()
    }

    fn mock_client(server: &MockServer) -> Client {
        let config = ClientConfig::new(server.base_url(), "test-token");
        Client::new(config).unwrap()
    }

    fn assert_path<T>(resource: Resource<T>, expected: &str)
    where
        T: serde::de::DeserializeOwned,
    {
        let paginator = resource.paginate(None).unwrap();
        assert_eq!(paginator.next_url(), Some(expected));
    }

    #[test]
    fn dcim_accessors_return_expected_paths() {
        let api = DcimApi::new(test_client());

        assert_path(api.cable_terminations(), "dcim/cable-terminations/");
        assert_path(api.cables(), "dcim/cables/");
        assert_path(api.console_port_templates(), "dcim/console-port-templates/");
        assert_path(api.console_ports(), "dcim/console-ports/");
        assert_path(
            api.console_server_port_templates(),
            "dcim/console-server-port-templates/",
        );
        assert_path(api.console_server_ports(), "dcim/console-server-ports/");
        assert_path(api.device_bay_templates(), "dcim/device-bay-templates/");
        assert_path(api.device_bays(), "dcim/device-bays/");
        assert_path(api.device_roles(), "dcim/device-roles/");
        assert_path(api.device_types(), "dcim/device-types/");
        assert_path(api.devices(), "dcim/devices/");
        assert_path(api.front_port_templates(), "dcim/front-port-templates/");
        assert_path(api.front_ports(), "dcim/front-ports/");
        assert_path(api.interface_templates(), "dcim/interface-templates/");
        assert_path(api.interfaces(), "dcim/interfaces/");
        assert_path(api.inventory_item_roles(), "dcim/inventory-item-roles/");
        assert_path(
            api.inventory_item_templates(),
            "dcim/inventory-item-templates/",
        );
        assert_path(api.inventory_items(), "dcim/inventory-items/");
        assert_path(api.locations(), "dcim/locations/");
        assert_path(api.mac_addresses(), "dcim/mac-addresses/");
        assert_path(api.manufacturers(), "dcim/manufacturers/");
        assert_path(api.module_bay_templates(), "dcim/module-bay-templates/");
        assert_path(api.module_bays(), "dcim/module-bays/");
        assert_path(api.module_type_profiles(), "dcim/module-type-profiles/");
        assert_path(api.module_types(), "dcim/module-types/");
        assert_path(api.modules(), "dcim/modules/");
        assert_path(api.platforms(), "dcim/platforms/");
        assert_path(api.power_feeds(), "dcim/power-feeds/");
        assert_path(api.power_outlet_templates(), "dcim/power-outlet-templates/");
        assert_path(api.power_outlets(), "dcim/power-outlets/");
        assert_path(api.power_panels(), "dcim/power-panels/");
        assert_path(api.power_port_templates(), "dcim/power-port-templates/");
        assert_path(api.power_ports(), "dcim/power-ports/");
        assert_path(api.rack_reservations(), "dcim/rack-reservations/");
        assert_path(api.rack_roles(), "dcim/rack-roles/");
        assert_path(api.rack_types(), "dcim/rack-types/");
        assert_path(api.racks(), "dcim/racks/");
        assert_path(api.rear_port_templates(), "dcim/rear-port-templates/");
        assert_path(api.rear_ports(), "dcim/rear-ports/");
        assert_path(api.regions(), "dcim/regions/");
        assert_path(api.site_groups(), "dcim/site-groups/");
        assert_path(api.sites(), "dcim/sites/");
        assert_path(api.virtual_chassis(), "dcim/virtual-chassis/");
        assert_path(
            api.virtual_device_contexts(),
            "dcim/virtual-device-contexts/",
        );
    }

    #[test]
    fn serialize_device_requests() {
        let create = CreateDeviceRequest {
            name: "device1".to_string(),
            device_type: 1,
            role: 2,
            site: 3,
            status: Some("active".to_string()),
            serial: None,
            asset_tag: None,
            tags: None,
        };
        let value = serde_json::to_value(&create).unwrap();
        assert_eq!(value["name"], "device1");
        assert_eq!(value["device_type"], 1);
        assert_eq!(value["role"], 2);
        assert_eq!(value["site"], 3);
        assert_eq!(value["status"], "active");

        let update = UpdateDeviceRequest {
            name: None,
            device_type: None,
            role: None,
            site: None,
            status: Some("offline".to_string()),
            serial: Some("SN1".to_string()),
            asset_tag: None,
        };
        let value = serde_json::to_value(&update).unwrap();
        assert_eq!(value["status"], "offline");
        assert_eq!(value["serial"], "SN1");
        assert!(value.get("name").is_none());
    }

    #[test]
    fn serialize_projection_patch_requests() {
        let mut fields = HashMap::new();
        fields.insert("fabric".to_string(), json!("fra1"));
        let tags = vec![crate::models::NestedTag::new(
            "EVPN Fabric".to_string(),
            "evpn-fabric".to_string(),
        )];

        let site = PatchSiteFieldsRequest {
            custom_fields: Some(fields.clone()),
            tags: Some(tags.clone()),
        };
        let value = serde_json::to_value(&site).unwrap();
        assert_eq!(value["custom_fields"]["fabric"], "fra1");
        assert_eq!(value["tags"][0]["slug"], "evpn-fabric");

        let device = PatchDeviceFieldsRequest {
            custom_fields: Some(fields),
            tags: Some(tags),
            local_context_data: Some(json!({"alembic": {"role_hint": "leaf"}})),
        };
        let value = serde_json::to_value(&device).unwrap();
        assert_eq!(value["custom_fields"]["fabric"], "fra1");
        assert_eq!(value["tags"][0]["name"], "EVPN Fabric");
        assert_eq!(value["local_context_data"]["alembic"]["role_hint"], "leaf");

        let interface = PatchInterfaceFieldsRequest {
            custom_fields: None,
            tags: None,
        };
        let value = serde_json::to_value(&interface).unwrap();
        assert!(value.get("custom_fields").is_none());
        assert!(value.get("tags").is_none());
    }

    #[test]
    fn connected_device_query_serializes() {
        #[derive(Serialize)]
        struct Query<'a> {
            peer_device: &'a str,
            peer_interface: &'a str,
        }

        let query = Query {
            peer_device: "leaf-01",
            peer_interface: "Ethernet1",
        };

        let encoded = serde_urlencoded::to_string(&query).unwrap();
        assert!(encoded.contains("peer_device=leaf-01"));
        assert!(encoded.contains("peer_interface=Ethernet1"));
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn trace_endpoints_use_expected_paths() {
        let server = MockServer::start();
        let client = mock_client(&server);

        // trace interface
        let mock1 = server.mock(|when, then| {
            when.method(GET).path("/api/dcim/interfaces/42/trace/");
            then.status(200).json_body(json!({}));
        });
        let _ = client.dcim().trace_interface(42).await;
        mock1.assert();

        // trace console port
        let mock2 = server.mock(|when, then| {
            when.method(GET).path("/api/dcim/console-ports/5/trace/");
            then.status(200).json_body(json!({}));
        });
        let _ = client.dcim().trace_console_port(5).await;
        mock2.assert();

        // trace console server port
        let mock3 = server.mock(|when, then| {
            when.method(GET)
                .path("/api/dcim/console-server-ports/3/trace/");
            then.status(200).json_body(json!({}));
        });
        let _ = client.dcim().trace_console_server_port(3).await;
        mock3.assert();

        // trace power port
        let mock4 = server.mock(|when, then| {
            when.method(GET).path("/api/dcim/power-ports/7/trace/");
            then.status(200).json_body(json!({}));
        });
        let _ = client.dcim().trace_power_port(7).await;
        mock4.assert();

        // trace power outlet
        let mock5 = server.mock(|when, then| {
            when.method(GET).path("/api/dcim/power-outlets/2/trace/");
            then.status(200).json_body(json!({}));
        });
        let _ = client.dcim().trace_power_outlet(2).await;
        mock5.assert();

        // trace power feed
        let mock6 = server.mock(|when, then| {
            when.method(GET).path("/api/dcim/power-feeds/9/trace/");
            then.status(200).json_body(json!({}));
        });
        let _ = client.dcim().trace_power_feed(9).await;
        mock6.assert();
    }
}