from nose.tools import *
from nose.tools import assert_raises
from testutil.helpers import *

import io
import os
import sys
import time

import nilmdb.server
import webtest

testdb = "tests/testdb"

# Test WSGI interface

class TestWSGI(object):
    def test_wsgi(self):

        # Bad database gives debug info
        app = webtest.TestApp(nilmdb.server.wsgi_application("/dev/null", "/"))
        resp = app.get('/', expect_errors=True)
        eq_(resp.status_int, 500)
        eq_(resp.content_type, "text/plain")
        body = resp.body.decode('utf-8')
        in_("Initializing database at path '/dev/null' failed", body)
        in_("Not a directory: b'/dev/null/data'", body)
        in_("Running as: uid=", body)
        in_("Environment:", body)

        # Good database works fine
        app = webtest.TestApp(nilmdb.server.wsgi_application(testdb, "/nilmdb"))
        resp = app.get('/version', expect_errors=True)
        eq_(resp.status_int, 404)
        resp = app.get('/nilmdb/version')
        eq_(resp.json, nilmdb.__version__)
