-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd-PatServer.tests.ps1
More file actions
698 lines (554 loc) · 31.5 KB
/
Add-PatServer.tests.ps1
File metadata and controls
698 lines (554 loc) · 31.5 KB
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
BeforeAll {
# Import the module from source
$ProjectRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot))
$ModuleRoot = Join-Path $ProjectRoot 'PlexAutomationToolkit'
$moduleManifestPath = Join-Path $ModuleRoot 'PlexAutomationToolkit.psd1'
Get-Module PlexAutomationToolkit | Remove-Module -Force -ErrorAction 'Ignore'
Import-Module -Name $moduleManifestPath -Verbose:$false -ErrorAction 'Stop'
}
Describe 'Add-PatServer' {
BeforeEach {
# Mock config functions to use in-memory config
$script:mockConfig = [PSCustomObject]@{
version = '1.0'
servers = @()
}
Mock -CommandName Get-PatServerConfiguration -ModuleName PlexAutomationToolkit -MockWith {
return $script:mockConfig
}
Mock -CommandName Set-PatServerConfiguration -ModuleName PlexAutomationToolkit -MockWith {
param($configuration)
$script:mockConfig = $configuration
}
# Mock validation functions - default to success
Mock -CommandName Join-PatUri -ModuleName PlexAutomationToolkit -MockWith {
param($BaseUri, $Endpoint)
return "$BaseUri$Endpoint"
}
Mock -CommandName Get-PatAuthenticationHeader -ModuleName PlexAutomationToolkit -MockWith {
param($Server)
$headers = @{ Accept = 'application/json' }
if ($Server.PSObject.Properties['token']) {
$headers['X-Plex-Token'] = $Server.token
}
return $headers
}
Mock -CommandName Invoke-PatApi -ModuleName PlexAutomationToolkit -MockWith {
# Default to successful validation
return @{ friendlyName = 'Mock Server' }
}
# Mock Set-PatServerToken to simulate plaintext storage (no vault)
Mock -CommandName Set-PatServerToken -ModuleName PlexAutomationToolkit -MockWith {
param($ServerName, $Token)
return [PSCustomObject]@{
StorageType = 'Plaintext'
Token = $Token
}
}
# Mock vault token cleanup; -Force overwrite path invokes this before re-adding.
Mock -CommandName Remove-PatServerToken -ModuleName PlexAutomationToolkit -MockWith { }
}
Context 'Adding a basic server' {
It 'Should add server to empty configuration' {
Add-PatServer -Name 'Test Server' -ServerUri 'http://test:32400'
$script:mockConfig.servers.Count | Should -Be 1
$script:mockConfig.servers[0].name | Should -Be 'Test Server'
$script:mockConfig.servers[0].uri | Should -Be 'http://test:32400'
$script:mockConfig.servers[0].default | Should -Be $false
}
It 'Should add server and mark as default' {
Add-PatServer -Name 'Main Server' -ServerUri 'http://main:32400' -Default
$script:mockConfig.servers[0].default | Should -Be $true
}
It 'Should add multiple servers' {
Add-PatServer -Name 'Server1' -ServerUri 'http://server1:32400'
Add-PatServer -Name 'Server2' -ServerUri 'http://server2:32400'
Add-PatServer -Name 'Server3' -ServerUri 'http://server3:32400'
$script:mockConfig.servers.Count | Should -Be 3
}
It 'Should add server with authentication token' {
Add-PatServer -Name 'Auth Server' -ServerUri 'http://auth:32400' -Token 'ABC123xyz'
$script:mockConfig.servers[0].token | Should -Be 'ABC123xyz'
}
It 'Should not add token property when token is not provided' {
Add-PatServer -Name 'No Auth' -ServerUri 'http://noauth:32400'
$script:mockConfig.servers[0].PSObject.Properties['token'] | Should -BeNullOrEmpty
}
}
Context 'Default server handling' {
It 'Should unset other defaults when adding new default server' {
Add-PatServer -Name 'Server1' -ServerUri 'http://server1:32400' -Default
Add-PatServer -Name 'Server2' -ServerUri 'http://server2:32400' -Default
$script:mockConfig.servers.Count | Should -Be 2
$script:mockConfig.servers[0].default | Should -Be $false
$script:mockConfig.servers[1].default | Should -Be $true
}
It 'Should preserve non-default servers when adding default' {
Add-PatServer -Name 'NonDefault' -ServerUri 'http://nd:32400'
Add-PatServer -Name 'Default' -ServerUri 'http://def:32400' -Default
$script:mockConfig.servers[0].default | Should -Be $false
$script:mockConfig.servers[1].default | Should -Be $true
}
}
Context 'Duplicate handling' {
It 'Should throw on duplicate server name without -Force' {
Add-PatServer -Name 'Duplicate' -ServerUri 'http://dup1:32400'
{ Add-PatServer -Name 'Duplicate' -ServerUri 'http://dup2:32400' } | Should -Throw "*already exists*"
}
It 'Should suggest -Force and Update-PatServerToken in the duplicate error' {
Add-PatServer -Name 'Duplicate' -ServerUri 'http://dup1:32400'
{ Add-PatServer -Name 'Duplicate' -ServerUri 'http://dup2:32400' } |
Should -Throw "*-Force*Update-PatServerToken*"
}
It 'Should allow same URI with different names' {
Add-PatServer -Name 'Server1' -ServerUri 'http://same:32400'
Add-PatServer -Name 'Server2' -ServerUri 'http://same:32400'
$script:mockConfig.servers.Count | Should -Be 2
}
It 'Should overwrite existing entry when -Force is specified' {
Add-PatServer -Name 'plex' -ServerUri 'http://old:32400' -Token 'OLD-TOKEN'
Add-PatServer -Name 'plex' -ServerUri 'http://new:32400' -Token 'NEW-TOKEN' -Force -Confirm:$false
$script:mockConfig.servers.Count | Should -Be 1
$script:mockConfig.servers[0].uri | Should -Be 'http://new:32400'
$script:mockConfig.servers[0].token | Should -Be 'NEW-TOKEN'
}
It 'Should remove vault token entry when -Force overwrites with a non-vault-stored new entry' {
# Default mock returns Plaintext, so the new entry has no tokenInVault. Any vault
# entry from the prior add would be orphaned without the cleanup call.
Add-PatServer -Name 'plex' -ServerUri 'http://old:32400' -Token 'OLD-TOKEN'
Add-PatServer -Name 'plex' -ServerUri 'http://new:32400' -Token 'NEW-TOKEN' -Force -Confirm:$false
Should -Invoke Remove-PatServerToken -ModuleName PlexAutomationToolkit -Times 1 -ParameterFilter {
$ServerName -eq 'plex'
}
}
It 'Should not call Remove-PatServerToken when -Force overwrites with a vault-stored new token' {
# When the new -Token is stored in the vault, Set-PatServerToken has already
# overwritten the vault entry; calling Remove-PatServerToken would clobber it.
Mock -CommandName Set-PatServerToken -ModuleName PlexAutomationToolkit -MockWith {
param($ServerName, $Token)
return [PSCustomObject]@{
StorageType = 'Vault'
Token = $null
}
}
Add-PatServer -Name 'plex' -ServerUri 'http://old:32400' -Token 'OLD-TOKEN'
Add-PatServer -Name 'plex' -ServerUri 'http://new:32400' -Token 'NEW-TOKEN' -Force -Confirm:$false
Should -Invoke Remove-PatServerToken -ModuleName PlexAutomationToolkit -Times 0
}
It 'Should not invoke Remove-PatServerToken or persist config when -Force overwrite is run with -WhatIf' {
Add-PatServer -Name 'plex' -ServerUri 'http://old:32400' -Token 'OLD-TOKEN'
# First add wrote the config; from here, -WhatIf must not perform any further writes.
Should -Invoke Set-PatServerConfiguration -ModuleName PlexAutomationToolkit -Times 1
Add-PatServer -Name 'plex' -ServerUri 'http://new:32400' -Token 'NEW-TOKEN' -Force -WhatIf
Should -Invoke Remove-PatServerToken -ModuleName PlexAutomationToolkit -Times 0
Should -Invoke Set-PatServerConfiguration -ModuleName PlexAutomationToolkit -Times 1
# In-memory configuration is unchanged from the first add.
$script:mockConfig.servers.Count | Should -Be 1
$script:mockConfig.servers[0].name | Should -Be 'plex'
$script:mockConfig.servers[0].uri | Should -Be 'http://old:32400'
}
It 'Should replace fields wholesale when -Force overwrites (no merge)' {
Add-PatServer -Name 'plex' -ServerUri 'http://old:32400' -LocalUri 'http://192.168.1.50:32400' -PreferLocal -SkipValidation
Add-PatServer -Name 'plex' -ServerUri 'http://new:32400' -Force -SkipValidation -Confirm:$false
$script:mockConfig.servers.Count | Should -Be 1
$script:mockConfig.servers[0].uri | Should -Be 'http://new:32400'
# Replace semantics: localUri/preferLocal from the old entry are not preserved.
$script:mockConfig.servers[0].PSObject.Properties['localUri'] | Should -BeNullOrEmpty
$script:mockConfig.servers[0].PSObject.Properties['preferLocal'] | Should -BeNullOrEmpty
}
It 'Should preserve other servers when -Force overwrites a single entry' {
Add-PatServer -Name 'keep' -ServerUri 'http://keep:32400'
Add-PatServer -Name 'plex' -ServerUri 'http://old:32400'
Add-PatServer -Name 'plex' -ServerUri 'http://new:32400' -Force -Confirm:$false
$script:mockConfig.servers.Count | Should -Be 2
($script:mockConfig.servers | Where-Object { $_.name -eq 'keep' }).uri | Should -Be 'http://keep:32400'
($script:mockConfig.servers | Where-Object { $_.name -eq 'plex' }).uri | Should -Be 'http://new:32400'
}
It 'Should not call Remove-PatServerToken when -Force adds a brand new entry' {
Add-PatServer -Name 'fresh' -ServerUri 'http://fresh:32400' -Force -Confirm:$false
Should -Invoke Remove-PatServerToken -ModuleName PlexAutomationToolkit -Times 0
}
}
Context 'PassThru parameter' {
It 'Should return server object when PassThru is specified' {
$result = Add-PatServer -Name 'Test' -ServerUri 'http://test:32400' -PassThru
$result | Should -Not -BeNullOrEmpty
$result.name | Should -Be 'Test'
$result.uri | Should -Be 'http://test:32400'
}
It 'Should not return object when PassThru is not specified' {
$result = Add-PatServer -Name 'Test' -ServerUri 'http://test:32400'
$result | Should -BeNullOrEmpty
}
It 'Should return server with token when provided' {
$result = Add-PatServer -Name 'Auth' -ServerUri 'http://auth:32400' -Token 'ABC' -PassThru
$result.token | Should -Be 'ABC'
}
}
Context 'ShouldProcess support' {
It 'Should support WhatIf' {
Add-PatServer -Name 'WhatIf Test' -ServerUri 'http://test:32400' -WhatIf
# WhatIf should prevent Set-PatServerConfiguration from being called
Should -Invoke Set-PatServerConfiguration -ModuleName PlexAutomationToolkit -Times 0
}
It 'Should call ShouldProcess with correct target' {
Add-PatServer -Name 'Test' -ServerUri 'http://test:32400' -Confirm:$false
Should -Invoke Set-PatServerConfiguration -ModuleName PlexAutomationToolkit -Times 1
}
}
Context 'Error handling' {
It 'Should throw when Get-PatServerConfiguration fails' {
Mock -CommandName Get-PatServerConfiguration -ModuleName PlexAutomationToolkit -MockWith {
throw 'Config error'
}
{ Add-PatServer -Name 'Test' -ServerUri 'http://test:32400' } | Should -Throw
}
It 'Should throw when Set-PatServerConfiguration fails' {
Mock -CommandName Set-PatServerConfiguration -ModuleName PlexAutomationToolkit -MockWith {
throw 'Write error'
}
{ Add-PatServer -Name 'Test' -ServerUri 'http://test:32400' } | Should -Throw
}
}
Context 'Server validation' {
It 'Should validate server connectivity by default' {
Add-PatServer -Name 'Test' -ServerUri 'http://test:32400'
Should -Invoke Invoke-PatApi -ModuleName PlexAutomationToolkit -Times 1
}
It 'Should skip validation when SkipValidation is specified' {
Add-PatServer -Name 'Test' -ServerUri 'http://test:32400' -SkipValidation
Should -Invoke Invoke-PatApi -ModuleName PlexAutomationToolkit -Times 0
}
It 'Should include token in validation headers when token is provided' {
Add-PatServer -Name 'Auth' -ServerUri 'http://auth:32400' -Token 'ABC123'
Should -Invoke Get-PatAuthenticationHeader -ModuleName PlexAutomationToolkit -Times 1 -ParameterFilter {
$Server.token -eq 'ABC123'
}
}
It 'Should warn on connection failure but still save configuration' {
Mock -CommandName Invoke-PatApi -ModuleName PlexAutomationToolkit -MockWith {
throw 'Unable to connect to the remote server'
}
$warnings = @()
Add-PatServer -Name 'Offline' -ServerUri 'http://offline:32400' -WarningVariable warnings 3>$null
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'Unable to connect'
$script:mockConfig.servers.Count | Should -Be 1
}
It 'Should warn on authentication failure with token' {
Mock -CommandName Invoke-PatApi -ModuleName PlexAutomationToolkit -MockWith {
throw 'Error invoking Plex API: 401 Unauthorized'
}
$warnings = @()
Add-PatServer -Name 'BadToken' -ServerUri 'http://test:32400' -Token 'INVALID' -WarningVariable warnings 3>$null
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'Authentication with provided token failed'
$script:mockConfig.servers.Count | Should -Be 1
}
It 'Should attempt authentication with -Force when server requires auth' {
# When server requires auth (401) and -Force is specified,
# automatically attempts Connect-PatAccount.
# Mock Connect-PatAccount to simulate failed auth (since we can't actually auth in tests)
Mock -CommandName Invoke-PatApi -ModuleName PlexAutomationToolkit -MockWith {
throw 'Error invoking Plex API: 401 Unauthorized'
}
Mock -CommandName Connect-PatAccount -ModuleName PlexAutomationToolkit -MockWith {
throw 'Authentication failed in test'
}
$warnings = @()
Add-PatServer -Name 'NeedsAuth' -ServerUri 'http://auth:32400' -Force -WarningVariable warnings -Confirm:$false 3>$null
# With -Force, Connect-PatAccount is called automatically
Should -Invoke Connect-PatAccount -ModuleName PlexAutomationToolkit -Times 1
# Since auth failed, server saved without token with warning
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'Authentication failed'
$script:mockConfig.servers.Count | Should -Be 1
}
It 'Should warn on generic validation errors' {
Mock -CommandName Invoke-PatApi -ModuleName PlexAutomationToolkit -MockWith {
throw 'Some unexpected error'
}
$warnings = @()
Add-PatServer -Name 'Error' -ServerUri 'http://test:32400' -WarningVariable warnings 3>$null
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'Failed to validate server'
$script:mockConfig.servers.Count | Should -Be 1
}
}
Context 'HTTPS upgrade detection' {
BeforeEach {
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
return @{ friendlyName = 'Mock Server' }
}
}
It 'Should use HTTPS when available with -Force' {
# Mock HTTPS check to succeed
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
return @{ friendlyName = 'Mock Server' }
}
$result = Add-PatServer -Name 'HTTPS Test' -ServerUri 'http://test:32400' -Force -PassThru -Confirm:$false
$result.uri | Should -Be 'https://test:32400'
}
It 'Should detect HTTPS available from 401 response' {
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
$response = [System.Net.HttpWebResponse]::new()
$exception = [System.Net.WebException]::new('401', $null, [System.Net.WebExceptionStatus]::ProtocolError, $response)
throw $exception
} -ParameterFilter { $Uri -like 'https://*' }
# This should still detect HTTPS as available because 401 means the server responded
# The test validates the error handling path for 401/403
}
It 'Should warn when using HTTP without HTTPS available' {
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
throw 'Connection failed'
} -ParameterFilter { $Uri -like 'https://*' }
$warnings = @()
Add-PatServer -Name 'HTTP Only' -ServerUri 'http://test:32400' -WarningVariable warnings 3>$null
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'Using unencrypted HTTP'
}
}
Context 'Token vault storage' {
It 'Should set tokenInVault when vault storage succeeds' {
Mock -CommandName Set-PatServerToken -ModuleName PlexAutomationToolkit -MockWith {
param($ServerName, $Token)
return [PSCustomObject]@{
StorageType = 'Vault'
Token = $null
}
}
$result = Add-PatServer -Name 'Vault Test' -ServerUri 'http://test:32400' -Token 'SECRET' -PassThru
$result.tokenInVault | Should -Be $true
$result.PSObject.Properties['token'] | Should -BeNullOrEmpty
}
}
Context 'Successful authentication when server requires auth' {
It 'Should store auth token when Connect-PatAccount succeeds with -Force' {
Mock -CommandName Invoke-PatApi -ModuleName PlexAutomationToolkit -MockWith {
throw 'Error invoking Plex API: 401 Unauthorized'
}
Mock -CommandName Connect-PatAccount -ModuleName PlexAutomationToolkit -MockWith {
return 'NEW-AUTH-TOKEN'
}
Mock -CommandName Set-PatServerToken -ModuleName PlexAutomationToolkit -MockWith {
param($ServerName, $Token)
return [PSCustomObject]@{
StorageType = 'Plaintext'
Token = $Token
}
}
$result = Add-PatServer -Name 'Auth Success' -ServerUri 'http://test:32400' -Force -PassThru -Confirm:$false
Should -Invoke Connect-PatAccount -ModuleName PlexAutomationToolkit -Times 1
$result.token | Should -Be 'NEW-AUTH-TOKEN'
}
It 'Should store auth token in vault when vault is available' {
Mock -CommandName Invoke-PatApi -ModuleName PlexAutomationToolkit -MockWith {
throw 'Error invoking Plex API: 401 Unauthorized'
}
Mock -CommandName Connect-PatAccount -ModuleName PlexAutomationToolkit -MockWith {
return 'NEW-AUTH-TOKEN'
}
Mock -CommandName Set-PatServerToken -ModuleName PlexAutomationToolkit -MockWith {
param($ServerName, $Token)
return [PSCustomObject]@{
StorageType = 'Vault'
Token = $null
}
}
$result = Add-PatServer -Name 'Auth Vault' -ServerUri 'http://test:32400' -Force -PassThru -Confirm:$false
$result.tokenInVault | Should -Be $true
}
}
Context 'DetectLocalUri feature' {
BeforeEach {
Mock -CommandName Get-PatServerIdentity -ModuleName PlexAutomationToolkit -MockWith {
return [PSCustomObject]@{
MachineIdentifier = 'abc123def456'
FriendlyName = 'Test Server'
}
}
Mock -CommandName Get-PatServerConnection -ModuleName PlexAutomationToolkit -MockWith {
return @(
[PSCustomObject]@{
Uri = 'https://remote.plex.tv:32400'
Local = $false
Relay = $false
IPv6 = $false
Protocol = 'https'
Address = 'remote.plex.tv'
Port = 32400
},
[PSCustomObject]@{
Uri = 'http://192.168.1.100:32400'
Local = $true
Relay = $false
IPv6 = $false
Protocol = 'http'
Address = '192.168.1.100'
Port = 32400
}
)
}
}
It 'Should warn when DetectLocalUri is used without token' {
$warnings = @()
Add-PatServer -Name 'NoToken' -ServerUri 'http://test:32400' -DetectLocalUri -WarningVariable warnings 3>$null
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'DetectLocalUri requires a valid authentication token'
}
It 'Should detect and store local URI when available' {
$result = Add-PatServer -Name 'LocalDetect' -ServerUri 'https://remote.plex.tv:32400' -Token 'ABC123' -DetectLocalUri -PassThru
Should -Invoke Get-PatServerIdentity -ModuleName PlexAutomationToolkit -Times 1
Should -Invoke Get-PatServerConnection -ModuleName PlexAutomationToolkit -Times 1
$result.localUri | Should -Be 'http://192.168.1.100:32400'
$result.preferLocal | Should -Be $true
}
It 'Should prefer HTTPS local connection when available' {
Mock -CommandName Get-PatServerConnection -ModuleName PlexAutomationToolkit -MockWith {
return @(
[PSCustomObject]@{
Uri = 'http://192.168.1.100:32400'
Local = $true
Relay = $false
Protocol = 'http'
},
[PSCustomObject]@{
Uri = 'https://192.168.1.100:32400'
Local = $true
Relay = $false
Protocol = 'https'
}
)
}
$result = Add-PatServer -Name 'HTTPSLocal' -ServerUri 'https://remote:32400' -Token 'ABC' -DetectLocalUri -PassThru
$result.localUri | Should -Be 'https://192.168.1.100:32400'
}
It 'Should not set localUri when detected URI matches primary URI' {
Mock -CommandName Get-PatServerConnection -ModuleName PlexAutomationToolkit -MockWith {
return @(
[PSCustomObject]@{
Uri = 'http://test:32400'
Local = $true
Relay = $false
Protocol = 'http'
}
)
}
$result = Add-PatServer -Name 'SameUri' -ServerUri 'http://test:32400' -Token 'ABC' -DetectLocalUri -PassThru -SkipValidation
$result.PSObject.Properties['localUri'] | Should -BeNullOrEmpty
}
It 'Should skip relay connections when detecting local URI' {
Mock -CommandName Get-PatServerConnection -ModuleName PlexAutomationToolkit -MockWith {
return @(
[PSCustomObject]@{
Uri = 'https://relay.plex.tv:32400'
Local = $true
Relay = $true
Protocol = 'https'
}
)
}
$result = Add-PatServer -Name 'RelayOnly' -ServerUri 'http://test:32400' -Token 'ABC' -DetectLocalUri -PassThru
$result.PSObject.Properties['localUri'] | Should -BeNullOrEmpty
}
It 'Should handle no connections returned from API' {
Mock -CommandName Get-PatServerConnection -ModuleName PlexAutomationToolkit -MockWith {
return @()
}
$result = Add-PatServer -Name 'NoConns' -ServerUri 'http://test:32400' -Token 'ABC' -DetectLocalUri -PassThru
$result.PSObject.Properties['localUri'] | Should -BeNullOrEmpty
}
It 'Should handle API errors gracefully with warning' {
Mock -CommandName Get-PatServerIdentity -ModuleName PlexAutomationToolkit -MockWith {
throw 'API connection failed'
}
$warnings = @()
$result = Add-PatServer -Name 'APIError' -ServerUri 'http://test:32400' -Token 'ABC' -DetectLocalUri -PassThru -WarningVariable warnings 3>$null
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'Failed to detect local URI'
# Server should still be added
$script:mockConfig.servers.Count | Should -Be 1
}
It 'Should skip DetectLocalUri when SkipValidation is specified' {
$result = Add-PatServer -Name 'SkipDetect' -ServerUri 'http://test:32400' -Token 'ABC' -DetectLocalUri -SkipValidation -PassThru
Should -Invoke Get-PatServerIdentity -ModuleName PlexAutomationToolkit -Times 0
$result.PSObject.Properties['localUri'] | Should -BeNullOrEmpty
}
}
Context 'LocalUri and PreferLocal parameters' {
It 'Should store LocalUri when provided' {
$result = Add-PatServer -Name 'WithLocal' -ServerUri 'https://remote:32400' -LocalUri 'http://192.168.1.100:32400' -PassThru -SkipValidation
$result.localUri | Should -Be 'http://192.168.1.100:32400'
}
It 'Should store PreferLocal when LocalUri is provided' {
$result = Add-PatServer -Name 'PreferLocal' -ServerUri 'https://remote:32400' -LocalUri 'http://local:32400' -PreferLocal -PassThru -SkipValidation
$result.localUri | Should -Be 'http://local:32400'
$result.preferLocal | Should -Be $true
}
It 'Should set preferLocal to false when LocalUri provided without PreferLocal switch' {
$result = Add-PatServer -Name 'NoPrefer' -ServerUri 'https://remote:32400' -LocalUri 'http://local:32400' -PassThru -SkipValidation
$result.preferLocal | Should -Be $false
}
It 'Should warn when PreferLocal specified without LocalUri' {
$warnings = @()
Add-PatServer -Name 'OrphanPrefer' -ServerUri 'http://test:32400' -PreferLocal -SkipValidation -WarningVariable warnings 3>$null
$warnings | Should -Not -BeNullOrEmpty
$warnings -join ' ' | Should -Match 'PreferLocal specified but no LocalUri'
}
}
# Note: Interactive prompt paths (ShouldContinue) cannot be unit tested
# as they require a valid $PSCmdlet context. These paths are tested manually:
# - User declining HTTPS upgrade (lines 231-233)
# - User declining authentication prompt (lines 383-385)
Context 'HTTPS detection edge cases' {
It 'Should detect HTTPS available when server returns 401' {
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
# Simulate a 401 response which indicates HTTPS is working
$mockResponse = New-Object PSObject -Property @{
StatusCode = @{ value__ = 401 }
}
$exception = New-Object System.Exception '401 Unauthorized'
$exception | Add-Member -NotePropertyName 'Response' -NotePropertyValue $mockResponse -Force
throw $exception
} -ParameterFilter { $Uri -like 'https://*' }
$result = Add-PatServer -Name 'HTTPS401' -ServerUri 'http://test:32400' -Force -PassThru -Confirm:$false
# Should upgrade to HTTPS since 401 means server responded
$result.uri | Should -Be 'https://test:32400'
}
It 'Should detect HTTPS available when server returns 403' {
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
$mockResponse = New-Object PSObject -Property @{
StatusCode = @{ value__ = 403 }
}
$exception = New-Object System.Exception '403 Forbidden'
$exception | Add-Member -NotePropertyName 'Response' -NotePropertyValue $mockResponse -Force
throw $exception
} -ParameterFilter { $Uri -like 'https://*' }
$result = Add-PatServer -Name 'HTTPS403' -ServerUri 'http://test:32400' -Force -PassThru -Confirm:$false
$result.uri | Should -Be 'https://test:32400'
}
It 'Should not check HTTPS when SkipValidation is specified' {
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
return @{ friendlyName = 'Mock Server' }
}
$result = Add-PatServer -Name 'SkipHTTPS' -ServerUri 'http://test:32400' -SkipValidation -PassThru
# Should not have called Invoke-RestMethod for HTTPS check
Should -Invoke Invoke-RestMethod -ModuleName PlexAutomationToolkit -Times 0
$result.uri | Should -Be 'http://test:32400'
}
}
Context 'PowerShell 5.1 certificate callback handling' {
It 'Should handle certificate callback restoration in finally block' {
# This test ensures the finally block properly restores state
# We test by running multiple adds in sequence to verify no state leakage
Mock -CommandName Invoke-RestMethod -ModuleName PlexAutomationToolkit -MockWith {
return @{ friendlyName = 'Mock Server' }
}
# Add multiple servers - if callback isn't restored properly, subsequent calls may fail
Add-PatServer -Name 'Server1' -ServerUri 'http://test1:32400' -Force -Confirm:$false
Add-PatServer -Name 'Server2' -ServerUri 'http://test2:32400' -Force -Confirm:$false
Add-PatServer -Name 'Server3' -ServerUri 'http://test3:32400' -Force -Confirm:$false
$script:mockConfig.servers.Count | Should -Be 3
}
}
}