Skip to content

Commit d6a3d90

Browse files
committed
make tests self-cleanup
1 parent ec852e0 commit d6a3d90

File tree

7 files changed

+31
-63
lines changed

7 files changed

+31
-63
lines changed

Sources/PostgreSQL/Connection/PostgreSQLConnection+Authenticate.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ extension PostgreSQLConnection {
88
"user": username,
99
"database": database ?? username
1010
]))]) { message in
11-
print("👈 \(message)")
1211
switch message {
1312
case .authenticationRequest(let a):
1413
authRequest = a
@@ -53,7 +52,6 @@ extension PostgreSQLConnection {
5352
}
5453

5554
return self.queue.enqueue(input) { message in
56-
print("👈 \(message)")
5755
switch message {
5856
case .error(let error): throw PostgreSQLError.errorResponse(error)
5957
case .readyForQuery: return true

Sources/PostgreSQL/Connection/PostgreSQLConnection+Query.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,6 @@ extension PostgreSQLConnection {
9494

9595
/// Non-operation bounded query.
9696
private func _query(_ string: String, _ parameters: [PostgreSQLDataConvertible] = [], resultFormat: PostgreSQLResultFormat, onRow: @escaping ([PostgreSQLColumn: PostgreSQLData]) throws -> ()) throws -> Future<Void> {
97-
print(string)
98-
print(parameters)
9997
let parameters = try parameters.map { try $0.convertToPostgreSQLData() }
10098
logger?.record(query: string, values: parameters.map { $0.description })
10199

Sources/PostgreSQL/Connection/PostgreSQLConnection.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ public final class PostgreSQLConnection: DatabaseConnection, BasicWorker {
8585
if let e = error { throw e }
8686
return true
8787
case .error(let e): error = PostgreSQLError.errorResponse(e)
88-
case .notice(let n): print(n)
88+
case .notice(let n): debugOnly { WARNING("\(n)") }
8989
default: try onResponse(message)
9090
}
9191
return false // request until ready for query

Sources/PostgreSQL/Data/PostgreSQLData+String.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ struct PostgreSQLNumericMetadata {
9595
var dscale: Int16
9696
}
9797

98+
9899
extension Data {
99100
/// Convert the row's data into a string, throwing if invalid encoding.
100101
internal func makeString(encoding: String.Encoding = .utf8) throws -> String {

Sources/PostgreSQL/Utilities/PostgreSQLError.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ public struct PostgreSQLError: Debuggable {
4848
}
4949
}
5050

51+
/// Only includes the supplied closure in non-release builds.
52+
internal func debugOnly(_ body: () -> Void) {
53+
assert({ body(); return true }())
54+
}
55+
56+
/// Logs a runtime warning.
57+
internal func WARNING(_ string: @autoclosure () -> String) {
58+
print("[WARNING] [PostgreSQL] \(string())")
59+
}
60+
5161
func VERBOSE(_ string: @autoclosure () -> (String)) {
5262
#if VERBOSE
5363
print("[VERBOSE] [PostgreSQL] \(string())")

Sources/PostgreSQL/Utilities/Utilities.swift

Lines changed: 9 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -67,33 +67,8 @@ extension ByteBuffer {
6767
}
6868
}
6969

70-
extension UnsafeBufferPointer {
71-
public var unsafeBaseAddress: UnsafePointer<Element> {
72-
guard let baseAddress = self.baseAddress else {
73-
fatalError("Unexpected nil baseAddress for \(self)")
74-
}
75-
return baseAddress
76-
}
77-
}
78-
79-
extension UnsafeRawBufferPointer {
80-
public var unsafeBaseAddress: UnsafeRawPointer {
81-
guard let baseAddress = self.baseAddress else {
82-
fatalError("Unexpected nil baseAddress for \(self)")
83-
}
84-
return baseAddress
85-
}
86-
}
87-
8870
extension Data {
89-
internal mutating func unsafePopFirst() -> Byte {
90-
guard let byte = popFirst() else {
91-
fatalError("Unexpected end of data")
92-
}
93-
return byte
94-
}
95-
96-
internal mutating func skip(_ n: Int) {
71+
mutating func skip(_ n: Int) {
9772
guard n < count else {
9873
self = Data()
9974
return
@@ -103,38 +78,33 @@ extension Data {
10378
assert(first != nil)
10479
}
10580
}
106-
107-
internal mutating func skip<T>(sizeOf: T.Type) {
81+
82+
mutating func skip<T>(sizeOf: T.Type) {
10883
skip(MemoryLayout<T>.size)
10984
}
110-
85+
11186
/// Casts data to a supplied type.
112-
internal mutating func extract<T>(_ type: T.Type = T.self) -> T {
87+
mutating func extract<T>(_ type: T.Type = T.self) -> T {
11388
assert(MemoryLayout<T>.size <= count, "Insufficient data to exctract: \(T.self)")
11489
defer { skip(sizeOf: T.self) }
11590
return withUnsafeBytes { (pointer: UnsafePointer<T>) -> T in
11691
return pointer.pointee
11792
}
11893
}
119-
120-
internal mutating func extract(count: Int) -> Data {
94+
95+
mutating func extract(count: Int) -> Data {
12196
assert(self.count >= count, "Insufficient data to extract bytes.")
12297
defer { skip(count) }
12398
return withUnsafeBytes({ (pointer: UnsafePointer<UInt8>) -> Data in
12499
let buffer = UnsafeBufferPointer(start: pointer, count: count)
125100
return Data(buffer)
126101
})
127102
}
128-
}
129-
130-
131-
extension Data {
103+
132104
/// Casts data to a supplied type.
133-
internal func unsafeCast<T>(to type: T.Type = T.self) -> T {
105+
func unsafeCast<T>(to type: T.Type = T.self) -> T {
134106
return withUnsafeBytes { (pointer: UnsafePointer<T>) -> T in
135107
return pointer.pointee
136108
}
137109
}
138-
139-
140110
}

Tests/PostgreSQLTests/PostgreSQLConnectionTests.swift

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,8 @@ class PostgreSQLConnectionTests: XCTestCase {
7878
-- "uuid" uuid
7979
);
8080
"""
81-
_ = try client.query("drop table if exists kitchen_sink;").wait()
8281
let createResult = try client.query(createQuery).wait()
82+
defer { _ = try? client.simpleQuery(.drop("kitchen_sink")).wait() }
8383
XCTAssertEqual(createResult.count, 0)
8484

8585
let insertQuery = """
@@ -172,8 +172,8 @@ class PostgreSQLConnectionTests: XCTestCase {
172172
-- "bit" bit(16),
173173
);
174174
"""
175-
_ = try client.query("drop table if exists kitchen_sink;").wait()
176175
let createResult = try client.query(createQuery).wait()
176+
defer { _ = try? client.simpleQuery(.drop("kitchen_sink")).wait() }
177177
XCTAssertEqual(createResult.count, 0)
178178

179179
let insertQuery = """
@@ -263,8 +263,8 @@ class PostgreSQLConnectionTests: XCTestCase {
263263
}
264264

265265
let client = try PostgreSQLConnection.makeTest(transport: .cleartext)
266-
_ = try client.query("drop table if exists foo;").wait()
267266
let createResult = try client.query("create table foo (id integer, dict jsonb);").wait()
267+
defer { _ = try? client.simpleQuery(.drop("foo")).wait() }
268268
XCTAssertEqual(createResult.count, 0)
269269
let insertResult = try client.query("insert into foo values ($1, $2);", [
270270
Int32(1), Hello(message: "hello, world")
@@ -283,9 +283,9 @@ class PostgreSQLConnectionTests: XCTestCase {
283283

284284
func testNull() throws {
285285
let client = try PostgreSQLConnection.makeTest(transport: .cleartext)
286-
_ = try client.query("drop table if exists nulltest;").wait()
287286
let createResult = try client.query("create table nulltest (i integer not null, d timestamp);").wait()
288287
XCTAssertEqual(createResult.count, 0)
288+
defer { _ = try? client.simpleQuery(.drop("nulltest")).wait() }
289289
let insertResult = try client.query("insert into nulltest (i, d) VALUES ($1, $2)", [
290290
PostgreSQLData(.int2, binary: Data([0x00, 0x01])),
291291
PostgreSQLData(null: .timestamp),
@@ -298,32 +298,24 @@ class PostgreSQLConnectionTests: XCTestCase {
298298
func testGH24() throws {
299299
/// PREPARE
300300
let client = try PostgreSQLConnection.makeTest(transport: .cleartext)
301-
_ = try client.query("""
302-
DROP TABLE IF EXISTS "acronym+category"
303-
""").wait()
304-
_ = try client.query("""
305-
DROP TABLE IF EXISTS "categories"
306-
""").wait()
307-
_ = try client.query("""
308-
DROP TABLE IF EXISTS "acronyms"
309-
""").wait()
310-
_ = try client.query("""
311-
DROP TABLE IF EXISTS "users"
312-
""").wait()
313-
301+
314302
/// CREATE
315303
let _ = try client.query("""
316304
CREATE TABLE "users" ("id" UUID PRIMARY KEY, "name" TEXT NOT NULL, "username" TEXT NOT NULL)
317305
""").wait()
306+
defer { _ = try! client.simpleQuery(.drop("users")).wait() }
318307
let _ = try client.query("""
319308
CREATE TABLE "acronyms" ("id" BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "short" TEXT NOT NULL, "long" TEXT NOT NULL, "userID" UUID NOT NULL, FOREIGN KEY ("userID") REFERENCES "users" ("id"), FOREIGN KEY ("userID") REFERENCES "users" ("id"))
320309
""").wait()
310+
defer { _ = try! client.simpleQuery(.drop("acronyms")).wait() }
321311
let _ = try client.query("""
322312
CREATE TABLE "categories" ("id" BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "name" TEXT NOT NULL)
323313
""").wait()
314+
defer { _ = try! client.simpleQuery(.drop("categories")).wait() }
324315
let _ = try client.query("""
325316
CREATE TABLE "acronym+category" ("id" UUID PRIMARY KEY, "acronymID" BIGINT NOT NULL, "categoryID" BIGINT NOT NULL, FOREIGN KEY ("acronymID") REFERENCES "acronyms" ("id"), FOREIGN KEY ("categoryID") REFERENCES "categories" ("id"), FOREIGN KEY ("acronymID") REFERENCES "acronyms" ("id"), FOREIGN KEY ("categoryID") REFERENCES "categories" ("id"))
326317
""").wait()
318+
defer { _ = try! client.simpleQuery(.drop("acronym+category")).wait() }
327319

328320
/// INSERT
329321
let userUUID = UUID()
@@ -448,8 +440,8 @@ class PostgreSQLConnectionTests: XCTestCase {
448440
}
449441

450442
let connection = try PostgreSQLConnection.makeTest(transport: .cleartext)
451-
_ = try connection.simpleQuery("DROP TABLE IF EXISTS apps").wait()
452443
_ = try connection.simpleQuery("CREATE TABLE apps (id INT, platform TEXT, identifier TEXT)").wait()
444+
defer { _ = try? connection.simpleQuery(.drop("apps")).wait() }
453445
_ = try connection.simpleQuery("INSERT INTO apps VALUES (1, 'a', 'b')").wait()
454446
_ = try connection.simpleQuery("INSERT INTO apps VALUES (2, 'c', 'd')").wait()
455447
_ = try connection.simpleQuery("INSERT INTO apps VALUES (3, 'a', 'd')").wait()
@@ -468,7 +460,6 @@ class PostgreSQLConnectionTests: XCTestCase {
468460

469461
func testDML() throws {
470462
let conn = try PostgreSQLConnection.makeTest(transport: .cleartext)
471-
_ = try conn.simpleQuery(.drop(ifExists: true, "users")).wait()
472463
_ = try conn.simpleQuery(.create("users", columns: [
473464
.column("id", .init(.int8, primaryKey: true, generatedIdentity: true)),
474465
.column("name", .text)

0 commit comments

Comments
 (0)