 
 import Foundation
 import XCTest
+import Shared
 import Storage
 
+
+// TODO: rewrite this test to not use BrowserTable. It used to use HistoryTable…
 class TestSwiftData: XCTestCase {
     var swiftData: SwiftData!
+    var table: BrowserTable!
+    var urlCounter = 1
 
     override func setUp() {
         let files = MockFiles()
         files.remove("testSwiftData.db")
         let testDB = files.getAndEnsureDirectory()!.stringByAppendingPathComponent("testSwiftData.db")
         swiftData = SwiftData(filename: testDB)
+        table = BrowserTable()
 
         // Ensure static flags match expected values.
         XCTAssert(SwiftData.ReuseConnections, "Reusing database connections")
         XCTAssert(SwiftData.EnableWAL, "WAL enabled")
+
+        swiftData.withConnection(SwiftData.Flags.ReadWriteCreate) { db in
+            let f = FaviconsTable<Favicon>()
+            f.create(db, version: 1)    // Because BrowserTable needs it.
+            self.table.create(db, version: 1)
+            var err: NSError?
+            return nil
+        }
+
+        XCTAssertNil(addSite(table, url: "http://url0", title: "title0"), "Added url0.")
     }
 
     override func tearDown() {

        SwiftData.EnableWAL = true
    }

    func testNoWALOrConnectionReuse() {
        SwiftData.ReuseConnections = false
        SwiftData.EnableWAL = false
        var error = writeDuringRead()
        XCTAssertEqual(error!.code, 5, "Got 'database is locked' error")
    }

    func testNoConnectionReuse() {
        SwiftData.ReuseConnections = false
        var error = writeDuringRead()
        XCTAssertEqual(error!.code, 8, "Got 'attempt to write to read-only database' error")
    }

    func testNoWAL() {
        SwiftData.EnableWAL = false
        var error = writeDuringRead()
        XCTAssertNil(error, "Insertion succeeded")
    }

    func testDefaultSettings() {
        var error = writeDuringRead()
        XCTAssertNil(error, "Insertion succeeded")
    }

    func testBusyTimeout() {
        SwiftData.ReuseConnections = false
        SwiftData.EnableWAL = false
        var error = writeDuringRead(closeTimeout: 1)
        XCTAssertNil(error, "Insertion succeeded")
    }

    func testFilledCursor() {
        SwiftData.ReuseConnections = false
        SwiftData.EnableWAL = false
        XCTAssertNil(writeDuringRead(safeQuery: true), "Insertion succeeded")
    }

    private func writeDuringRead(safeQuery: Bool = false, closeTimeout: UInt64? = nil) -> NSError? {

        // Query the database and hold the cursor.
        var c: Cursor<SDRow>!
        var error = swiftData.withConnection(SwiftData.Flags.ReadOnly) { db in
            if safeQuery {
                c = db.executeQuery("SELECT * FROM history", factory: { $0 })
            } else {
                c = db.executeQueryUnsafe("SELECT * FROM history", factory: { $0 })
            }
            return nil
        }
