예제 #1
0
    def test_login(self):

        clerk = MockClerk(SCHEMA)
        clerk.store(Author(username='******', password='******'))
        sess = Sess(InMemorySessPool(), RequestBuilder().build(), Response())
        aa = AuthorAuth(sess, clerk)

        assert aa.fetch(1).username == 'fred'
        aa.login(1)
        assert aa.user.username == 'fred'

        assert aa.validate({"username": "******", "password": "******"})
        assert not aa.validate({"username": "******", "password": "******"})
예제 #2
0
 def test_redirectToQuerystring(self):
     eng = Engine("import weblib; raise weblib.Redirect('?x=1')",
                  request=RequestBuilder().build(path="test.app"))
     eng.run()
     assert ('Location', 'test.app?x=1') in eng.response.headers
예제 #3
0
 def setUp(self):
     self.builder = RequestBuilder()
예제 #4
0
class EngineTest(unittest.TestCase):
    def setUp(self):
        self.builder = RequestBuilder()

    def test_globals(self):
        myscript = trim("""
            import weblib
            assert isinstance(REQ, weblib.Request)
            assert isinstance(RES, weblib.Response)
            assert isinstance(ENG, weblib.Engine)
            """)
        eng = Engine(script=myscript)
        eng.run()
        assert eng.result == Engine.SUCCESS, eng.error

    def test_print(self):
        import sys, StringIO
        eng = Engine(script=trim("""
            import weblib
            print >> RES, 'this should show'
            print 'this should not'
            """))
        tempout, sys.stdout = sys.stdout, StringIO.StringIO()
        eng.run()
        sys.stdout, tempout = tempout, sys.stdout
        assert eng.response.buffer == "this should show\n", \
               "doesn't grab prints after import weblib!"
        assert tempout.getvalue() == "this should not\n", \
               "doesn't print rest to stdout"

    def test_exit(self):
        try:
            eng = Engine(script="raise SystemExit")
            eng.run()
            gotError = 0
        except SystemExit:
            gotError = 1
        assert not gotError, "Engine doesn't trap sys.exit()!"

    def test_runtwice(self):
        eng = Engine(script='print >> RES, "hello"')
        eng.run()
        try:
            eng.run()
            gotError = 0
        except:
            gotError = 1
        assert gotError, "you should not be able to use engine twice!"

    def test_on_exit(self):
        """
        engine.do_on_exit(XXX) should remember XXX and call it at end of page.
        """
        def nothing():
            pass

        eng = Engine(script="")
        assert len(eng._exitstuff)==0, \
               "exitstuff not empty by default"

        eng.do_on_exit(nothing)
        assert len(eng._exitstuff)==1, \
               "do_on_exit doesn't add to exitstuff"

        eng._exitstuff = []

        eng = Engine(script=trim("""
            # underscores on next line are just for emacs.. (trim strips them)
        ___ def cleanup():   
                print >> RES, 'wokka wokka wokka'
            ENG.do_on_exit(cleanup)
            """))
        eng.execute(eng.script)
        assert len(eng._exitstuff) == 1, \
               "didn't register exit function: %s" % str(eng._exitstuff)
        eng._exit()
        assert eng.response.buffer=='wokka wokka wokka\n', \
               "got wrong response: %s" % eng.response.buffer

    def test_result(self):
        eng = Engine(script='1+1')
        assert eng.result == None, \
               "engine.result doesn't default to None"

        eng.run()
        assert eng.result == eng.SUCCESS, \
               "engine.result doesn't return SUCCESS on success"

        eng = Engine(script="print 'cat' + 5")
        eng.run()
        assert eng.result == eng.EXCEPTION, \
               "engine.result doesn't return EXCEPTION on error."

        eng = Engine("assert 1==0, 'math is working.. :('")
        eng.run()
        assert eng.result == eng.FAILURE, \
               "engine.result doesn't return FAILURE on assertion failure."

        eng = Engine("import weblib; raise weblib.Redirect, 'url?query'")
        eng.run()
        assert eng.result == eng.REDIRECT, \
               "engine.result doesn't return REDIRECT on redirect."

    ## CGI-SPECIFIC (needs to move) ############################

    ## @TODO: this is really a test of Request
    def test_request(self):
        os.environ["QUERY_STRING"] = "enginetest"

        engine = Engine(script="")
        assert engine.request.query.string=="enginetest", \
               "engine has wrong default request"
        del engine

        req = self.builder.build(querystring="e=mc2&this=a+test")
        engine = Engine("pass", request=req)
        assert engine.request.query.string=="e=mc2&this=a+test", \
               "engine has wrong passed-in request:" + \
               engine.request.query.string

    #@TODO: move to testRequest
    def test_form(self):
        weblib.MYFORM = {"a": "bcd"}
        try:
            myscript = trim("""
                import weblib
                assert REQ.form is weblib.MYFORM, \
                    'request uses wrong form'
                """)
            req = self.builder.build(form=weblib.MYFORM)
            eng = weblib.Engine(request=req, script=myscript)
            eng.run()
            assert eng.result == eng.SUCCESS, eng.result
        finally:
            del weblib.MYFORM

    def test_hadProblem(self):
        e = Engine(script="x = 1")
        e.run()
        assert not e.hadProblem()
        e = Engine(script="raise hell")
        e.run()
        assert e.hadProblem()
        e = Engine(script="assert 0")
        e.run()
        assert e.hadProblem()

    def test__main__(self):
        e = Engine(script=trim("""
            if __name__=='__main__':
               print >> RES, 'sup?'
            """))
        e.run()
        assert e.response.buffer == "sup?\n"

    # engine needs to set pathinfo so that response
    # can redirect to ?lsakdfjlsdkafj
    # scripts should not pull it out of os.environ
    # because that won't work for twisted
    # instead, the engine for each service should
    # do this. (twisted, cgi, etc...)
    def test_pathInfo(self):
        eng = Engine(script=open("spec/pathinfo.app"))
        assert eng.request.pathInfo == "spec/pathinfo.app", \
               "Engine doesn't set .pathInfo correctly for open()ed scripts."

    def test_redirectToQuerystring(self):
        eng = Engine("import weblib; raise weblib.Redirect('?x=1')",
                     request=RequestBuilder().build(path="test.app"))
        eng.run()
        assert ('Location', 'test.app?x=1') in eng.response.headers
