agrafix / Spock

Another Haskell web framework for rapid development
https://www.spock.li
678 stars 56 forks source link

Testing with session #99

Closed zjhmale closed 7 years ago

zjhmale commented 7 years ago

Hi @agrafix, When I try to test an API actually needs the session, it will fail since the mock server can not reach the in-memory session. For instance, when testing with this test case, it will produce the error message:

image

Which is defined here, and it proves that the mock app can not reach out to the session when testing it, but it works fine when I start the server and test the API by hand.

Any ideas to fix this? Thanks in advance!

agrafix commented 7 years ago

I think the testing framework does not automatically manage cookies for you. So you'll need to read and then set the cookies by hand :-/

zjhmale commented 7 years ago

@agrafix, Thanks for the hint! But after I using setCookie in login action, I still can not read cookie in posts action.

Here is the code snippet.

post "login" $ do
      c <- cookie "todo"
      liftIO $ print c
      setCookie "todo" "HczlBC9LOI9jyi9lhZ4Yj8YZLG9WmW31nJ01DzPKw-h9SRVsx3JhLRT-Kaid9DLnh3EsxvH04RDDiKj3hP_Y7g" defaultCookieSettings { cs_EOL = CookieValidFor 3600 }
      username <- param' "username"
      password <- param' "password"
      _type <- param' "type"
      (j, sess) <- runQuery' $ loginSignupPost username password _type
      writeSession sess
      json j

post "posts" $ do
      c <- cookie "todo"
      liftIO $ print c
      requireAuth onfail $ \(uid, _) ->
        jsonBody' >>= runQuery' . newPost uid >>= json

If I start the server by hand, it will log out the cookie with a Just value, but in test cases, it will just get Nothing.

Is there any example projects that actually test Spock app with session and cookie? I can find one you wrote here, but seems you did not actually test the cookie/single and cookie/multiple API.

agrafix commented 7 years ago

Sorry, that's not what I meant. The testing framework runs each test in it's own session, so cookies will not be preserved between the tests. (See https://github.com/hspec/hspec-wai/blob/2c09b944bc85b0d6d2f3d3807c4885b01f736c03/src/Test/Hspec/Wai/Internal.hs#L42 ). You'll either have to write your own wrapper around wai-test(-extra) and reuse the session, or extract and pass around cookies manually like in https://github.com/agrafix/Spock/blob/2c60a48b2c0be0768071cc1b3c7f14590ffcc7d6/Spock/test/Web/Spock/CsrfSpec.hs#L32-L45

zjhmale commented 7 years ago

Thanks! I'll follow the second solution first :)

zjhmale commented 7 years ago

Hi @agrafix, the second way works for me, Thanks! I'll try to figure out how to write my own hspec wrapper then.

agrafix commented 7 years ago

Btw: please do take a look at https://github.com/agrafix/users , I think it would be a great fit for your project :-)

zjhmale commented 7 years ago

@agrafix Great! I'll try to use this package tomorrow :)