Medical Imaging Interaction Toolkit  2018.4.99-389bf124
Medical Imaging Interaction Toolkit
mitkRESTClientTest.cpp
Go to the documentation of this file.
1 /*============================================================================
2 
3 The Medical Imaging Interaction Toolkit (MITK)
4 
5 Copyright (c) German Cancer Research Center (DKFZ)
6 All rights reserved.
7 
8 Use of this source code is governed by a 3-clause BSD license that can be
9 found in the LICENSE file.
10 
11 ============================================================================*/
12 
13 #include <mitkTestFixture.h>
14 #include <mitkTestingMacros.h>
15 
16 #include <mitkIRESTManager.h>
17 #include <mitkIRESTObserver.h>
18 #include <mitkRESTClient.h>
19 #include <mitkRESTUtil.h>
20 
21 #include <usGetModuleContext.h>
22 #include <usModuleContext.h>
23 #include <usServiceReference.h>
24 
25 #include <vtkDebugLeaks.h>
26 
27 class mitkRESTClientTestSuite : public mitk::TestFixture, mitk::IRESTObserver
28 {
29  CPPUNIT_TEST_SUITE(mitkRESTClientTestSuite);
30  // MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); GET requests do not support content yet?
31  MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish);
32  // MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); Does not work reliably on dart clients
33  // MITK_TEST(PostRequestValidURI_ReturnsExpectedJSON); -- " --
34  MITK_TEST(GetRequestInvalidURI_ThrowsException);
35  MITK_TEST(PutRequestInvalidURI_ThrowsException);
36  MITK_TEST(PostRequestInvalidURI_ThrowsException);
37  CPPUNIT_TEST_SUITE_END();
38 
39 public:
41  web::json::value m_Data;
42 
43  web::http::http_response Notify(const web::uri &,
44  const web::json::value &,
45  const web::http::method &,
46  const mitk::RESTUtil::ParamMap &) override
47  {
48  auto response = web::http::http_response();
49  response.set_body(m_Data);
50  response.set_status_code(web::http::status_codes::OK);
51 
52  return response;
53  }
54 
59  void setUp() override
60  {
61  m_Data = web::json::value();
62  m_Data[U("userId")] = web::json::value(1);
63  m_Data[U("id")] = web::json::value(1);
64  m_Data[U("title")] = web::json::value(U("this is a title"));
65  m_Data[U("body")] = web::json::value(U("this is a body"));
66 
69  if (serviceRef)
70  {
71  m_Service = us::GetModuleContext()->GetService(serviceRef);
72  }
73 
74  if (!m_Service)
75  {
76  CPPUNIT_FAIL("Getting Service in setUp() failed");
77  }
78 
79  m_Service->ReceiveRequest(U("http://localhost:8080/clienttest"), this);
80  }
81 
82  void tearDown() override { m_Service->HandleDeleteObserver(this); }
83 
84  void GetRequestValidURI_ReturnsExpectedJSON()
85  {
86  web::json::value result;
87 
88  m_Service->SendRequest(U("http://localhost:8080/clienttest"))
89  .then([&](pplx::task<web::json::value> resultTask) {
90  try
91  {
92  result = resultTask.get();
93  }
94  catch (const mitk::Exception &exception)
95  {
96  MITK_ERROR << exception.what();
97  return;
98  }
99  })
100  .wait();
101 
102  CPPUNIT_ASSERT_MESSAGE("Result is the expected JSON value", result == m_Data);
103  }
104 
105  void MultipleGetRequestValidURI_AllTasksFinish()
106  {
107  int count = 0;
108 
109  // Create multiple tasks e.g. as shown below
110  std::vector<pplx::task<void>> tasks;
111  for (int i = 0; i < 20; ++i)
112  {
113  pplx::task<void> singleTask = m_Service->SendRequest(U("http://localhost:8080/clienttest"))
114  .then([&](pplx::task<web::json::value> resultTask) {
115  // Do something when a single task is done
116  try
117  {
118  resultTask.get();
119  count += 1;
120  }
121  catch (const mitk::Exception &exception)
122  {
123  MITK_ERROR << exception.what();
124  return;
125  }
126  });
127  tasks.emplace_back(singleTask);
128  }
129  // Create a joinTask which includes all tasks you've created
130  auto joinTask = pplx::when_all(begin(tasks), end(tasks));
131  // Run asynchonously
132  joinTask
133  .then([&](pplx::task<void> resultTask) {
134  // Do something when all tasks are finished
135  try
136  {
137  resultTask.get();
138  count += 1;
139  }
140  catch (const mitk::Exception &exception)
141  {
142  MITK_ERROR << exception.what();
143  return;
144  }
145  })
146  .wait();
147 
148  CPPUNIT_ASSERT_MESSAGE("Multiple Requests", 21 == count);
149  }
150 
151  void PutRequestValidURI_ReturnsExpectedJSON()
152  {
153  // optional: link might get invalid or content is changed
154  web::json::value result;
155 
156  m_Service
157  ->SendJSONRequest(
158  U("https://jsonplaceholder.typicode.com/posts/1"), mitk::IRESTManager::RequestType::Put)
159  .then([&](pplx::task<web::json::value> resultTask) {
160  try
161  {
162  result = resultTask.get();
163  }
164  catch (const mitk::Exception &exception)
165  {
166  MITK_ERROR << exception.what();
167  return;
168  }
169  })
170  .wait();
171 
172  CPPUNIT_ASSERT_MESSAGE(
173  "Result is the expected JSON value, check if the link is still valid since this is an optional test",
174  result == m_Data);
175  }
176 
177  void PostRequestValidURI_ReturnsExpectedJSON()
178  {
179  // optional: link might get invalid or content is changed
180  web::json::value result;
181  web::json::value data;
182 
183  data[U("userId")] = m_Data[U("userId")];
184  data[U("title")] = m_Data[U("title")];
185  data[U("body")] = m_Data[U("body")];
186 
187  m_Service
188  ->SendJSONRequest(U("https://jsonplaceholder.typicode.com/posts"), mitk::IRESTManager::RequestType::Post, &data)
189  .then([&](pplx::task<web::json::value> resultTask) {
190  try
191  {
192  result = resultTask.get();
193  }
194  catch (const mitk::Exception &exception)
195  {
196  MITK_ERROR << exception.what();
197  return;
198  }
199  })
200  .wait();
201 
202  data[U("id")] = web::json::value(101);
203  CPPUNIT_ASSERT_MESSAGE(
204  "Result is the expected JSON value, check if the link is still valid since this is an optional test",
205  result == data);
206  }
207 
208  void PostRequestHeaders_Success()
209  {
210  mitk::RESTUtil::ParamMap headers;
211  headers.insert(mitk::RESTUtil::ParamMap::value_type(
212  U("Content-Type"), U("multipart/related; type=\"application/dicom\"; boundary=boundary")));
213 
214  m_Service->SendRequest(U("http://localhost:8080/clienttest")).then([&](pplx::task<web::json::value> resultTask) {
215  // Do something when a single task is done
216  try
217  {
218  resultTask.get();
219  }
220  catch (const mitk::Exception &exception)
221  {
222  MITK_ERROR << exception.what();
223  return;
224  }
225  });
226  }
227 
228  void GetException()
229  {
230  // Method which makes a get request to an invalid uri
231  web::json::value result;
232 
233  m_Service->SendRequest(U("http://localhost:1234/invalid"))
234  .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
235  .wait();
236  }
237  void GetRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(GetException(), mitk::Exception); }
238 
239  void PutException()
240  {
241  // Method which makes a put request to an invalid uri
242  web::json::value result;
243 
244  m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Put, &m_Data)
245  .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
246  .wait();
247  }
248  void PutRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); }
249 
250  void PostException()
251  {
252  // Method which makes a post request to an invalid uri
253  web::json::value result;
254 
255  m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Post, &m_Data)
256  .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); })
257  .wait();
258  }
259  void PostRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); }
260 };
261 
262 MITK_TEST_SUITE_REGISTRATION(mitkRESTClient)
virtual pplx::task< web::json::value > SendJSONRequest(const web::uri &uri, const RequestType &type=RequestType::Get, const web::json::value *body=nullptr, const std::map< utility::string_t, utility::string_t > headers={}, const utility::string_t &filePath={})=0
Executes a HTTP request in the mitkRESTClient class.
ServiceReferenceU GetServiceReference(const std::string &clazz)
virtual void ReceiveRequest(const web::uri &uri, IRESTObserver *observer)=0
starts listening for requests if there isn&#39;t another observer listening and the port is free ...
MITK_TEST_SUITE_REGISTRATION(mitkImageToItk)
#define MITK_ERROR
Definition: mitkLogMacros.h:20
This is a microservice interface for managing REST requests.
#define MITK_TEST(TESTMETHOD)
Adds a test to the current test suite.
void * GetService(const ServiceReferenceBase &reference)
#define OK
An object of this class represents an exception of MITK. Please don&#39;t instantiate exceptions manually...
Definition: mitkException.h:45
Test fixture for parameterized tests.
virtual pplx::task< web::json::value > SendRequest(const web::uri &uri, const RequestType &type=RequestType::Get, const std::map< utility::string_t, utility::string_t > headers={})=0
Executes a HTTP request in the mitkRESTClient class.
virtual web::http::http_response Notify(const web::uri &uri, const web::json::value &data, const web::http::method &method, const mitk::RESTUtil::ParamMap &headers)=0
Called if there&#39;s an incoming request for the observer, observer implements how to handle request...
web::http::http_response http_response
mitk::PlanePositionManagerService * m_Service
std::map< utility::string_t, utility::string_t > ParamMap
Definition: mitkRESTUtil.h:27
virtual void HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri={})=0
Handles the deletion of an observer for all or a specific uri.
static ModuleContext * GetModuleContext()
Returns the module context of the calling module.