Skip to content

Commit

Permalink
Merge pull request #252 from Spirit-Balanceholder/MKP-Tests
Browse files Browse the repository at this point in the history
Basic CRUD tests
  • Loading branch information
Joannis authored Aug 25, 2020
2 parents 1ac3848 + b149ad8 commit a4b5f6c
Show file tree
Hide file tree
Showing 14 changed files with 131 additions and 172 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ Package.pins
Package.resolved
docs/generated
/.swiftpm
/.vscode
55 changes: 0 additions & 55 deletions GenerateXcodeproj.rb

This file was deleted.

7 changes: 4 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ let package = Package(
.testTarget(
name: "MongoKittenTests",
dependencies: ["MongoKitten"]),
.testTarget(
name: "MeowTests",
dependencies: ["Meow"]),
// TODO: Reimplement these tests
// .testTarget(
// name: "MeowTests",
// dependencies: ["Meow"]),
]
)
17 changes: 17 additions & 0 deletions Sources/MongoCore/Primitives/ConnectionSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -286,5 +286,22 @@ public struct ConnectionSettings: Equatable {

self.applicationName = queries["appname"]
self.dnsServer = queries["dnsServer"]

for key in [
"appname",
"dnsServer",
"sslVerify",
"maxConnections",
"connectTimeoutMS",
"socketTimeoutMS",
"tlsCAFile",
"authSource",
"ssl",
"tls",
"authMechanism",
] {
self.queryParameters[key] = nil

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public final class FindAndModifyBuilder {

/// Executes the command
public func execute() -> EventLoopFuture<FindAndModifyReply> {
return collection.pool.next(for: .basic).flatMap { connection in
return collection.pool.next(for: .writable).flatMap { connection in
connection.executeCodable(self.command,
namespace: self.collection.database.commandNamespace,
in: self.collection.transaction,
Expand Down
10 changes: 8 additions & 2 deletions Sources/MongoKitten/MongoDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class MongoDatabase {
public let pool: MongoConnectionPool

/// The collection to execute commands on
internal var commandNamespace: MongoNamespace {
public var commandNamespace: MongoNamespace {
return MongoNamespace(to: "$cmd", inDatabase: self.name)
}

Expand Down Expand Up @@ -296,7 +296,13 @@ extension EventLoopFuture where Value == MongoServerReply {
public func decodeReply<D: Decodable>(_ type: D.Type) -> EventLoopFuture<D> {
return flatMapThrowing { reply in
do {
return try D(reply: reply)
let ok = try OK(reply: reply)

if ok.isSuccessful {
return try D(reply: reply)
} else {
throw try MongoGenericErrorReply(reply: reply)
}
} catch {
throw try MongoGenericErrorReply(reply: reply)
}
Expand Down
2 changes: 2 additions & 0 deletions Sources/MongoKitten/MongoTransactionDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ internal struct OK: Decodable {

private let ok: Int

public var isSuccessful: Bool { ok == 1 }

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.ok = try container.decode(Int.self, forKey: .ok)
Expand Down
5 changes: 3 additions & 2 deletions Sources/MongoKittenCore/Commands/FindAndModify.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import MongoCore

/// Implements https://docs.mongodb.com/manual/reference/command/findAndModify/
public struct FindAndModifyCommand: Codable {
/// The collection against which to run the command.
public private(set) var findAndModify: String
Expand All @@ -19,7 +20,7 @@ public struct FindAndModifyCommand: Codable {
* `$project` and its alias `$unset`
* `$replaceRoot` and its alias `$replcaeWith`
*/
public var update: Document = []
public var update: Document?
/// When true, returns the modified document rather than the original. The findAndModify method ignores the new option for remove operations.
public var new: Bool?
/// A subset of fields to return. The `fields` document specifies an inclusion of a field with `1`, as in: `fields: { <field1>: 1, <field2>: 1, ... }`. [See projection](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#read-operations-projection).
Expand Down Expand Up @@ -54,7 +55,7 @@ public struct FindAndModifyCommand: Codable {
query: Document? = nil,
sort: Document? = nil,
remove: Bool = false,
update: Document = [],
update: Document? = nil,
new: Bool? = nil,
fields: Document? = nil,
upsert: Bool? = nil,
Expand Down
1 change: 0 additions & 1 deletion Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@
//

import XCTest
import MongoKittenTests

XCTMain([])
51 changes: 0 additions & 51 deletions Tests/MeowTests/KeyPathQueryTests.swift

This file was deleted.

7 changes: 4 additions & 3 deletions Tests/MongoCoreTests/ProtocolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,10 @@ class ProtocolTests: XCTestCase {
_ = try OpMessage(reading: &buffer, header: header)
}

func testOpMessageDeniesFirstUInt16Flags() throws {
XCTAssertNoThrow(try OpMessage(reading: &buffer, header: header))
}
// TODO: Reimplement this test
// func testOpMessageDeniesFirstUInt16Flags() throws {
// XCTAssertNoThrow(try OpMessage(reading: &buffer, header: header))
// }
}

extension ByteBuffer {
Expand Down
116 changes: 90 additions & 26 deletions Tests/MongoKittenTests/CRUDTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class CrudTests : XCTestCase {
}
}

let settings = try! ConnectionSettings("mongodb://localhost:27018/debug")
let settings = try! ConnectionSettings("mongodb://localhost/debug")

//let settings = ConnectionSettings(
// authentication: .auto(username: "admin", password: "Autimatisering1"),
Expand Down Expand Up @@ -84,7 +84,7 @@ class CrudTests : XCTestCase {
}

// is used repeatedly for all the tests that require dummy data
func testBackupBulkCreateDummyAccounts () throws -> [DummyAccount] {
func BackupBulkCreateDummyAccounts () throws -> [DummyAccount] {
let dummyAccounts = [
DummyAccount(name: "Test", password: "ing", age: 77),
DummyAccount(name: "To", password: "see", age: 10),
Expand Down Expand Up @@ -113,7 +113,7 @@ class CrudTests : XCTestCase {
func testBulkCreateDummyAccounts () throws -> [DummyAccount] {
var dummyAccounts: [DummyAccount] = []

for index in 0...4 {
for index in 0...2 {
for age in 1...100 {
dummyAccounts.append(DummyAccount(name: "Name-\(age + index * 100)", password: "Pass-\(age + index * 100)", age: age))
}
Expand All @@ -139,10 +139,12 @@ class CrudTests : XCTestCase {
}

func testReadDummyAccounts () throws {
try _ = testBulkCreateDummyAccounts()
if let dummy: DummyAccount = try readDummyAccount(name: "Name-182") {
XCTAssertEqual(dummy.password, "Pass-182")
XCTAssertEqual(dummy.age, 82 )
let originalAccounts = try testBulkCreateDummyAccounts()
let testDummyAccount = originalAccounts[Int.random(in: 0...originalAccounts.count)]

if let dummy: DummyAccount = try readDummyAccount(name: testDummyAccount.name) {
XCTAssertEqual(dummy.password, testDummyAccount.password)
XCTAssertEqual(dummy.age, testDummyAccount.age )
} else {
XCTFail("Retrieved a nil value")
}
Expand Down Expand Up @@ -280,7 +282,7 @@ class CrudTests : XCTestCase {
XCTAssertNotEqual(deleteReply.writeErrors?.isEmpty, false)

sleep(5)

XCTAssertNil(try readDummyAccount(name: testDummyAccount.name))
} else {
XCTFail()
Expand Down Expand Up @@ -412,26 +414,88 @@ class CrudTests : XCTestCase {
XCTAssertEqual(newAccount?.age, 111)
}

// func testFindOneAndDelete () throws {
// let originalAccounts = try testBulkCreateDummyAccounts()
// let schema: MongoCollection = mongo[DummyAccount.collectionName]
func testFindOneAndDelete () throws {
let originalAccounts = try testBulkCreateDummyAccounts()
let schema: MongoCollection = mongo[DummyAccount.collectionName]
let testDummyAccount = originalAccounts[Int.random(in: 0...originalAccounts.count)]

// let results = try schema.findOneAndDelete(where: ["age": 30]).execute().wait()
let results = try schema.findOneAndDelete(where: "name" == testDummyAccount.name).execute().wait()

// guard let resultValue = results.value else{
// XCTFail()
// return
// }

// let Account = try BSONDecoder().decode(DummyAccount.self, from: resultValue)
// XCTAssert(originalAccounts.contains(Account))
// schema.findOneAndDelete(where: ["age": 30]).execute().wait()
// }
XCTAssertEqual(results.ok, 1)

// TODO: Foreach future
// TODO: Change stream
// TODO: Find varieties
// TODO: Indexes
// TODO: Transactions
guard let resultValue = results.value else{
XCTFail()
return
}

let account = try BSONDecoder().decode(DummyAccount.self, from: resultValue)
XCTAssert(originalAccounts.contains(account))

if let _ = try schema.findOne("_id" == account._id).decode(DummyAccount.self).wait() {
XCTFail("still found the document that was supposed to be deleted")
}
}

func testFindOneAndReplace () throws {
let originalAccounts = try testBulkCreateDummyAccounts()
let schema: MongoCollection = mongo[DummyAccount.collectionName]
let tempDummyAccount = originalAccounts[Int.random(in: 0...originalAccounts.count)]

guard var testDummyAccount = try schema.findOne("name" == tempDummyAccount.name).decode(DummyAccount.self).wait() else {
XCTFail()
return
}

testDummyAccount.name = "repla"
testDummyAccount.password = "cement"
testDummyAccount.age = 111
let replacement = try BSONEncoder().encode(testDummyAccount)

let results = try schema.findOneAndReplace(where: "_id" == testDummyAccount._id, replacement: replacement).execute().wait()

XCTAssertEqual(results.ok, 1)

guard let replacedAccount = try schema.findOne("_id" == testDummyAccount._id).decode(DummyAccount.self).wait() else {
XCTFail()
return
}
XCTAssertEqual(replacedAccount, testDummyAccount)
}

func testFindOneAndUpdate () throws {
let originalAccounts = try testBulkCreateDummyAccounts()
let schema: MongoCollection = mongo[DummyAccount.collectionName]
let tempDummyAccount = originalAccounts[Int.random(in: 0...originalAccounts.count)]

guard let testDummyAccount = try schema.findOne("name" == tempDummyAccount.name).decode(DummyAccount.self).wait() else {
XCTFail()
return
}

let results = try schema.findOneAndUpdate(where: "_id" == testDummyAccount._id, to: ["$set": ["name": "updated"]]).execute().wait()

XCTAssertEqual(results.ok, 1)

guard let updatedAccount = try schema.findOne("_id" == testDummyAccount._id).decode(DummyAccount.self).wait() else {
XCTFail()
return
}
XCTAssertEqual(updatedAccount.name, "updated")
}

func testIndexes () throws {
_ = try testBulkCreateDummyAccounts()
let schema: MongoCollection = mongo[DummyAccount.collectionName]

try schema.createIndex(named: "nameIndex", keys: ["name": -1]).wait()
let result = try schema.listIndexes().wait().allResults().wait()

XCTAssertEqual(result.count, 2)
XCTAssertEqual(result[0].name, "_id_")
XCTAssertEqual(result[1].name, "nameIndex")
}

// TODO ON ICE: Foreach future
// TODO ON ICE: Change stream
// TODO: Transactions
}
Loading

0 comments on commit a4b5f6c

Please sign in to comment.