Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update coverage utils #234

Merged
merged 12 commits into from
Dec 2, 2024
17 changes: 9 additions & 8 deletions Networking/Tests/NetworkingTests/PeerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,12 @@ struct PeerTests {
presistentStreamHandler: MockPresentStreamHandler(),
ephemeralStreamHandler: MockEphemeralStreamHandler(),
serverSettings: .defaultSettings,
clientSettings: .defaultSettings
clientSettings: .defaultSettings,
peerSettings: PeerSettings(maxBuilderConnections: 3)
)
)
// Create 30 peer nodes
for _ in 0 ..< 30 {
// Create 5 peer nodes
for _ in 0 ..< 5 {
let handler = MockPresentStreamHandler()
handlers.append(handler)
let peer = try Peer(
Expand All @@ -160,20 +161,20 @@ struct PeerTests {
}

// Make some connections
for i in 0 ..< 30 {
for i in 0 ..< 5 {
let peer = peers[i]
let con = try peer.connect(to: centerPeer.listenAddress(), role: .builder)
try await con.ready()
}
// Simulate close connections 5~8s
try? await Task.sleep(for: .milliseconds(8000))
centerPeer.broadcast(kind: .uniqueA, message: .init(kind: .uniqueA, data: Data("connection rotation strategy".utf8)))
// Simulate close connections 1~3s
try? await Task.sleep(for: .milliseconds(1000))
centerPeer.broadcast(kind: .uniqueA, message: .init(kind: .uniqueA, data: Data("connection rotation strategy".utf8)))
try? await Task.sleep(for: .milliseconds(100))
var receivedCount = 0
for handler in handlers {
receivedCount += await handler.receivedData.count
}
#expect(receivedCount == PeerSettings.defaultSettings.maxBuilderConnections)
#expect(receivedCount == 3)
}

@Test
Expand Down
7 changes: 1 addition & 6 deletions Utils/Sources/Utils/JSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import Foundation

public indirect enum JSON: Codable, Equatable {
public indirect enum JSON: Codable, Equatable, Sendable {
case dictionary([String: JSON])
case array([JSON])
case string(String)
Expand Down Expand Up @@ -155,11 +155,6 @@ extension JSON {
stringValue = value.description
}

init(_ value: String) {
intValue = nil
stringValue = value
}

init?(intValue: Int) {
self.init(intValue)
}
Expand Down
1 change: 0 additions & 1 deletion Utils/Sources/Utils/Merklization/MMR.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Codec

// TODO: add tests
// Merkle Mountain Range
public struct MMR: Sendable, Equatable, Codable {
public var peaks: [Data32?]
Expand Down
1 change: 0 additions & 1 deletion Utils/Sources/Utils/Merklization/Merklization.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Foundation

// TODO: add tests
public enum Merklization {
// roundup of half
private static func half(_ i: Int) -> Int {
Expand Down
3 changes: 1 addition & 2 deletions Utils/Sources/Utils/SortedContainer/SortedUniqueArray.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// TODO: add tests
public struct SortedUniqueArray<T: Comparable>: SortedContainer {
public private(set) var array: [T]

Expand Down Expand Up @@ -35,7 +34,7 @@ public struct SortedUniqueArray<T: Comparable>: SortedContainer {
var begin = 0
for element in other.array {
let idx = insertIndex(element, begin: begin)
if idx > array.count || array[idx] != element {
if idx == array.count || array[idx] != element {
array.insert(element, at: idx)
}
begin = idx + 1
Expand Down
40 changes: 20 additions & 20 deletions Utils/Sources/Utils/debugCheck.swift
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
import Foundation

public enum AssertError: Error {
case assertionFailed
public enum DebugCheckError: Error {
case assertionFailed(String, file: StaticString, line: UInt)
case unexpectedError(Error, file: StaticString, line: UInt)
}

public func debugCheck(
_ condition: @autoclosure () throws -> Bool, file: StaticString = #file, line: UInt = #line
) {
) throws {
#if DEBUG_ASSERT
let res = Result { try condition() }
switch res {
case let .success(res):
if !res {
fatalError(file: file, line: line)
let result = Result { try condition() }
switch result {
case let .success(isValid):
if !isValid {
throw DebugCheckError.assertionFailed("Assertion failed", file: file, line: line)
}
case let .failure(err):
fatalError("\(err)", file: file, line: line)
case let .failure(error):
throw DebugCheckError.unexpectedError(error, file: file, line: line)

Check warning on line 19 in Utils/Sources/Utils/debugCheck.swift

View check run for this annotation

Codecov / codecov/patch

Utils/Sources/Utils/debugCheck.swift#L19

Added line #L19 was not covered by tests
}
#endif
}

public func debugCheck(
_ condition: @autoclosure () async throws -> Bool, file: StaticString = #file,
line: UInt = #line
) async {
_ condition: @autoclosure () async throws -> Bool, file: StaticString = #file, line: UInt = #line
) async throws {
#if DEBUG_ASSERT
let res = await Result { try await condition() }
switch res {
case let .success(res):
if !res {
fatalError(file: file, line: line)
let result = await Result { try await condition() }
switch result {
case let .success(isValid):
if !isValid {
throw DebugCheckError.assertionFailed("Assertion failed", file: file, line: line)
}
case let .failure(err):
fatalError("\(err)", file: file, line: line)
case let .failure(error):
throw DebugCheckError.unexpectedError(error, file: file, line: line)

Check warning on line 35 in Utils/Sources/Utils/debugCheck.swift

View check run for this annotation

Codecov / codecov/patch

Utils/Sources/Utils/debugCheck.swift#L35

Added line #L35 was not covered by tests
}
#endif
}
62 changes: 61 additions & 1 deletion Utils/Tests/UtilsTests/ConfigLimitedSizeArrayTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import Testing

@testable import Utils

struct MinLengthNegated: ReadInt {
typealias TConfig = Int

static func read(config _: Int) -> Int {
-1
}
}

struct MinLength3: ReadInt {
typealias TConfig = Int

Expand All @@ -20,13 +28,24 @@ struct MaxLength5: ReadInt {
}
}

struct MaxLength8: ReadInt {
typealias TConfig = Int

static func read(config _: Int) -> Int {
8
}
}

struct ConfigLimitedSizeArrayTests {
@Test func initWithDefaultValue() throws {
let config = 0
let defaultValue = 1
let array = try ConfigLimitedSizeArray<Int, MinLength3, MaxLength5>(config: config, defaultValue: defaultValue)
var array = try ConfigLimitedSizeArray<Int, MinLength3, MaxLength5>(config: config, defaultValue: defaultValue)
#expect(array.array == [1, 1, 1])
#expect(array.count == 3)
#expect(array[0] == 1)
array[0] = 0
#expect(array[0] != 1)
}

@Test func initWithArrayWithinBounds() throws {
Expand Down Expand Up @@ -141,4 +160,45 @@ struct ConfigLimitedSizeArrayTests {
let decoded = try JamDecoder.decode(ConfigLimitedSizeArray<Int, MinLength3, MaxLength5>.self, from: encoded, withConfig: config)
#expect(decoded == array)
}

@Test func throwLength() throws {
#expect(throws: Error.self) {
_ = try ConfigLimitedSizeArray<Int, MinLengthNegated, MaxLength5>(config: 0, array: [1, 2, 3])
}
#expect(throws: Error.self) {
_ = try ConfigLimitedSizeArray<Int, MaxLength5, MinLength3>(config: 0, array: [1, 2, 3])
}
}

@Test func randomAccessCollection() throws {
let value = try ConfigLimitedSizeArray<Int, MinLength3, MaxLength8>(config: 0, array: [1, 2, 3, 4, 5, 6, 7, 8])
#expect(value.startIndex == 0)
#expect(value.endIndex == 8)

var idx = value.startIndex
value.formIndex(after: &idx)
#expect(idx == 1)

value.formIndex(before: &idx)
#expect(idx == 0)

let dist = value.distance(from: 0, to: 7)
#expect(dist == 7)

let indexForward = value.index(0, offsetBy: 3)
#expect(indexForward == 3)

let indexWithinLimit = value.index(0, offsetBy: 3, limitedBy: 5)
#expect(indexWithinLimit == 3)
#expect(value.index(after: indexWithinLimit!) == 4)
#expect(value.index(before: indexWithinLimit!) == 2)
#expect(value.index(from: indexWithinLimit!) == 3)
}

@Test func description() throws {
let config = 0
let array = try ConfigLimitedSizeArray<Int, MinLength3, MaxLength5>(config: config, array: [1, 2, 3, 4, 5])
#expect(array.description == "[1, 2, 3, 4, 5]")
#expect(array.debugDescription == "ConfigLimitedSizeArray<Int, 3, 5>([1, 2, 3, 4, 5])")
}
}
40 changes: 40 additions & 0 deletions Utils/Tests/UtilsTests/ConfigSizeBitStringTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,44 @@ struct ConfigSizeBitStringTests {
value[19] = true
#expect(value == value3)
}

@Test func encodedSizeTests() throws {
let data = Data([0b1011_0101, 0b1100_0101, 0b0000_0110])
let length = 20
let value = try ConfigSizeBitString<ReadIntValue>(config: length, data: data)

#expect(value.encodedSize == data.count)
#expect(ConfigSizeBitString<ReadIntValue>.encodeedSizeHint == nil)
}

@Test func randomAccessCollection() throws {
var value = ConfigSizeBitString<ReadIntValue>(config: 8)
let result = value.withPtr { ptr in
ptr.reduce(0, +)
}
#expect(result == 0)

#expect(value.startIndex == 0)
#expect(value.endIndex == 8)

value[7] = true
let collected = Array(value)
#expect(collected == [false, false, false, false, false, false, false, true])

var idx = value.startIndex
value.formIndex(after: &idx)
#expect(idx == 1)

value.formIndex(before: &idx)
#expect(idx == 0)

let dist = value.distance(from: 0, to: 7)
#expect(dist == 7)

let indexForward = value.index(0, offsetBy: 3)
#expect(indexForward == 3)

let indexWithinLimit = value.index(0, offsetBy: 3, limitedBy: 5)
#expect(indexWithinLimit == 3)
}
}
22 changes: 22 additions & 0 deletions Utils/Tests/UtilsTests/ConstValueTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import Testing

@testable import Utils

struct ConstIntTests {
@Test
func constIntValues() {
#expect(ConstInt0.value == 0)
#expect(ConstInt1.value == 1)
#expect(ConstInt2.value == 2)
#expect(ConstInt3.value == 3)
#expect(ConstIntMax.value == Int.max)
#expect(ConstInt32.value == 32)
#expect(ConstInt48.value == 48)
#expect(ConstInt64.value == 64)
#expect(ConstUInt96.value == 96)
#expect(ConstUInt128.value == 128)
#expect(ConstUInt144.value == 144)
#expect(ConstUInt384.value == 384)
#expect(ConstUInt784.value == 784)
}
}
33 changes: 33 additions & 0 deletions Utils/Tests/UtilsTests/DebugCheckTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Foundation
import Testing

@testable import Utils

struct DebugCheckTests {
func awaitThrow(_ expression: () async throws -> some Any) async throws -> Bool {
_ = try await expression()
return true
}

func doesThrow(_ expression: () throws -> some Any) throws -> Bool {
_ = try expression()
return true
}

@Test
func testDebugCheck() async throws {
try #expect(doesThrow {
try debugCheck(1 + 1 == 2)
} == true)
#expect(throws: DebugCheckError.self) {
try debugCheck(1 + 1 == 3)
}
try await #expect(awaitThrow {
try await debugCheck(1 + 1 == 2)
} == true)

await #expect(throws: DebugCheckError.self) {
try await debugCheck(1 + 1 == 3)
}
}
}
Loading