예제 #5
0
 def setUp(self):
     self.builder = RequestBuilder()
예제 #6
0
class RequestTest(unittest.TestCase):

    def setUp(self):
        self.builder = RequestBuilder()

    def test_getitem(self):
        req = self.builder.build(querystring="a=1&aa=2&aa=3&z1=querystring",
                      form={"b":"2", "z1":"form", "z2":"form"},
                      cookie={"c":"3", "z1":"cookie", "z2":"cookie",
                              "z3":"cookie"})
       
        assert req["a"] == "1", \
               "getitem scews up on querystring"
        assert req["aa"] == ("2", "3"), \
               "getitem screws up on multiple values"
        assert req["b"] == "2", \
               "getitem screws up on forms"
        assert req["c"] == "3", \
               "getitem screws up on cookies"

        # it should fetch things in this order:
        assert req["z1"][0] == "querystring", \
               "getitem goes in wrong order (z1)"
        assert req["z2"][0] == "form", \
               "getitem goes in wrong order (z2)"
        assert req["z3"] == "cookie", \
               "getitem goes in wrong order (z3)"

    def test_keys(self):
        req = self.builder.build(querystring="querystring=1",
                      form={"form":"1"},
                      cookie={"cookie":"1"})
        keys = req.keys()
        keys.sort()
        
        assert keys== ['cookie','form','querystring'], \
               "request.keys() doesn't work."


    def test_get(self):
        req = self.builder.build(querystring="a=1")
        assert req.get("a") == "1", \
               "get breaks for valid keys"
        assert req.get("b") is None, \
               "get breaks for non-present keys"


    def test_encoding(self):
        req = self.builder.build(content="a=<>")
        assert req.form["a"] == "<>", \
               "doesn't handle <> correctly (got %s)" \
               % repr(req.form["a"])


    def test_content(self):
        req = self.builder.build()
        assert req.content =="", \
               "request.content doesnt default to blank string"
        
        req = self.builder.build(content="abcdefg")
        assert req.content == "abcdefg", \
               "request doesn't store content correctly."
      

    def test_multipart(self):
        raise "skip"
        req = self.builder.build(
            method="POST",
            contentType=
            "multipart/form-data; boundary=---------------------------7d035c305e4",
            content=weblib.trim(
            """
            -----------------------------7d035c305e4
            Content-Disposition: form-data; name="upfile"; filename="mime.test"
            Content-Type: text/plain

            THIS IS A TEST
            THIS IS ONLY A TEST

            -----------------------------7d035c305e4
            Content-Disposition: form-data; name="action"
            
            upload
            -----------------------------7d035c305e4
            Content-Disposition: form-data; name="twovalues"
            
            value1
            -----------------------------7d035c305e4
            Content-Disposition: form-data; name="twovalues"
            
            value2
            -----------------------------7d035c305e4--
            """            
            ))

        #@TODO: try MIME-generation module instead of hard-coding the string..
        assert request.form.get("action")=="upload", \
               weblib.trim(
               """
               form values don't work on multipart forms. (got %s)
               -----------
               ** NOTE **
               this test works when I test manually, but not via
               the test script.. The bug appears to be in using StringIO
               (rather than sys.stdin) with the cgi.FieldStorage, or in
               some invisible characters in the MIME stuff.. 
               I have never been able to track it down... (help?)
               -----------
               """
               % repr(request.form.get("action")))

        assert request.form["upfile"].filename == "C:\mimetest.txt", \
               "file uploads don't return FieldStorage objects"

        assert request.form["twovalues"] == ("value1", "value2"), \
               "multi-value fields break on multi-part forms."


    def test_ampersand(self):
        """
        ampersand is %26 .. what if the querystring or
        form or whatever has an ampersand in it? At one
        point, urlDecode()ing it would break the value in
        two pieces...
        """
        ampstr = "a=apple&b=boys%26girls"
        req = self.builder.build(content=ampstr, querystring=ampstr)
        goal = {"a":"apple", "b":"boys&girls"}

        assert req.query == goal, \
               ".query doesn't grok ampersands."

        assert req.form == goal, \
               ".form doesn't grok ampersands."
