restMock-spec Pub Share

Mocking REST services

Mocking REST services is simple with the di:es:el framework: every message is exposed automatically as a REST service! So simply by defining a mock, you get a working service - here are some examples.

Here's a simple mock for a REST service - a basic service1/status service which returns a JSON. The prefix for these automatic services (one per message) is /diesel/react/ which normally you configure as the URL+prefix of the service implementation.

When you click service1/status, the following mock rule is executed:

0 $mock:: service1.status
   . (payload={status:"ok",someStats:"123"})

Note that you can't use this to serve /myStatus - here's a quick way to do that (the prefix in this case is /diesel/rest/ - see the link):

0 $mock:: diesel.rest (path == "/myStatus")
   . (payload={status:"ok",someStats:"123"})

Simple path mapping

We can use a simple path mapping, fairly common in matching REST URLs (note the special ~path operator):

Data not found:

0 $mock:: diesel.rest (path ~path "/account2/404/id")
   diesel.flow.return (diesel.http.response.status:Number=404=404, diesel.http.response.header.myHeader="mine"="mine")

Success finding data:

0 $mock:: diesel.rest (path ~path "/account2/:acctId/id")
   . (payload={status:"ok",accountId:acctId})

$when:: diesel.rest (path ~path "/path2/*idpath")
   . (payload={status:"ok",accountId:idpath})

Regular expressions in the path

If you have complex paths to match, or if you want a custom path with anonymous elements that you ignore: use a regular expression and the ~= operator. You can call this via an url like /getAccount/54554 :

0 $mock:: diesel.rest (path ~= "/getAccount/(\d+)")
   . (payload={status:"ok",someStats:"456"})

You can also use a custom path with named elements: use named capture groups in the regular expression - these are parsed and defined as values in the context. You can call this via an url like /getAccount1/54554 :

0 $mock:: diesel.rest (path ~= "/getAccount1/(?<acctId>\d+)")
   . (payload={status:"ok",someStats:"67",accountId:acctId})

NOTE that thers is a catch when using REST: you need to save this spec for it to be visible and used!

Setting response code and headears

0 $mock:: diesel.rest (path ~= "/getAccount/(\d+)")
   ctx.set (dieselx.x="asdf"="asdf")
   . (payload={status:"ok",someStats:"456"})

TODO resp code

TODO c-type from payload type json when response code set - different branch


Was this useful?    

By: Razie | 2019-04-27 .. 2021-02-02 | Tags: spec , dsl , private


Viewed 875 times ( | History | Print ) this page.

You need to log in to post a comment!

© Copyright DieselApps, 2012-2024, all rights reserved.