scotty-web / scotty

Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp (Official Repository)
http://hackage.haskell.org/package/scotty
BSD 3-Clause "New" or "Revised" License
1.72k stars 134 forks source link

Is there any documentation on how to test Scotty endpoints? #275

Closed JivanRoquet closed 8 months ago

JivanRoquet commented 3 years ago

With the following endpoint:

myendpoint :: Text -> ScottyM ()
myendpoint info =
    post "/foo/bar/:var" $ do
        var :: Text <- param "var"
        query :: Query <- jsonData
        result <- liftIO $ retrieveResult info var query
        json $ result

runApi :: IO ()
runApi = scotty 4602 $ do
    myendpoint

How to test myendpoint with different possible inputs, for instance:

info1 = "foo"
query1 = Query { qParam1 = "foo", qParam2 = "bar" }
var1 = "bar"
expect1 = Result { foo = "foo", bar = "bar" }

res1 = decode $ test_myendpoint info1 query1 var1
res1 `shouldBe` expect1

info2 = "baz"
query2 = Query { qParam1 = "hello", qParam2 = "there" }
var2 = "boo"
expect2 = Result { foo = "biz", bar = "dev" }

res2 = decode $ test_myendpoint info2 query2 var2
res2 `shouldBe` expect2
RyanGlScott commented 3 years ago

I think you may be looking for the functionality provided by the hspec-wai library. In particular, the shouldRespondWith function may be what you are looking for. There are examples of shouldRespondWith being used in scotty's test suite.

JivanRoquet commented 3 years ago

Well, thanks for the answer obviously. However this lib doesn't seem to allow inspecting the response provided by the endpoint, instead just checking that it's equal to some value. E.g. you can't do "assert that this JSON list has 5 elements in it and they're all Int's".

In the end I simply chose to run the API for real and query it with a regular http client.

ocramz commented 1 year ago

@JivanRoquet I suppose it's ultimately a matter of taste here (in addition to engineering elbow grease and OSS maintainership work), but aeson's responsibility ends at "this response can be parsed as JSON and if not, here's an error". Any validation is up to the user.

You might want to add something like https://hackage.haskell.org/package/hspec-golden-aeson to your project for that.

ocramz commented 8 months ago

At present, the best documentation is our test suite and our examples.