예제 #7
0
class EngineTest(unittest.TestCase):

    def setUp(self):
        self.builder = RequestBuilder()

    def test_globals(self):
        myscript = trim(
            """
            import weblib
            assert isinstance(REQ, weblib.Request)
            assert isinstance(RES, weblib.Response)
            assert isinstance(ENG, weblib.Engine)
            """)
        eng = Engine(script=myscript)
        eng.run()
        assert eng.result == Engine.SUCCESS, eng.error
        

    def test_print(self):
        import sys, StringIO
        eng = Engine(script=trim(
            """
            import weblib
            print >> RES, 'this should show'
            print 'this should not'
            """))
        tempout, sys.stdout = sys.stdout, StringIO.StringIO()
        eng.run()
        sys.stdout, tempout = tempout, sys.stdout
        assert eng.response.buffer == "this should show\n", \
               "doesn't grab prints after import weblib!"
        assert tempout.getvalue() == "this should not\n", \
               "doesn't print rest to stdout"


    def test_exit(self):
        try:
            eng = Engine(script="raise SystemExit")
            eng.run()
            gotError = 0
        except SystemExit:
            gotError = 1
        assert not gotError, "Engine doesn't trap sys.exit()!"


    def test_runtwice(self):
        eng = Engine(script='print >> RES, "hello"')
        eng.run()
        try:
            eng.run()
            gotError = 0 
        except:
            gotError = 1
        assert gotError, "you should not be able to use engine twice!"

    def test_on_exit(self):
        """
        engine.do_on_exit(XXX) should remember XXX and call it at end of page.
        """
        def nothing():
            pass
        
        eng = Engine(script="")
        assert len(eng._exitstuff)==0, \
               "exitstuff not empty by default"
        
        eng.do_on_exit(nothing)
        assert len(eng._exitstuff)==1, \
               "do_on_exit doesn't add to exitstuff" 

        eng._exitstuff = []
        
        eng = Engine(script=trim(
            """
            # underscores on next line are just for emacs.. (trim strips them)
        ___ def cleanup():   
                print >> RES, 'wokka wokka wokka'
            ENG.do_on_exit(cleanup)
            """))
        eng.execute(eng.script)
        assert len(eng._exitstuff) == 1, \
               "didn't register exit function: %s" % str(eng._exitstuff)
        eng._exit()
        assert eng.response.buffer=='wokka wokka wokka\n', \
               "got wrong response: %s" % eng.response.buffer
        


    def test_result(self):
        eng = Engine(script='1+1')
        assert eng.result == None, \
               "engine.result doesn't default to None"

        eng.run()
        assert eng.result == eng.SUCCESS, \
               "engine.result doesn't return SUCCESS on success"

        eng = Engine(script="print 'cat' + 5")
        eng.run()
        assert eng.result == eng.EXCEPTION, \
               "engine.result doesn't return EXCEPTION on error."

        eng = Engine("assert 1==0, 'math is working.. :('")
        eng.run()
        assert eng.result == eng.FAILURE, \
               "engine.result doesn't return FAILURE on assertion failure."

        eng = Engine("import weblib; raise weblib.Redirect, 'url?query'")
        eng.run()
        assert eng.result == eng.REDIRECT, \
               "engine.result doesn't return REDIRECT on redirect."

    ## CGI-SPECIFIC (needs to move) ############################

    ## @TODO: this is really a test of Request
    def test_request(self):
        os.environ["QUERY_STRING"]="enginetest"

        engine = Engine(script="")
        assert engine.request.query.string=="enginetest", \
               "engine has wrong default request"
        del engine

        req = self.builder.build(querystring="e=mc2&this=a+test")
        engine = Engine("pass", request=req)
        assert engine.request.query.string=="e=mc2&this=a+test", \
               "engine has wrong passed-in request:" + \
               engine.request.query.string

    #@TODO: move to testRequest
    def test_form(self):
        weblib.MYFORM = {"a":"bcd"}
        try:
            myscript = trim(
                """
                import weblib
                assert REQ.form is weblib.MYFORM, \
                    'request uses wrong form'
                """)
            req = self.builder.build(form=weblib.MYFORM)
            eng = weblib.Engine(request=req, script=myscript)
            eng.run()
            assert eng.result == eng.SUCCESS, eng.result
        finally:
            del weblib.MYFORM

    def test_hadProblem(self):
        e = Engine(script="x = 1"); e.run()
        assert not e.hadProblem()
        e = Engine(script="raise hell"); e.run()
        assert e.hadProblem()
        e = Engine(script="assert 0"); e.run()
        assert e.hadProblem()


    def test__main__(self):
        e = Engine(script=trim(
            """
            if __name__=='__main__':
               print >> RES, 'sup?'
            """))
        e.run()
        assert e.response.buffer =="sup?\n"
        
            

    # engine needs to set pathinfo so that response
    # can redirect to ?lsakdfjlsdkafj
    # scripts should not pull it out of os.environ
    # because that won't work for twisted
    # instead, the engine for each service should
    # do this. (twisted, cgi, etc...)
    def test_pathInfo(self):
        eng = Engine(script=open("spec/pathinfo.app"))
        assert eng.request.pathInfo == "spec/pathinfo.app", \
               "Engine doesn't set .pathInfo correctly for open()ed scripts."


    def test_redirectToQuerystring(self):
        eng = Engine("import weblib; raise weblib.Redirect('?x=1')",
                     request=RequestBuilder().build(path="test.app"))
        eng.run()
        assert ('Location', 'test.app?x=1') in eng.response.headers