1+ <?php
2+ /**
3+ * @author Anton Tuyakhov <atuyakhov@gmail.com>
4+ */
5+ namespace tuyakhov \jsonapi \tests ;
6+
7+
8+ use tuyakhov \jsonapi \JsonApiResponseFormatter ;
9+ use tuyakhov \jsonapi \Serializer ;
10+ use tuyakhov \jsonapi \tests \data \ResourceModel ;
11+ use yii \helpers \Json ;
12+ use yii \web \Response ;
13+ use yii \web \ServerErrorHttpException ;
14+
15+ class JsonApiResponseFormatterTest extends TestCase
16+ {
17+ public function testFormatException ()
18+ {
19+ $ formatter = new JsonApiResponseFormatter ();
20+ $ exception = new ServerErrorHttpException ('Server error ' );
21+ $ response = new Response ();
22+ $ response ->setStatusCode ($ exception ->statusCode );
23+ $ response ->data = [
24+ 'name ' => $ exception ->getName (),
25+ 'message ' => $ exception ->getMessage (),
26+ 'code ' => $ exception ->getCode (),
27+ 'status ' => $ exception ->statusCode
28+ ];
29+ $ formatter ->format ($ response );
30+ $ this ->assertJson ($ response ->content );
31+ $ this ->assertSame (Json::encode ([
32+ 'errors ' => [
33+ [
34+ 'code ' => '0 ' ,
35+ 'status ' => '500 ' ,
36+ 'title ' => Response::$ httpStatuses [500 ],
37+ 'detail ' => 'Server error ' ,
38+ ]
39+ ]
40+ ]), $ response ->content );
41+ }
42+
43+ public function testFormModelError ()
44+ {
45+ $ formatter = new JsonApiResponseFormatter ();
46+ $ exception = new ServerErrorHttpException ('Server error ' );
47+ $ response = new Response ();
48+ $ response ->setStatusCode ($ exception ->statusCode );
49+ $ serializer = new Serializer ();
50+ $ model = new ResourceModel ();
51+ $ model ->addError ('field1 ' , 'Error ' );
52+ $ model ->addError ('field2 ' , 'Test Error ' );
53+ $ response ->data = $ serializer ->serialize ($ model );
54+ $ formatter ->format ($ response );
55+ $ this ->assertJson ($ response ->content );
56+ $ this ->assertSame (Json::encode ([
57+ 'errors ' => [
58+ [
59+ 'source ' => ['pointer ' => "/data/attributes/field1 " ],
60+ 'detail ' => 'Error ' ,
61+ 'status ' => '422 '
62+ ],
63+ [
64+ 'source ' => ['pointer ' => "/data/attributes/field2 " ],
65+ 'detail ' => 'Test Error ' ,
66+ 'status ' => '422 '
67+ ]
68+ ]
69+ ]), $ response ->content );
70+ }
71+ }
0 commit comments