import pytest
import logging
import requests
import socket
from db import TEST_PASSPHRASE
from multiprocessing import Process
from os import path
from zerodb import api


logging.basicConfig(level=logging.DEBUG)


def api_run(**kw):
    api.run(use_reloader=False, **kw)


@pytest.fixture(scope="module")
def api_server(request, db):
    # Get available TCP port
    sock = socket.socket()
    sock.bind(("localhost", 0))
    _, port = sock.getsockname()
    sock.close()

    server = Process(target=api_run, kwargs={
        "host": "localhost",
        "port": port,
        "data_models": path.join(path.dirname(__file__), "db.py")})

    @request.addfinalizer
    def fin():
        server.terminate()
        server.join()

    server.start()

    return {
            "api_uri": "http://localhost:%s" % port,
            "zeo_uri": db._storage._addr}


def test_connect(api_server):
    print api_server
    session = requests.Session()
    session.get(api_server["api_uri"], params={
        "username": "root",
        "passphrase": TEST_PASSPHRASE,
        "host": api_server["zeo_uri"]})

@@ -56,23 +56,37 @@
 ket%0A
+import time%0A
 from 
-db
+json
  import 
 TEST
@@ -81,31 +81,21 @@
  import 
-TEST_PASSPHRASE
+loads
 %0Afrom mu
@@ -143,16 +143,47 @@
 rt path%0A
+from db import TEST_PASSPHRASE%0A
 from zer
@@ -776,16 +776,36 @@
 .start()
+%0A    time.sleep(0.2)
 %0A%0A    re
@@ -942,29 +942,8 @@
 r):%0A
-    print api_server%0A
     
@@ -971,19 +971,41 @@
 ssion()%0A
+%0A
    
+ # Connect%0A    resp =
  session
@@ -1030,16 +1030,30 @@
 pi_uri%22%5D
+ + %22/_connect%22
 , params
@@ -1162,8 +1162,167 @@
 uri%22%5D%7D)%0A
+    assert loads(resp.text)%5B%22ok%22%5D == 1%0A%0A    # Disconnect%0A    resp = session.get(api_server%5B%22api_uri%22%5D + %22/_disconnect%22)%0A    assert loads(resp.text)%5B%22ok%22%5D == 1%0A

Test connect + disconnect