Merge branch 'master' into 3609-arv-run
[arvados.git] / services / keepstore / handler_test.go
1 // Tests for Keep HTTP handlers:
2 //
3 //     GetBlockHandler
4 //     PutBlockHandler
5 //     IndexHandler
6 //
7 // The HTTP handlers are responsible for enforcing permission policy,
8 // so these tests must exercise all possible permission permutations.
9
10 package main
11
12 import (
13         "bytes"
14         "encoding/json"
15         "fmt"
16         "github.com/gorilla/mux"
17         "net/http"
18         "net/http/httptest"
19         "os"
20         "regexp"
21         "strings"
22         "testing"
23         "time"
24 )
25
26 // A RequestTester represents the parameters for an HTTP request to
27 // be issued on behalf of a unit test.
28 type RequestTester struct {
29         uri          string
30         api_token    string
31         method       string
32         request_body []byte
33 }
34
35 // Test GetBlockHandler on the following situations:
36 //   - permissions off, unauthenticated request, unsigned locator
37 //   - permissions on, authenticated request, signed locator
38 //   - permissions on, authenticated request, unsigned locator
39 //   - permissions on, unauthenticated request, signed locator
40 //   - permissions on, authenticated request, expired locator
41 //
42 func TestGetHandler(t *testing.T) {
43         defer teardown()
44
45         // Prepare two test Keep volumes. Our block is stored on the second volume.
46         KeepVM = MakeTestVolumeManager(2)
47         defer KeepVM.Quit()
48
49         vols := KeepVM.Volumes()
50         if err := vols[0].Put(TEST_HASH, TEST_BLOCK); err != nil {
51                 t.Error(err)
52         }
53
54         // Set up a REST router for testing the handlers.
55         rest := MakeRESTRouter()
56
57         // Create locators for testing.
58         // Turn on permission settings so we can generate signed locators.
59         enforce_permissions = true
60         PermissionSecret = []byte(known_key)
61         permission_ttl = time.Duration(300) * time.Second
62
63         var (
64                 unsigned_locator  = "/" + TEST_HASH
65                 valid_timestamp   = time.Now().Add(permission_ttl)
66                 expired_timestamp = time.Now().Add(-time.Hour)
67                 signed_locator    = "/" + SignLocator(TEST_HASH, known_token, valid_timestamp)
68                 expired_locator   = "/" + SignLocator(TEST_HASH, known_token, expired_timestamp)
69         )
70
71         // -----------------
72         // Test unauthenticated request with permissions off.
73         enforce_permissions = false
74
75         // Unauthenticated request, unsigned locator
76         // => OK
77         response := IssueRequest(rest,
78                 &RequestTester{
79                         method: "GET",
80                         uri:    unsigned_locator,
81                 })
82         ExpectStatusCode(t,
83                 "Unauthenticated request, unsigned locator", http.StatusOK, response)
84         ExpectBody(t,
85                 "Unauthenticated request, unsigned locator",
86                 string(TEST_BLOCK),
87                 response)
88         received_xbs := response.Header().Get("X-Block-Size")
89         expected_xbs := fmt.Sprintf("%d", len(TEST_BLOCK))
90         if received_xbs != expected_xbs {
91                 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
92         }
93
94         // ----------------
95         // Permissions: on.
96         enforce_permissions = true
97
98         // Authenticated request, signed locator
99         // => OK
100         response = IssueRequest(rest, &RequestTester{
101                 method:    "GET",
102                 uri:       signed_locator,
103                 api_token: known_token,
104         })
105         ExpectStatusCode(t,
106                 "Authenticated request, signed locator", http.StatusOK, response)
107         ExpectBody(t,
108                 "Authenticated request, signed locator", string(TEST_BLOCK), response)
109         received_xbs = response.Header().Get("X-Block-Size")
110         expected_xbs = fmt.Sprintf("%d", len(TEST_BLOCK))
111         if received_xbs != expected_xbs {
112                 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
113         }
114
115         // Authenticated request, unsigned locator
116         // => PermissionError
117         response = IssueRequest(rest, &RequestTester{
118                 method:    "GET",
119                 uri:       unsigned_locator,
120                 api_token: known_token,
121         })
122         ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
123
124         // Unauthenticated request, signed locator
125         // => PermissionError
126         response = IssueRequest(rest, &RequestTester{
127                 method: "GET",
128                 uri:    signed_locator,
129         })
130         ExpectStatusCode(t,
131                 "Unauthenticated request, signed locator",
132                 PermissionError.HTTPCode, response)
133
134         // Authenticated request, expired locator
135         // => ExpiredError
136         response = IssueRequest(rest, &RequestTester{
137                 method:    "GET",
138                 uri:       expired_locator,
139                 api_token: known_token,
140         })
141         ExpectStatusCode(t,
142                 "Authenticated request, expired locator",
143                 ExpiredError.HTTPCode, response)
144 }
145
146 // Test PutBlockHandler on the following situations:
147 //   - no server key
148 //   - with server key, authenticated request, unsigned locator
149 //   - with server key, unauthenticated request, unsigned locator
150 //
151 func TestPutHandler(t *testing.T) {
152         defer teardown()
153
154         // Prepare two test Keep volumes.
155         KeepVM = MakeTestVolumeManager(2)
156         defer KeepVM.Quit()
157
158         // Set up a REST router for testing the handlers.
159         rest := MakeRESTRouter()
160
161         // --------------
162         // No server key.
163
164         // Unauthenticated request, no server key
165         // => OK (unsigned response)
166         unsigned_locator := "/" + TEST_HASH
167         response := IssueRequest(rest,
168                 &RequestTester{
169                         method:       "PUT",
170                         uri:          unsigned_locator,
171                         request_body: TEST_BLOCK,
172                 })
173
174         ExpectStatusCode(t,
175                 "Unauthenticated request, no server key", http.StatusOK, response)
176         ExpectBody(t,
177                 "Unauthenticated request, no server key",
178                 TEST_HASH_PUT_RESPONSE, response)
179
180         // ------------------
181         // With a server key.
182
183         PermissionSecret = []byte(known_key)
184         permission_ttl = time.Duration(300) * time.Second
185
186         // When a permission key is available, the locator returned
187         // from an authenticated PUT request will be signed.
188
189         // Authenticated PUT, signed locator
190         // => OK (signed response)
191         response = IssueRequest(rest,
192                 &RequestTester{
193                         method:       "PUT",
194                         uri:          unsigned_locator,
195                         request_body: TEST_BLOCK,
196                         api_token:    known_token,
197                 })
198
199         ExpectStatusCode(t,
200                 "Authenticated PUT, signed locator, with server key",
201                 http.StatusOK, response)
202         response_locator := strings.TrimSpace(response.Body.String())
203         if !VerifySignature(response_locator, known_token) {
204                 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
205                         "response '%s' does not contain a valid signature",
206                         response_locator)
207         }
208
209         // Unauthenticated PUT, unsigned locator
210         // => OK
211         response = IssueRequest(rest,
212                 &RequestTester{
213                         method:       "PUT",
214                         uri:          unsigned_locator,
215                         request_body: TEST_BLOCK,
216                 })
217
218         ExpectStatusCode(t,
219                 "Unauthenticated PUT, unsigned locator, with server key",
220                 http.StatusOK, response)
221         ExpectBody(t,
222                 "Unauthenticated PUT, unsigned locator, with server key",
223                 TEST_HASH_PUT_RESPONSE, response)
224 }
225
226 // Test /index requests:
227 //   - unauthenticated /index request
228 //   - unauthenticated /index/prefix request
229 //   - authenticated   /index request        | non-superuser
230 //   - authenticated   /index/prefix request | non-superuser
231 //   - authenticated   /index request        | superuser
232 //   - authenticated   /index/prefix request | superuser
233 //
234 // The only /index requests that should succeed are those issued by the
235 // superuser. They should pass regardless of the value of enforce_permissions.
236 //
237 func TestIndexHandler(t *testing.T) {
238         defer teardown()
239
240         // Set up Keep volumes and populate them.
241         // Include multiple blocks on different volumes, and
242         // some metadata files (which should be omitted from index listings)
243         KeepVM = MakeTestVolumeManager(2)
244         defer KeepVM.Quit()
245
246         vols := KeepVM.Volumes()
247         vols[0].Put(TEST_HASH, TEST_BLOCK)
248         vols[1].Put(TEST_HASH_2, TEST_BLOCK_2)
249         vols[0].Put(TEST_HASH+".meta", []byte("metadata"))
250         vols[1].Put(TEST_HASH_2+".meta", []byte("metadata"))
251
252         // Set up a REST router for testing the handlers.
253         rest := MakeRESTRouter()
254
255         data_manager_token = "DATA MANAGER TOKEN"
256
257         unauthenticated_req := &RequestTester{
258                 method: "GET",
259                 uri:    "/index",
260         }
261         authenticated_req := &RequestTester{
262                 method:    "GET",
263                 uri:       "/index",
264                 api_token: known_token,
265         }
266         superuser_req := &RequestTester{
267                 method:    "GET",
268                 uri:       "/index",
269                 api_token: data_manager_token,
270         }
271         unauth_prefix_req := &RequestTester{
272                 method: "GET",
273                 uri:    "/index/" + TEST_HASH[0:3],
274         }
275         auth_prefix_req := &RequestTester{
276                 method:    "GET",
277                 uri:       "/index/" + TEST_HASH[0:3],
278                 api_token: known_token,
279         }
280         superuser_prefix_req := &RequestTester{
281                 method:    "GET",
282                 uri:       "/index/" + TEST_HASH[0:3],
283                 api_token: data_manager_token,
284         }
285
286         // -------------------------------------------------------------
287         // Only the superuser should be allowed to issue /index requests.
288
289   // ---------------------------
290   // enforce_permissions enabled
291         // This setting should not affect tests passing.
292   enforce_permissions = true
293
294         // unauthenticated /index request
295         // => UnauthorizedError
296         response := IssueRequest(rest, unauthenticated_req)
297         ExpectStatusCode(t,
298                 "enforce_permissions on, unauthenticated request",
299                 UnauthorizedError.HTTPCode,
300                 response)
301
302         // unauthenticated /index/prefix request
303         // => UnauthorizedError
304         response = IssueRequest(rest, unauth_prefix_req)
305         ExpectStatusCode(t,
306                 "permissions on, unauthenticated /index/prefix request",
307                 UnauthorizedError.HTTPCode,
308                 response)
309
310         // authenticated /index request, non-superuser
311         // => UnauthorizedError
312         response = IssueRequest(rest, authenticated_req)
313         ExpectStatusCode(t,
314                 "permissions on, authenticated request, non-superuser",
315                 UnauthorizedError.HTTPCode,
316                 response)
317
318         // authenticated /index/prefix request, non-superuser
319         // => UnauthorizedError
320         response = IssueRequest(rest, auth_prefix_req)
321         ExpectStatusCode(t,
322                 "permissions on, authenticated /index/prefix request, non-superuser",
323                 UnauthorizedError.HTTPCode,
324                 response)
325
326         // superuser /index request
327         // => OK
328         response = IssueRequest(rest, superuser_req)
329         ExpectStatusCode(t,
330                 "permissions on, superuser request",
331                 http.StatusOK,
332                 response)
333
334         // ----------------------------
335         // enforce_permissions disabled
336         // Valid Request should still pass.
337         enforce_permissions = false
338
339         // superuser /index request
340         // => OK
341         response = IssueRequest(rest, superuser_req)
342         ExpectStatusCode(t,
343                 "permissions on, superuser request",
344                 http.StatusOK,
345                 response)
346
347
348
349         expected := `^` + TEST_HASH + `\+\d+ \d+\n` +
350                 TEST_HASH_2 + `\+\d+ \d+\n$`
351         match, _ := regexp.MatchString(expected, response.Body.String())
352         if !match {
353                 t.Errorf(
354                         "permissions on, superuser request: expected %s, got:\n%s",
355                         expected, response.Body.String())
356         }
357
358         // superuser /index/prefix request
359         // => OK
360         response = IssueRequest(rest, superuser_prefix_req)
361         ExpectStatusCode(t,
362                 "permissions on, superuser request",
363                 http.StatusOK,
364                 response)
365
366         expected = `^` + TEST_HASH + `\+\d+ \d+\n$`
367         match, _ = regexp.MatchString(expected, response.Body.String())
368         if !match {
369                 t.Errorf(
370                         "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
371                         expected, response.Body.String())
372         }
373 }
374
375 // TestDeleteHandler
376 //
377 // Cases tested:
378 //
379 //   With no token and with a non-data-manager token:
380 //   * Delete existing block
381 //     (test for 403 Forbidden, confirm block not deleted)
382 //
383 //   With data manager token:
384 //
385 //   * Delete existing block
386 //     (test for 200 OK, response counts, confirm block deleted)
387 //
388 //   * Delete nonexistent block
389 //     (test for 200 OK, response counts)
390 //
391 //   TODO(twp):
392 //
393 //   * Delete block on read-only and read-write volume
394 //     (test for 200 OK, response with copies_deleted=1,
395 //     copies_failed=1, confirm block deleted only on r/w volume)
396 //
397 //   * Delete block on read-only volume only
398 //     (test for 200 OK, response with copies_deleted=0, copies_failed=1,
399 //     confirm block not deleted)
400 //
401 func TestDeleteHandler(t *testing.T) {
402         defer teardown()
403
404         // Set up Keep volumes and populate them.
405         // Include multiple blocks on different volumes, and
406         // some metadata files (which should be omitted from index listings)
407         KeepVM = MakeTestVolumeManager(2)
408         defer KeepVM.Quit()
409
410         vols := KeepVM.Volumes()
411         vols[0].Put(TEST_HASH, TEST_BLOCK)
412
413         // Explicitly set the permission_ttl to 0 for these
414         // tests, to ensure the MockVolume deletes the blocks
415         // even though they have just been created.
416         permission_ttl = time.Duration(0)
417
418         // Set up a REST router for testing the handlers.
419         rest := MakeRESTRouter()
420
421         var user_token = "NOT DATA MANAGER TOKEN"
422         data_manager_token = "DATA MANAGER TOKEN"
423
424         unauth_req := &RequestTester{
425                 method: "DELETE",
426                 uri:    "/" + TEST_HASH,
427         }
428
429         user_req := &RequestTester{
430                 method:    "DELETE",
431                 uri:       "/" + TEST_HASH,
432                 api_token: user_token,
433         }
434
435         superuser_existing_block_req := &RequestTester{
436                 method:    "DELETE",
437                 uri:       "/" + TEST_HASH,
438                 api_token: data_manager_token,
439         }
440
441         superuser_nonexistent_block_req := &RequestTester{
442                 method:    "DELETE",
443                 uri:       "/" + TEST_HASH_2,
444                 api_token: data_manager_token,
445         }
446
447         // Unauthenticated request returns PermissionError.
448         var response *httptest.ResponseRecorder
449         response = IssueRequest(rest, unauth_req)
450         ExpectStatusCode(t,
451                 "unauthenticated request",
452                 PermissionError.HTTPCode,
453                 response)
454
455         // Authenticated non-admin request returns PermissionError.
456         response = IssueRequest(rest, user_req)
457         ExpectStatusCode(t,
458                 "authenticated non-admin request",
459                 PermissionError.HTTPCode,
460                 response)
461
462         // Authenticated admin request for nonexistent block.
463         type deletecounter struct {
464                 Deleted int `json:"copies_deleted"`
465                 Failed  int `json:"copies_failed"`
466         }
467         var response_dc, expected_dc deletecounter
468
469         response = IssueRequest(rest, superuser_nonexistent_block_req)
470         ExpectStatusCode(t,
471                 "data manager request, nonexistent block",
472                 http.StatusNotFound,
473                 response)
474
475         // Authenticated admin request for existing block while never_delete is set.
476         never_delete = true
477         response = IssueRequest(rest, superuser_existing_block_req)
478         ExpectStatusCode(t,
479                 "authenticated request, existing block, method disabled",
480                 MethodDisabledError.HTTPCode,
481                 response)
482         never_delete = false
483
484         // Authenticated admin request for existing block.
485         response = IssueRequest(rest, superuser_existing_block_req)
486         ExpectStatusCode(t,
487                 "data manager request, existing block",
488                 http.StatusOK,
489                 response)
490         // Expect response {"copies_deleted":1,"copies_failed":0}
491         expected_dc = deletecounter{1, 0}
492         json.NewDecoder(response.Body).Decode(&response_dc)
493         if response_dc != expected_dc {
494                 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
495                         expected_dc, response_dc)
496         }
497         // Confirm the block has been deleted
498         _, err := vols[0].Get(TEST_HASH)
499         var block_deleted = os.IsNotExist(err)
500         if !block_deleted {
501                 t.Error("superuser_existing_block_req: block not deleted")
502         }
503
504         // A DELETE request on a block newer than permission_ttl should return
505         // success but leave the block on the volume.
506         vols[0].Put(TEST_HASH, TEST_BLOCK)
507         permission_ttl = time.Duration(1) * time.Hour
508
509         response = IssueRequest(rest, superuser_existing_block_req)
510         ExpectStatusCode(t,
511                 "data manager request, existing block",
512                 http.StatusOK,
513                 response)
514         // Expect response {"copies_deleted":1,"copies_failed":0}
515         expected_dc = deletecounter{1, 0}
516         json.NewDecoder(response.Body).Decode(&response_dc)
517         if response_dc != expected_dc {
518                 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
519                         expected_dc, response_dc)
520         }
521         // Confirm the block has NOT been deleted.
522         _, err = vols[0].Get(TEST_HASH)
523         if err != nil {
524                 t.Errorf("testing delete on new block: %s\n", err)
525         }
526 }
527
528 // TestPullHandler
529 //
530 // Test handling of the PUT /pull statement.
531 //
532 // Cases tested: syntactically valid and invalid pull lists, from the
533 // data manager and from unprivileged users:
534 //
535 //   1. Valid pull list from an ordinary user
536 //      (expected result: 401 Unauthorized)
537 //
538 //   2. Invalid pull request from an ordinary user
539 //      (expected result: 401 Unauthorized)
540 //
541 //   3. Valid pull request from the data manager
542 //      (expected result: 200 OK with request body "Received 3 pull
543 //      requests"
544 //
545 //   4. Invalid pull request from the data manager
546 //      (expected result: 400 Bad Request)
547 //
548 // Test that in the end, the pull manager received a good pull list with
549 // the expected number of requests.
550 //
551 // TODO(twp): test concurrency: launch 100 goroutines to update the
552 // pull list simultaneously.  Make sure that none of them return 400
553 // Bad Request and that pullq.GetList() returns a valid list.
554 //
555 func TestPullHandler(t *testing.T) {
556         defer teardown()
557
558         // Set up a REST router for testing the handlers.
559         rest := MakeRESTRouter()
560
561         var user_token = "USER TOKEN"
562         data_manager_token = "DATA MANAGER TOKEN"
563
564         good_json := []byte(`[
565                 {
566                         "locator":"locator_with_two_servers",
567                         "servers":[
568                                 "server1",
569                                 "server2"
570                         ]
571                 },
572                 {
573                         "locator":"locator_with_no_servers",
574                         "servers":[]
575                 },
576                 {
577                         "locator":"",
578                         "servers":["empty_locator"]
579                 }
580         ]`)
581
582         bad_json := []byte(`{ "key":"I'm a little teapot" }`)
583
584         type pullTest struct {
585                 name          string
586                 req           RequestTester
587                 response_code int
588                 response_body string
589         }
590         var testcases = []pullTest{
591                 {
592                         "Valid pull list from an ordinary user",
593                         RequestTester{"/pull", user_token, "PUT", good_json},
594                         http.StatusUnauthorized,
595                         "Unauthorized\n",
596                 },
597                 {
598                         "Invalid pull request from an ordinary user",
599                         RequestTester{"/pull", user_token, "PUT", bad_json},
600                         http.StatusUnauthorized,
601                         "Unauthorized\n",
602                 },
603                 {
604                         "Valid pull request from the data manager",
605                         RequestTester{"/pull", data_manager_token, "PUT", good_json},
606                         http.StatusOK,
607                         "Received 3 pull requests\n",
608                 },
609                 {
610                         "Invalid pull request from the data manager",
611                         RequestTester{"/pull", data_manager_token, "PUT", bad_json},
612                         http.StatusBadRequest,
613                         "Bad Request\n",
614                 },
615         }
616
617         for _, tst := range testcases {
618                 response := IssueRequest(rest, &tst.req)
619                 ExpectStatusCode(t, tst.name, tst.response_code, response)
620                 ExpectBody(t, tst.name, tst.response_body, response)
621         }
622
623         // The Keep pull manager should have received one good list with 3
624         // requests on it.
625         for i := 0; i < 3; i++ {
626                 item := <-pullq.NextItem
627                 if _, ok := item.(PullRequest); !ok {
628                         t.Errorf("item %v could not be parsed as a PullRequest", item)
629                 }
630         }
631
632         expectChannelEmpty(t, pullq.NextItem)
633 }
634
635 // TestTrashHandler
636 //
637 // Test cases:
638 //
639 // Cases tested: syntactically valid and invalid trash lists, from the
640 // data manager and from unprivileged users:
641 //
642 //   1. Valid trash list from an ordinary user
643 //      (expected result: 401 Unauthorized)
644 //
645 //   2. Invalid trash list from an ordinary user
646 //      (expected result: 401 Unauthorized)
647 //
648 //   3. Valid trash list from the data manager
649 //      (expected result: 200 OK with request body "Received 3 trash
650 //      requests"
651 //
652 //   4. Invalid trash list from the data manager
653 //      (expected result: 400 Bad Request)
654 //
655 // Test that in the end, the trash collector received a good list
656 // trash list with the expected number of requests.
657 //
658 // TODO(twp): test concurrency: launch 100 goroutines to update the
659 // pull list simultaneously.  Make sure that none of them return 400
660 // Bad Request and that replica.Dump() returns a valid list.
661 //
662 func TestTrashHandler(t *testing.T) {
663         defer teardown()
664
665         // Set up a REST router for testing the handlers.
666         rest := MakeRESTRouter()
667
668         var user_token = "USER TOKEN"
669         data_manager_token = "DATA MANAGER TOKEN"
670
671         good_json := []byte(`[
672                 {
673                         "locator":"block1",
674                         "block_mtime":1409082153
675                 },
676                 {
677                         "locator":"block2",
678                         "block_mtime":1409082153
679                 },
680                 {
681                         "locator":"block3",
682                         "block_mtime":1409082153
683                 }
684         ]`)
685
686         bad_json := []byte(`I am not a valid JSON string`)
687
688         type trashTest struct {
689                 name          string
690                 req           RequestTester
691                 response_code int
692                 response_body string
693         }
694
695         var testcases = []trashTest{
696                 {
697                         "Valid trash list from an ordinary user",
698                         RequestTester{"/trash", user_token, "PUT", good_json},
699                         http.StatusUnauthorized,
700                         "Unauthorized\n",
701                 },
702                 {
703                         "Invalid trash list from an ordinary user",
704                         RequestTester{"/trash", user_token, "PUT", bad_json},
705                         http.StatusUnauthorized,
706                         "Unauthorized\n",
707                 },
708                 {
709                         "Valid trash list from the data manager",
710                         RequestTester{"/trash", data_manager_token, "PUT", good_json},
711                         http.StatusOK,
712                         "Received 3 trash requests\n",
713                 },
714                 {
715                         "Invalid trash list from the data manager",
716                         RequestTester{"/trash", data_manager_token, "PUT", bad_json},
717                         http.StatusBadRequest,
718                         "Bad Request\n",
719                 },
720         }
721
722         for _, tst := range testcases {
723                 response := IssueRequest(rest, &tst.req)
724                 ExpectStatusCode(t, tst.name, tst.response_code, response)
725                 ExpectBody(t, tst.name, tst.response_body, response)
726         }
727
728         // The trash collector should have received one good list with 3
729         // requests on it.
730         for i := 0; i < 3; i++ {
731                 item := <-trashq.NextItem
732                 if _, ok := item.(TrashRequest); !ok {
733                         t.Errorf("item %v could not be parsed as a TrashRequest", item)
734                 }
735         }
736
737         expectChannelEmpty(t, trashq.NextItem)
738 }
739
740 // ====================
741 // Helper functions
742 // ====================
743
744 // IssueTestRequest executes an HTTP request described by rt, to a
745 // specified REST router.  It returns the HTTP response to the request.
746 func IssueRequest(router *mux.Router, rt *RequestTester) *httptest.ResponseRecorder {
747         response := httptest.NewRecorder()
748         body := bytes.NewReader(rt.request_body)
749         req, _ := http.NewRequest(rt.method, rt.uri, body)
750         if rt.api_token != "" {
751                 req.Header.Set("Authorization", "OAuth2 "+rt.api_token)
752         }
753         router.ServeHTTP(response, req)
754         return response
755 }
756
757 // ExpectStatusCode checks whether a response has the specified status code,
758 // and reports a test failure if not.
759 func ExpectStatusCode(
760         t *testing.T,
761         testname string,
762         expected_status int,
763         response *httptest.ResponseRecorder) {
764         if response.Code != expected_status {
765                 t.Errorf("%s: expected status %s, got %+v",
766                         testname, expected_status, response)
767         }
768 }
769
770 func ExpectBody(
771         t *testing.T,
772         testname string,
773         expected_body string,
774         response *httptest.ResponseRecorder) {
775         if response.Body.String() != expected_body {
776                 t.Errorf("%s: expected response body '%s', got %+v",
777                         testname, expected_body, response)
778         }
779 }