p2p-swift / Tests / IrdP2PCryptoTests / IdentifierTests.swift
169 words
 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
import Foundation
import Testing
@testable import IrdP2PCrypto

@Suite struct IdentifierTests {
    @Test func secretMustBeAtLeast16Bytes() throws {
        let v = try vector("room-crypto")["tooShort"]!
        #expect(throws: IdentifierError.roomSecretTooShort(bytes: 15)) { try RoomSecret(base64URL: v["secret"]!.str) }
        #expect(throws: IdentifierError.malformedBase64URL) { try RoomSecret(base64URL: "***") }
        let s = RoomSecret.random()
        #expect(s.bytes.count == 32)
        #expect(s.base64URL.count == 43)
        let back = try RoomSecret(base64URL: s.base64URL)
        #expect(back == s)
    }

    @Test func roomIdShape() throws {
        #expect(RoomId.isValid(String(repeating: "A", count: 43)))
        #expect(!RoomId.isValid(String(repeating: "A", count: 42)))
        #expect(!RoomId.isValid(String(repeating: "A", count: 42) + "+"))
        #expect(throws: IdentifierError.malformedRoomId) { try RoomId("short") }
    }

    @Test func peerIdShape() throws {
        #expect(PeerId.isValid(String(repeating: "0", count: 32)))
        #expect(!PeerId.isValid(String(repeating: "0", count: 31) + "A"))   // uppercase refused
        #expect(!PeerId.isValid(String(repeating: "0", count: 33)))
        #expect(throws: IdentifierError.malformedPeerId) { try PeerId("nope") }
        let p = PeerId.random()
        #expect(PeerId.isValid(p.hex))
        let (lo, hi) = (try PeerId("00000000000000000000000000000001"), try PeerId("0f1e2d3c4b5a69788796a5b4c3d2e1f0"))
        #expect(lo < hi)
    }

    @Test func peerIdCodable() throws {
        let p = try PeerId("0f1e2d3c4b5a69788796a5b4c3d2e1f0")
        let data = try JSONEncoder().encode([p])
        #expect(String(decoding: data, as: UTF8.self) == #"["0f1e2d3c4b5a69788796a5b4c3d2e1f0"]"#)
        let decoded = try JSONDecoder().decode([PeerId].self, from: data)
        #expect(decoded == [p])
        #expect(throws: (any Error).self) { try JSONDecoder().decode([PeerId].self, from: Data(#"["xyz"]"#.utf8)) }
    }
}

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/p2p-swift.git