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