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+  $ formatternew  JsonApiResponseFormatter ();
20+  $ exceptionnew  ServerErrorHttpException ('Server error ' );
21+  $ responsenew  Response ();
22+  $ responsesetStatusCode ($ exceptionstatusCode );
23+  $ responsedata  = [
24+  'name '  => $ exceptiongetName (),
25+  'message '  => $ exceptiongetMessage (),
26+  'code '  => $ exceptiongetCode (),
27+  'status '  => $ exceptionstatusCode 
28+  ];
29+  $ formatterformat ($ response
30+  $ this assertJson ($ responsecontent );
31+  $ this assertSame (Json::encode ([
32+  'errors '  => [
33+  [
34+  'code '  => '0 ' ,
35+  'status '  => '500 ' ,
36+  'title '  => Response::$ httpStatuses500 ],
37+  'detail '  => 'Server error ' ,
38+  ]
39+  ]
40+  ]), $ responsecontent );
41+  }
42+ 
43+  public  function  testFormModelError ()
44+  {
45+  $ formatternew  JsonApiResponseFormatter ();
46+  $ exceptionnew  ServerErrorHttpException ('Server error ' );
47+  $ responsenew  Response ();
48+  $ responsesetStatusCode ($ exceptionstatusCode );
49+  $ serializernew  Serializer ();
50+  $ modelnew  ResourceModel ();
51+  $ modeladdError ('field1 ' , 'Error ' );
52+  $ modeladdError ('field2 ' , 'Test Error ' );
53+  $ responsedata  = $ serializerserialize ($ model
54+  $ formatterformat ($ response
55+  $ this assertJson ($ responsecontent );
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+  ]), $ responsecontent );
70+  }
71+ }
0 commit comments