-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathPatchApiTestBase.cs
More file actions
1254 lines (1157 loc) · 54.8 KB
/
PatchApiTestBase.cs
File metadata and controls
1254 lines (1157 loc) · 54.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Service.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Patch
{
/// <summary>
/// Test PATCH REST Api validating expected results are obtained.
/// </summary>
[TestClass]
public abstract class PatchApiTestBase : RestApiTestBase
{
#region Positive Tests
/// <summary>
/// Tests the PatchOne functionality with a REST PATCH request
/// with a nullable column specified as NULL.
/// The test should pass successfully for update as well as insert.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Nulled_Test()
{
// Performs a successful PATCH insert when a nullable column
// is specified as null in the request body.
string requestBody = @"
{
""categoryName"": ""SciFi"",
""piecesAvailable"": null,
""piecesRequired"": 4
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"categoryid/3/pieceid/1",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOne_Insert_Nulled_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
// Performs a successful PATCH update when a nullable column
// is specified as null in the request body.
requestBody = @"
{
""piecesAvailable"": null
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/1/pieceid/1",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOne_Update_Nulled_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
}
/// <summary>
/// Tests REST PatchOne which results in an insert.
/// URI Path: PK of record that does not exist.
/// Req Body: Valid Parameters.
/// Expects: 201 Created where sqlQuery validates insert.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Insert_UniqueCharacters_Test()
{
string requestBody = @"
{
""始計"": ""Revised Chapter 1 notes: "",
""作戰"": ""Revised Chapter 2 notes: "",
""謀攻"": ""Revised Chapter 3 notes: ""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"┬─┬ノ( º _ ºノ)/2",
queryString: null,
entityNameOrPath: _integrationUniqueCharactersEntity,
sqlQuery: GetQuery(nameof(PatchOne_Insert_UniqueCharacters_Test)),
operationType: EntityActionOperation.Upsert,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests REST PatchOne which results in an insert.
/// URI Path: PK of record that does not exist.
/// Req Body: Valid Parameters.
/// Expects: 201 Created where sqlQuery validates insert.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Insert_NonAutoGenPK_Test()
{
string requestBody = @"
{
""title"": ""Batman Begins"",
""issue_number"": 1234
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"id/2",
queryString: null,
entityNameOrPath: _integration_NonAutoGenPK_EntityName,
sqlQuery: GetQuery(nameof(PatchOne_Insert_NonAutoGenPK_Test)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
requestBody = @"
{
""categoryName"": ""Tales"",
""piecesAvailable"":""5"",
""piecesRequired"":""4""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"categoryid/4/pieceid/1",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOne_Insert_CompositeNonAutoGenPK_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
requestBody = @"
{
""categoryName"": """",
""piecesAvailable"":""5"",
""piecesRequired"":""4""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"categoryid/5/pieceid/1",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOne_Insert_Empty_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
requestBody = @"
{
""categoryName"": ""SciFi""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"categoryid/7/pieceid/1",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOne_Insert_Default_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
// Entity with mapping defined for columns
requestBody = @"
{
""Scientific Name"": ""Quercus"",
""United State's Region"": ""South West""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"treeId/4",
queryString: null,
entityNameOrPath: _integrationMappingEntity,
sqlQuery: GetQuery("PatchOne_Insert_Mapping_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests to validate that request PATCH requests modifying fields
/// from one base table in view and resolving to insert operation
/// execute successfully.
/// </summary>
/// <returns></returns>
[TestMethod]
public virtual async Task PatchOneInsertInViewTest()
{
// PATCH insert on simple view based on stocks table.
string requestBody = @"
{
""categoryName"": ""SciFi""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/4/pieceid/1",
queryString: null,
entityNameOrPath: _simple_subset_stocks,
sqlQuery: GetQuery("PatchOneInsertInStocksViewSelected"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests REST PatchOne which results in incremental update
/// URI Path: PK of existing record.
/// Req Body: Valid Parameter with intended update.
/// Expects: 200 OK where sqlQuery validates update.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Update_Test()
{
string requestBody = @"
{
""title"": ""Heart of Darkness""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/8",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: GetQuery(nameof(PatchOne_Update_Test)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
requestBody = @"
{
""content"": ""That's a great book""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/567/book_id/1",
queryString: null,
entityNameOrPath: _entityWithCompositePrimaryKey,
sqlQuery: GetQuery("PatchOne_Update_Default_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
requestBody = @"
{
""piecesAvailable"": ""10""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/1/pieceid/1",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOne_Update_CompositeNonAutoGenPK_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
requestBody = @"
{
""categoryName"": """"
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/1/pieceid/1",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOne_Update_Empty_Test"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
}
/// <summary>
/// Test to validate successful execution of a request when a computed field is missing from the request body.
/// </summary>
[TestMethod]
public virtual async Task PatchOneWithComputedFieldMissingFromRequestBody()
{
// Validate successful execution of a PATCH update when a computed field (here 'last_sold_on_date')
// is missing from the request body. Successful execution of the PATCH request confirms that we did not
// attempt to NULL out the 'last_sold_on_update' field.
string requestBody = @"
{
""book_name"": ""New book"",
""copies_sold"": 50
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"id/1",
queryString: null,
entityNameOrPath: _entityWithReadOnlyFields,
sqlQuery: GetQuery("PatchOneUpdateWithComputedFieldMissingFromRequestBody"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
// Validate successful execution of a PATCH insert when a computed field (here 'last_sold_on_date')
// is missing from the request body. Successful execution of the PATCH request confirms that we did not
// attempt to NULL out the 'last_sold_on_update' field.
requestBody = @"
{
""book_name"": ""New book"",
""copies_sold"": 50
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: $"id/2",
queryString: null,
entityNameOrPath: _entityWithReadOnlyFields,
sqlQuery: GetQuery("PatchOneInsertWithComputedFieldMissingFromRequestBody"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests that the PATCH updates can only update the rows which are accessible after applying the
/// security policy which uses data from session context.
/// </summary>
[TestMethod]
public virtual Task PatchOneUpdateTestOnTableWithSecurityPolicy()
{
return Task.CompletedTask;
}
/// <summary>
/// Tests the PatchOne functionality with a REST PATCH request
/// without a primary key route on an entity with an auto-generated primary key.
/// With keyless PATCH support, ValidateUpsertRequestContext allows this because
/// all PK columns are auto-generated. The mutation engine then performs an insert
/// and succeeds with 201 Created.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Insert_KeylessWithAutoGenPK_Test()
{
string requestBody = @"
{
""title"": ""My New Book"",
""publisher_id"": 1234
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: string.Empty,
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: GetQuery(nameof(PatchOne_Insert_KeylessWithAutoGenPK_Test)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests the PatchOne functionality with a REST PATCH request
/// without a primary key route, where the request body contains
/// all PK columns that match an existing row.
/// The engine should detect the PK in the body, route through the
/// upsert path, find the existing row, and perform an UPDATE (200 OK).
/// This is a regression test: previously, a keyless upsert with body PKs
/// always executed an INSERT, which would fail on a PK violation.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Update_KeylessWithPKInBody_ExistingRow_Test()
{
// id=1 exists in the magazines table with title='Vogue'.
// Sending a PATCH with the PK in the body should UPDATE the existing row.
string requestBody = @"
{
""id"": 1,
""title"": ""Updated Vogue""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: string.Empty,
queryString: null,
entityNameOrPath: _integration_NonAutoGenPK_EntityName,
sqlQuery: GetQuery(nameof(PatchOne_Update_KeylessWithPKInBody_ExistingRow_Test)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
}
/// <summary>
/// Tests the PatchOne functionality with a REST PATCH request
/// without a primary key route, where the request body contains
/// all PK columns that do NOT match any existing row.
/// The engine should detect the PK in the body, route through the
/// upsert path, find no existing row, and perform an INSERT (201 Created).
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Insert_KeylessWithPKInBody_NewRow_Test()
{
string requestBody = @"
{
""id"": " + STARTING_ID_FOR_TEST_INSERTS + @",
""title"": ""Brand New Magazine""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: string.Empty,
queryString: null,
entityNameOrPath: _integration_NonAutoGenPK_EntityName,
sqlQuery: GetQuery(nameof(PatchOne_Insert_KeylessWithPKInBody_NewRow_Test)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests successful execution of PATCH update requests on views
/// when requests try to modify fields belonging to one base table
/// in the view.
/// </summary>
/// <returns></returns>
[TestMethod]
public virtual async Task PatchOneUpdateViewTest()
{
// PATCH update on simple view based on stocks table.
string requestBody = @"
{
""categoryName"": ""Historical""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/2/pieceid/1",
queryString: null,
entityNameOrPath: _simple_subset_stocks,
sqlQuery: GetQuery("PatchOneUpdateStocksViewSelected"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
}
/// <summary>
/// Tests the PatchOne functionality with a REST PATCH request using
/// headers that include as a key "If-Match" with an item that does exist,
/// resulting in an update occuring. Verify update with Find.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Update_IfMatchHeaders_Test()
{
Dictionary<string, StringValues> headerDictionary = new();
headerDictionary.Add("If-Match", "*");
string requestBody = @"
{
""title"": ""The Hobbit Returns to The Shire"",
""publisher_id"": 1234
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/1",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: GetQuery(nameof(PatchOne_Update_IfMatchHeaders_Test)),
operationType: EntityActionOperation.UpsertIncremental,
headers: new HeaderDictionary(headerDictionary),
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK
);
}
/// <summary>
/// Tests that a PATCH request with an invalid If-Match header value
/// (anything other than "*") returns a 400 Bad Request response
/// because ETags are not supported.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Update_InvalidIfMatchHeader_Returns400_Test()
{
Dictionary<string, StringValues> headerDictionary = new();
headerDictionary.Add("If-Match", "\"abc123\"");
string requestBody = @"
{
""title"": ""The Hobbit Returns to The Shire"",
""publisher_id"": 1234
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/1",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: string.Empty,
operationType: EntityActionOperation.UpsertIncremental,
headers: new HeaderDictionary(headerDictionary),
requestBody: requestBody,
exceptionExpected: true,
expectedErrorMessage: "Etags not supported, use '*'",
expectedStatusCode: HttpStatusCode.BadRequest,
expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString()
);
}
/// <summary>
/// Test to validate successful execution of PATCH operation which satisfies the database policy for the update operation it resolves into.
/// </summary>
[TestMethod]
public virtual async Task PatchOneUpdateWithDatabasePolicy()
{
// PATCH operation resolves to update because we have a record present for given PK.
// Since the database policy for update operation ("@item.pieceid ne 1") is satisfied by the operation, it executes successfully.
string requestBody = @"
{
""piecesAvailable"": 4
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/100/pieceid/99",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOneUpdateWithDatabasePolicy"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK,
clientRoleHeader: "database_policy_tester"
);
}
/// <summary>
/// Test to validate successful execution of PATCH operation which satisfies the database policy for the insert operation it resolves into.
/// </summary>
[TestMethod]
public virtual async Task PatchOneInsertWithDatabasePolicy()
{
// PATCH operation resolves to insert because we don't have a record present for given PK.
// Since the database policy for insert operation ("@item.pieceid ne 6 and @item.piecesAvailable gt 0") is satisfied by the operation, it executes successfully.
string requestBody = @"
{
""piecesAvailable"": 4,
""categoryName"": ""SciFi""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/0/pieceid/7",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchOneInsertWithDatabasePolicy"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
clientRoleHeader: "database_policy_tester",
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests that for a successful PATCH API request, the response returned takes into account that no read action is configured for the role.
/// URI Path: PK of existing record.
/// Req Body: Valid Parameter with intended update.
/// Expects:
/// Status: 200 OK since the PATCH operation results in an update
/// Response Body: Empty because the role policy_tester_noread has no read action configured.
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Update_NoReadTest()
{
string requestBody = @"
{
""title"": ""Heart of Darkness""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/8",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: GetQuery(nameof(PatchOne_Update_NoReadTest)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK,
clientRoleHeader: "test_role_with_noread"
);
}
/// <summary>
/// Tests that for a successful PATCH API request, the response returned takes into account the include and exclude fields configured for the read action.
/// URI Path: PK of existing record.
/// Req Body: Valid Parameter with intended update.
/// Expects:
/// Status: 200 OK as PATCH operation results in an update operation.
/// Response Body: Contains only the id, title fields as publisher_id field is excluded in the read configuration.
/// </summary>
[TestMethod]
public virtual async Task Patch_Update_WithExcludeFieldsTest()
{
string requestBody = @"
{
""title"": ""Heart of Darkness""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/8",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: GetQuery(nameof(Patch_Update_WithExcludeFieldsTest)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK,
clientRoleHeader: "test_role_with_excluded_fields"
);
}
/// <summary>
/// Tests that for a successful PATCH API request, the response returned takes into account the database policy configured for the read action.
/// URI Path: PK of existing record.
/// Req Body: Valid Parameter with intended update.
/// Expects:
/// Status: 200 OK
/// Response Body: Empty. The read action for the role used in this test has a database policy
/// defined which states that title cannot be equal to Test. Since, this test updates the title
/// to Test the response must be empty.
/// </summary>
[TestMethod]
public virtual async Task Patch_Update_WithReadDatabasePolicyTest()
{
string requestBody = @"
{
""title"": ""Test""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/8",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: GetQuery(nameof(PatchOne_Update_NoReadTest)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK,
clientRoleHeader: "test_role_with_policy_excluded_fields"
);
}
/// <summary>
/// Tests that for a successful PATCH API request, the response returned takes into account the database policy configured for the read action.
/// URI Path: PK of existing record.
/// Req Body: Valid Parameter with intended update.
/// Expects:
/// Status: 200 OK
/// Response Body: Non-Empty and does not contain the publisher_id field. The read action for the role used in this test has a database policy
/// defined which states that title cannot be equal to Test. Since, this test updates the title
/// to a different the response must be non-empty. Also, since the role excludes the publisher_id field, the repsonse should not
/// contain publisher_id field.
/// </summary>
[TestMethod]
public virtual async Task Patch_Update_WithReadDatabasePolicyUnsatisfiedTest()
{
string requestBody = @"
{
""title"": ""Heart of Darkness""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/8",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: GetQuery(nameof(Patch_Update_WithExcludeFieldsTest)),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.OK,
clientRoleHeader: "test_role_with_policy_excluded_fields"
);
}
/// <summary>
/// Test to validate that for a PATCH API request that results in a successful insert operation,
/// the response returned takes into account that no read action is configured for the role.
/// URI Path: Contains a Non-existent PK.
/// Req Body: Valid Parameter with intended insert data.
/// Expects:
/// Status: 201 Created since the PATCH results in an insert operation
/// Response Body: Empty because the role policy_tester_noread has no read action configured.
/// </summary>
[TestMethod]
public virtual async Task PatchInsert_NoReadTest()
{
string requestBody = @"
{
""piecesAvailable"": 4,
""categoryName"": ""SciFi"",
""piecesRequired"": 4
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/0/pieceid/7",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchInsert_NoReadTest"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
clientRoleHeader: "test_role_with_noread",
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests that for a PATCH API request that results in a successful insert operation,
/// the response returned takes into account the include and exclude fields configured for the read action.
/// URI Path: Contains a non-existent PK.
/// Req Body: Valid Parameter with intended update.
/// Expects:
/// Status: 201 Created as PATCH results in an insert operation.
/// Response Body: Does not contain the categoryName field as it is excluded in the read configuration.
/// </summary>
[TestMethod]
public virtual async Task Patch_Insert_WithExcludeFieldsTest()
{
string requestBody = @"
{
""piecesAvailable"": 4,
""categoryName"": ""SciFi"",
""piecesRequired"": 4
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/0/pieceid/7",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("Patch_Insert_WithExcludeFieldsTest"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
clientRoleHeader: "test_role_with_excluded_fields",
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests that for a PATCH API request that results in a successful insert operation,
/// the response returned takes into account the database policy configured for the read action.
/// URI Path: Contains a non-existent PK.
/// Req Body: Valid Parameter with intended update.
/// Expects:
/// Status: 201 Created as PATCH results in an insert operation.
/// Response Body: Empty. The database policy configured for the read action states that piecesAvailable cannot be 0.
/// Since, the PATCH request inserts a record with piecesAvailable = 0, the response must be empty.
/// </summary>
[TestMethod]
public virtual async Task Patch_Insert_WithReadDatabasePolicyTest()
{
string requestBody = @"
{
""piecesAvailable"": 0,
""categoryName"": ""SciFi"",
""piecesRequired"": 4
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/0/pieceid/7",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("PatchInsert_NoReadTest"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
clientRoleHeader: "test_role_with_policy_excluded_fields",
expectedLocationHeader: string.Empty
);
}
/// <summary>
/// Tests that for a PATCH API request that results in a successful insert operation,
/// the response returned takes into account the database policy and the include/exlude fields
/// configured for the read action.
/// URI Path: Contains a non-existent PK.
/// Req Body: Valid Parameter with intended update.
/// Expects:
/// Status: 201 Created as PATCH results in an insert operation.
/// Response Body: Non-empty and should not contain the categoryName. The database policy configured for the read action states that piecesAvailable cannot be 0.
/// But, the PATCH request inserts a record with piecesAvailable = 4, so the policy is unsatisfied. Hence, the response should be non-empty.
/// The policy also excludes the categoryName field, so the response should not contain the categoryName field.
/// </summary>
[TestMethod]
public virtual async Task Patch_Insert_WithReadDatabasePolicyUnsatisfiedTest()
{
string requestBody = @"
{
""piecesAvailable"": 4,
""categoryName"": ""SciFi"",
""piecesRequired"": 4
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/0/pieceid/7",
queryString: null,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: GetQuery("Patch_Insert_WithExcludeFieldsTest"),
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
expectedStatusCode: HttpStatusCode.Created,
clientRoleHeader: "test_role_with_policy_excluded_fields",
expectedLocationHeader: string.Empty
);
}
#endregion
#region Negative Tests
/// <summary>
/// Tests REST PatchOne which results in insert.
/// URI Path: PK of record that does not exist, Schema PK is autogenerated.
/// Req Body: Valid Parameters.
/// Expects: 500 Server error (Not 400 since we don't catch DB specific Identity() insert errors).
/// </summary>
/// <returns></returns>
[TestMethod]
public virtual async Task PatchOne_Insert_PKAutoGen_Test()
{
string requestBody = @"
{
""title"": ""The Hobbit Returns to The Shire""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/1000",
queryString: null,
entityNameOrPath: _integrationEntityName,
sqlQuery: null,
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
exceptionExpected: true,
expectedErrorMessage: $"Cannot perform INSERT and could not find {_integrationEntityName} with primary key <id: 1000> to perform UPDATE on.",
expectedStatusCode: HttpStatusCode.NotFound,
expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.ItemNotFound.ToString()
);
}
/// <summary>
/// Tests REST PatchOne which results in insert
/// URI Path: PK of record that does not exist.
/// Req Body: Missing non-nullable parameters.
/// Expects: BadRequest, so no sqlQuery used since req does not touch DB.
/// </summary>
/// <returns></returns>
[TestMethod]
public virtual async Task PatchOne_Insert_WithoutNonNullableField_Test()
{
string requestBody = @"
{
""issue_number"": ""1234""
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/1000",
queryString: null,
entityNameOrPath: _integration_NonAutoGenPK_EntityName,
sqlQuery: null,
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
exceptionExpected: true,
expectedErrorMessage: $"Cannot perform INSERT and could not find {_integration_NonAutoGenPK_EntityName} with primary key <id: 1000> to perform UPDATE on.",
expectedStatusCode: HttpStatusCode.NotFound,
expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.ItemNotFound.ToString()
);
}
/// <summary>
/// Tests the PatchOne functionality with a REST PATCH request using
/// headers that include as a key "If-Match" with an item that does not exist,
/// resulting in a DataApiBuilderException with 404 status code with .
/// </summary>
[TestMethod]
public virtual async Task PatchOne_Update_IfMatchHeaders_NoUpdatePerformed_Test()
{
Dictionary<string, StringValues> headerDictionary = new();
headerDictionary.Add("If-Match", "*");
headerDictionary.Add("StatusCode", "200");
string requestBody = @"
{
""title"": ""The Return of the King"",
""publisher_id"": 1234
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "id/24",
queryString: string.Empty,
entityNameOrPath: _integrationEntityName,
sqlQuery: string.Empty,
operationType: EntityActionOperation.UpsertIncremental,
headers: new HeaderDictionary(headerDictionary),
requestBody: requestBody,
exceptionExpected: true,
expectedErrorMessage: "No Update could be performed, record not found",
expectedStatusCode: HttpStatusCode.NotFound,
expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString()
);
}
/// <summary>
/// Verifies that we throw exception when field
/// provided to upsert is an exposed name that
/// maps to a backing column name that does not
/// exist in the table.
/// </summary>
/// <returns></returns>
[TestMethod]
public async Task PatchTestWithInvalidMapping()
{
string requestBody = @"
{
""hazards"": ""black mold"",
""region"": ""Pacific North West""
}";
string expectedLocationHeader = $"speciedid/3";
await SetupAndRunRestApiTest(
primaryKeyRoute: expectedLocationHeader,
queryString: string.Empty,
entityNameOrPath: _integrationBrokenMappingEntity,
sqlQuery: string.Empty,
operationType: EntityActionOperation.UpsertIncremental,
exceptionExpected: true,
requestBody: requestBody,
expectedErrorMessage: "Invalid request body. Either insufficient or extra fields supplied.",
expectedStatusCode: HttpStatusCode.BadRequest,
expectedSubStatusCode: "BadRequest",
expectedLocationHeader: expectedLocationHeader
);
}
/// <summary>
/// Tests the Patch functionality with a REST PATCH request
/// with the request body having null value for non-nullable column
/// We expect a failure and so no sql query is provided.
/// </summary>
[TestMethod]
public virtual async Task PatchOneWithNonNullableFieldAsNull()
{
//Negative test case for Patch resulting in a failed update
string requestBody = @"
{
""piecesAvailable"": ""3"",
""piecesRequired"": ""1"",
""categoryName"":null
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/2/pieceid/1",
queryString: string.Empty,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: string.Empty,
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
exceptionExpected: true,
expectedErrorMessage: "Invalid value for field categoryName in request body.",
expectedStatusCode: HttpStatusCode.BadRequest
);
//Negative test case for Patch resulting in a failed insert
requestBody = @"
{
""piecesAvailable"": ""3"",
""piecesRequired"": ""1"",
""categoryName"":null
}";
await SetupAndRunRestApiTest(
primaryKeyRoute: "categoryid/3/pieceid/1",
queryString: string.Empty,
entityNameOrPath: _Composite_NonAutoGenPK_EntityPath,
sqlQuery: string.Empty,
operationType: EntityActionOperation.UpsertIncremental,
requestBody: requestBody,
exceptionExpected: true,
expectedErrorMessage: "Invalid value for field categoryName in request body.",
expectedStatusCode: HttpStatusCode.BadRequest
);
}
/// <summary>
/// Verifies that we throw an exception when an extraneous field that does not map to a backing column in the table
/// is provided in the request body for a PATCH operation. This test validates the behavior of rest.request-body-strict when it is:
/// 1. Included in runtime config (and set to true)
/// 2. Excluded from runtime config(defaults to true)
/// </summary>