forked from steipete/agent-rules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswift-observation.mdc
More file actions
7033 lines (4134 loc) · 292 KB
/
swift-observation.mdc
File metadata and controls
7033 lines (4134 loc) · 292 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
---
description: Swift Observation framework documentation and usage patterns for reactive programming
globs: "**/*.swift"
alwaysApply: false
---
# https://developer.apple.com/documentation/testing llms-full.txt
## Swift Testing Overview
[Skip Navigation](https://developer.apple.com/documentation/testing#app-main)
Framework
# Swift Testing
Create and run tests for your Swift packages and Xcode projects.
Swift 6.0+Xcode 16.0+
## [Overview](https://developer.apple.com/documentation/testing\#Overview)

With Swift Testing you leverage powerful and expressive capabilities of the Swift programming language to develop tests with more confidence and less code. The library integrates seamlessly with Swift Package Manager testing workflow, supports flexible test organization, customizable metadata, and scalable test execution.
- Define test functions almost anywhere with a single attribute.
- Group related tests into hierarchies using Swift’s type system.
- Integrate seamlessly with Swift concurrency.
- Parameterize test functions across wide ranges of inputs.
- Enable tests dynamically depending on runtime conditions.
- Parallelize tests in-process.
- Categorize tests using tags.
- Associate bugs directly with the tests that verify their fixes or reproduce their problems.
#### [Related videos](https://developer.apple.com/documentation/testing\#Related-videos)
[\\
\\
Meet Swift Testing](https://developer.apple.com/videos/play/wwdc2024/10179)
[\\
\\
Go further with Swift Testing](https://developer.apple.com/videos/play/wwdc2024/10195)
## [Topics](https://developer.apple.com/documentation/testing\#topics)
### [Essentials](https://developer.apple.com/documentation/testing\#Essentials)
[Defining test functions](https://developer.apple.com/documentation/testing/definingtests)
Define a test function to validate that code is working correctly.
[Organizing test functions with suite types](https://developer.apple.com/documentation/testing/organizingtests)
Organize tests into test suites.
[Migrating a test from XCTest](https://developer.apple.com/documentation/testing/migratingfromxctest)
Migrate an existing test method or test class written using XCTest.
[`macro Test(String?, any TestTrait...)`](https://developer.apple.com/documentation/testing/test(_:_:))
Declare a test.
[`struct Test`](https://developer.apple.com/documentation/testing/test)
A type representing a test or suite.
[`macro Suite(String?, any SuiteTrait...)`](https://developer.apple.com/documentation/testing/suite(_:_:))
Declare a test suite.
### [Test parameterization](https://developer.apple.com/documentation/testing\#Test-parameterization)
[Implementing parameterized tests](https://developer.apple.com/documentation/testing/parameterizedtesting)
Specify different input parameters to generate multiple test cases from a test function.
[`macro Test<C>(String?, any TestTrait..., arguments: C)`](https://developer.apple.com/documentation/testing/test(_:_:arguments:)-8kn7a)
Declare a test parameterized over a collection of values.
[`macro Test<C1, C2>(String?, any TestTrait..., arguments: C1, C2)`](https://developer.apple.com/documentation/testing/test(_:_:arguments:_:))
Declare a test parameterized over two collections of values.
[`macro Test<C1, C2>(String?, any TestTrait..., arguments: Zip2Sequence<C1, C2>)`](https://developer.apple.com/documentation/testing/test(_:_:arguments:)-3rzok)
Declare a test parameterized over two zipped collections of values.
[`protocol CustomTestArgumentEncodable`](https://developer.apple.com/documentation/testing/customtestargumentencodable)
A protocol for customizing how arguments passed to parameterized tests are encoded, which is used to match against when running specific arguments.
[`struct Case`](https://developer.apple.com/documentation/testing/test/case)
A single test case from a parameterized [`Test`](https://developer.apple.com/documentation/testing/test).
### [Behavior validation](https://developer.apple.com/documentation/testing\#Behavior-validation)
[API Reference\\
Expectations and confirmations](https://developer.apple.com/documentation/testing/expectations)
Check for expected values, outcomes, and asynchronous events in tests.
[API Reference\\
Known issues](https://developer.apple.com/documentation/testing/known-issues)
Highlight known issues when running tests.
### [Test customization](https://developer.apple.com/documentation/testing\#Test-customization)
[API Reference\\
Traits](https://developer.apple.com/documentation/testing/traits)
Annotate test functions and suites, and customize their behavior.
Current page is Swift Testing
## Adding Tags to Tests
[Skip Navigation](https://developer.apple.com/documentation/testing/addingtags#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- [Traits](https://developer.apple.com/documentation/testing/traits)
- Adding tags to tests
Article
# Adding tags to tests
Use tags to provide semantic information for organization, filtering, and customizing appearances.
## [Overview](https://developer.apple.com/documentation/testing/addingtags\#Overview)
A complex package or project may contain hundreds or thousands of tests and suites. Some subset of those tests may share some common facet, such as being _critical_ or _flaky_. The testing library includes a type of trait called _tags_ that you can add to group and categorize tests.
Tags are different from test suites: test suites impose structure on test functions at the source level, while tags provide semantic information for a test that can be shared with any number of other tests across test suites, source files, and even test targets.
## [Add a tag](https://developer.apple.com/documentation/testing/addingtags\#Add-a-tag)
To add a tag to a test, use the [`tags(_:)`](https://developer.apple.com/documentation/testing/trait/tags(_:)) trait. This trait takes a sequence of tags as its argument, and those tags are then applied to the corresponding test at runtime. If any tags are applied to a test suite, then all tests in that suite inherit those tags.
The testing library doesn’t assign any semantic meaning to any tags, nor does the presence or absence of tags affect how the testing library runs tests.
Tags themselves are instances of [`Tag`](https://developer.apple.com/documentation/testing/tag) and expressed as named constants declared as static members of [`Tag`](https://developer.apple.com/documentation/testing/tag). To declare a named constant tag, use the [`Tag()`](https://developer.apple.com/documentation/testing/tag()) macro:
```
extension Tag {
@Tag static var legallyRequired: Self
}
@Test("Vendor's license is valid", .tags(.legallyRequired))
func licenseValid() { ... }
```
If two tags with the same name ( `legallyRequired` in the above example) are declared in different files, modules, or other contexts, the testing library treats them as equivalent.
If it’s important for a tag to be distinguished from similar tags declared elsewhere in a package or project (or its dependencies), use reverse-DNS naming to create a unique Swift symbol name for your tag:
```
extension Tag {
enum com_example_foodtruck {}
}
extension Tag.com_example_foodtruck {
@Tag static var extraSpecial: Tag
}
@Test(
"Extra Special Sauce recipe is secret",
.tags(.com_example_foodtruck.extraSpecial)
)
func secretSauce() { ... }
```
### [Where tags can be declared](https://developer.apple.com/documentation/testing/addingtags\#Where-tags-can-be-declared)
Tags must always be declared as members of [`Tag`](https://developer.apple.com/documentation/testing/tag) in an extension to that type or in a type nested within [`Tag`](https://developer.apple.com/documentation/testing/tag). Redeclaring a tag under a second name has no effect and the additional name will not be recognized by the testing library. The following example is unsupported:
```
extension Tag {
@Tag static var legallyRequired: Self // ✅ OK: Declaring a new tag.
static var requiredByLaw: Self { // ❌ ERROR: This tag name isn't
// recognized at runtime.
legallyRequired
}
}
```
If a tag is declared as a named constant outside of an extension to the [`Tag`](https://developer.apple.com/documentation/testing/tag) type (for example, at the root of a file or in another unrelated type declaration), it cannot be applied to test functions or test suites. The following declarations are unsupported:
```
@Tag let needsKetchup: Self // ❌ ERROR: Tags must be declared in an extension
// to Tag.
struct Food {
@Tag var needsMustard: Self // ❌ ERROR: Tags must be declared in an extension
// to Tag.
}
```
## [See Also](https://developer.apple.com/documentation/testing/addingtags\#see-also)
### [Annotating tests](https://developer.apple.com/documentation/testing/addingtags\#Annotating-tests)
[Adding comments to tests](https://developer.apple.com/documentation/testing/addingcomments)
Add comments to provide useful information about tests.
[Associating bugs with tests](https://developer.apple.com/documentation/testing/associatingbugs)
Associate bugs uncovered or verified by tests.
[Interpreting bug identifiers](https://developer.apple.com/documentation/testing/bugidentifiers)
Examine how the testing library interprets bug identifiers provided by developers.
[`macro Tag()`](https://developer.apple.com/documentation/testing/tag())
Declare a tag that can be applied to a test function or test suite.
[`static func bug(String, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:_:))
Constructs a bug to track with a test.
[`static func bug(String?, id: String, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-10yf5)
Constructs a bug to track with a test.
[`static func bug(String?, id: some Numeric, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-3vtpl)
Constructs a bug to track with a test.
Current page is Adding tags to tests
## Swift Test Overview
[Skip Navigation](https://developer.apple.com/documentation/testing/test#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- Test
Structure
# Test
A type representing a test or suite.
iOSiPadOSMac CatalystmacOStvOSvisionOSwatchOSSwift 6.0+Xcode 16.0+
```
struct Test
```
## [Overview](https://developer.apple.com/documentation/testing/test\#overview)
An instance of this type may represent:
- A type containing zero or more tests (i.e. a _test suite_);
- An individual test function (possibly contained within a type); or
- A test function parameterized over one or more sequences of inputs.
Two instances of this type are considered to be equal if the values of their [`id`](https://developer.apple.com/documentation/testing/test/id-swift.property) properties are equal.
## [Topics](https://developer.apple.com/documentation/testing/test\#topics)
### [Structures](https://developer.apple.com/documentation/testing/test\#Structures)
[`struct Case`](https://developer.apple.com/documentation/testing/test/case)
A single test case from a parameterized [`Test`](https://developer.apple.com/documentation/testing/test).
### [Instance Properties](https://developer.apple.com/documentation/testing/test\#Instance-Properties)
[`var associatedBugs: [Bug]`](https://developer.apple.com/documentation/testing/test/associatedbugs)
The set of bugs associated with this test.
[`var comments: [Comment]`](https://developer.apple.com/documentation/testing/test/comments)
The complete set of comments about this test from all of its traits.
[`var displayName: String?`](https://developer.apple.com/documentation/testing/test/displayname)
The customized display name of this instance, if specified.
[`var isParameterized: Bool`](https://developer.apple.com/documentation/testing/test/isparameterized)
Whether or not this test is parameterized.
[`var isSuite: Bool`](https://developer.apple.com/documentation/testing/test/issuite)
Whether or not this instance is a test suite containing other tests.
[`var name: String`](https://developer.apple.com/documentation/testing/test/name)
The name of this instance.
[`var sourceLocation: SourceLocation`](https://developer.apple.com/documentation/testing/test/sourcelocation)
The source location of this test.
[`var tags: Set<Tag>`](https://developer.apple.com/documentation/testing/test/tags)
The complete, unique set of tags associated with this test.
[`var timeLimit: Duration?`](https://developer.apple.com/documentation/testing/test/timelimit)
The maximum amount of time this test’s cases may run for.
[`var traits: [any Trait]`](https://developer.apple.com/documentation/testing/test/traits)
The set of traits added to this instance when it was initialized.
### [Type Properties](https://developer.apple.com/documentation/testing/test\#Type-Properties)
[`static var current: Test?`](https://developer.apple.com/documentation/testing/test/current)
The test that is running on the current task, if any.
### [Default Implementations](https://developer.apple.com/documentation/testing/test\#Default-Implementations)
[API Reference\\
Equatable Implementations](https://developer.apple.com/documentation/testing/test/equatable-implementations)
[API Reference\\
Hashable Implementations](https://developer.apple.com/documentation/testing/test/hashable-implementations)
[API Reference\\
Identifiable Implementations](https://developer.apple.com/documentation/testing/test/identifiable-implementations)
## [Relationships](https://developer.apple.com/documentation/testing/test\#relationships)
### [Conforms To](https://developer.apple.com/documentation/testing/test\#conforms-to)
- [`Copyable`](https://developer.apple.com/documentation/Swift/Copyable)
- [`Equatable`](https://developer.apple.com/documentation/Swift/Equatable)
- [`Hashable`](https://developer.apple.com/documentation/Swift/Hashable)
- [`Identifiable`](https://developer.apple.com/documentation/Swift/Identifiable)
- [`Sendable`](https://developer.apple.com/documentation/Swift/Sendable)
## [See Also](https://developer.apple.com/documentation/testing/test\#see-also)
### [Essentials](https://developer.apple.com/documentation/testing/test\#Essentials)
[Defining test functions](https://developer.apple.com/documentation/testing/definingtests)
Define a test function to validate that code is working correctly.
[Organizing test functions with suite types](https://developer.apple.com/documentation/testing/organizingtests)
Organize tests into test suites.
[Migrating a test from XCTest](https://developer.apple.com/documentation/testing/migratingfromxctest)
Migrate an existing test method or test class written using XCTest.
[`macro Test(String?, any TestTrait...)`](https://developer.apple.com/documentation/testing/test(_:_:))
Declare a test.
[`macro Suite(String?, any SuiteTrait...)`](https://developer.apple.com/documentation/testing/suite(_:_:))
Declare a test suite.
Current page is Test
## Adding Comments to Tests
[Skip Navigation](https://developer.apple.com/documentation/testing/addingcomments#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- [Traits](https://developer.apple.com/documentation/testing/traits)
- Adding comments to tests
Article
# Adding comments to tests
Add comments to provide useful information about tests.
## [Overview](https://developer.apple.com/documentation/testing/addingcomments\#Overview)
It’s often useful to add comments to code to:
- Provide context or background information about the code’s purpose
- Explain how complex code implemented
- Include details which may be helpful when diagnosing issues
Test code is no different and can benefit from explanatory code comments, but often test issues are shown in places where the source code of the test is unavailable such as in continuous integration (CI) interfaces or in log files.
Seeing comments related to tests in these contexts can help diagnose issues more quickly. Comments can be added to test declarations and the testing library will automatically capture and show them when issues are recorded.
## [Add a code comment to a test](https://developer.apple.com/documentation/testing/addingcomments\#Add-a-code-comment-to-a-test)
To include a comment on a test or suite, write an ordinary Swift code comment immediately before its `@Test` or `@Suite` attribute:
```
// Assumes the standard lunch menu includes a taco
@Test func lunchMenu() {
let foodTruck = FoodTruck(
menu: .lunch,
ingredients: [.tortillas, .cheese]
)
#expect(foodTruck.menu.contains { $0 is Taco })
}
```
The comment, `// Assumes the standard lunch menu includes a taco`, is added to the test.
The following language comment styles are supported:
| Syntax | Style |
| --- | --- |
| `// ...` | Line comment |
| `/// ...` | Documentation line comment |
| `/* ... */` | Block comment |
| `/** ... */` | Documentation block comment |
### [Comment formatting](https://developer.apple.com/documentation/testing/addingcomments\#Comment-formatting)
Test comments which are automatically added from source code comments preserve their original formatting, including any prefixes like `//` or `/**`. This is because the whitespace and formatting of comments can be meaningful in some circumstances or aid in understanding the comment — for example, when a comment includes an example code snippet or diagram.
## [Use test comments effectively](https://developer.apple.com/documentation/testing/addingcomments\#Use-test-comments-effectively)
As in normal code, comments on tests are generally most useful when they:
- Add information that isn’t obvious from reading the code
- Provide useful information about the operation or motivation of a test
If a test is related to a bug or issue, consider using the [`Bug`](https://developer.apple.com/documentation/testing/bug) trait instead of comments. For more information, see [Associating bugs with tests](https://developer.apple.com/documentation/testing/associatingbugs).
## [See Also](https://developer.apple.com/documentation/testing/addingcomments\#see-also)
### [Annotating tests](https://developer.apple.com/documentation/testing/addingcomments\#Annotating-tests)
[Adding tags to tests](https://developer.apple.com/documentation/testing/addingtags)
Use tags to provide semantic information for organization, filtering, and customizing appearances.
[Associating bugs with tests](https://developer.apple.com/documentation/testing/associatingbugs)
Associate bugs uncovered or verified by tests.
[Interpreting bug identifiers](https://developer.apple.com/documentation/testing/bugidentifiers)
Examine how the testing library interprets bug identifiers provided by developers.
[`macro Tag()`](https://developer.apple.com/documentation/testing/tag())
Declare a tag that can be applied to a test function or test suite.
[`static func bug(String, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:_:))
Constructs a bug to track with a test.
[`static func bug(String?, id: String, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-10yf5)
Constructs a bug to track with a test.
[`static func bug(String?, id: some Numeric, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-3vtpl)
Constructs a bug to track with a test.
Current page is Adding comments to tests
## Organizing Test Functions
[Skip Navigation](https://developer.apple.com/documentation/testing/organizingtests#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- Organizing test functions with suite types
Article
# Organizing test functions with suite types
Organize tests into test suites.
## [Overview](https://developer.apple.com/documentation/testing/organizingtests\#Overview)
When working with a large selection of test functions, it can be helpful to organize them into test suites.
A test function can be added to a test suite in one of two ways:
- By placing it in a Swift type.
- By placing it in a Swift type and annotating that type with the `@Suite` attribute.
The `@Suite` attribute isn’t required for the testing library to recognize that a type contains test functions, but adding it allows customization of a test suite’s appearance in the IDE and at the command line. If a trait such as [`tags(_:)`](https://developer.apple.com/documentation/testing/trait/tags(_:)) or [`disabled(_:sourceLocation:)`](https://developer.apple.com/documentation/testing/trait/disabled(_:sourcelocation:)) is applied to a test suite, it’s automatically inherited by the tests contained in the suite.
In addition to containing test functions and any other members that a Swift type might contain, test suite types can also contain additional test suites nested within them. To add a nested test suite type, simply declare an additional type within the scope of the outer test suite type.
By default, tests contained within a suite run in parallel with each other. For more information about test parallelization, see [Running tests serially or in parallel](https://developer.apple.com/documentation/testing/parallelization).
### [Customize a suite’s name](https://developer.apple.com/documentation/testing/organizingtests\#Customize-a-suites-name)
To customize a test suite’s name, supply a string literal as an argument to the `@Suite` attribute:
```
@Suite("Food truck tests") struct FoodTruckTests {
@Test func foodTruckExists() { ... }
}
```
To further customize the appearance and behavior of a test function, use [traits](https://developer.apple.com/documentation/testing/traits) such as [`tags(_:)`](https://developer.apple.com/documentation/testing/trait/tags(_:)).
## [Test functions in test suite types](https://developer.apple.com/documentation/testing/organizingtests\#Test-functions-in-test-suite-types)
If a type contains a test function declared as an instance method (that is, without either the `static` or `class` keyword), the testing library calls that test function at runtime by initializing an instance of the type, then calling the test function on that instance. If a test suite type contains multiple test functions declared as instance methods, each one is called on a distinct instance of the type. Therefore, the following test suite and test function:
```
@Suite struct FoodTruckTests {
@Test func foodTruckExists() { ... }
}
```
Are equivalent to:
```
@Suite struct FoodTruckTests {
func foodTruckExists() { ... }
@Test static func staticFoodTruckExists() {
let instance = FoodTruckTests()
instance.foodTruckExists()
}
}
```
### [Constraints on test suite types](https://developer.apple.com/documentation/testing/organizingtests\#Constraints-on-test-suite-types)
When using a type as a test suite, it’s subject to some constraints that are not otherwise applied to Swift types.
#### [An initializer may be required](https://developer.apple.com/documentation/testing/organizingtests\#An-initializer-may-be-required)
If a type contains test functions declared as instance methods, it must be possible to initialize an instance of the type with a zero-argument initializer. The initializer may be any combination of:
- implicit or explicit
- synchronous or asynchronous
- throwing or non-throwing
- `private`, `fileprivate`, `internal`, `package`, or `public`
For example:
```
@Suite struct FoodTruckTests {
var batteryLevel = 100
@Test func foodTruckExists() { ... } // ✅ OK: The type has an implicit init().
}
@Suite struct CashRegisterTests {
private init(cashOnHand: Decimal = 0.0) async throws { ... }
@Test func calculateSalesTax() { ... } // ✅ OK: The type has a callable init().
}
struct MenuTests {
var foods: [Food]
var prices: [Food: Decimal]
@Test static func specialOfTheDay() { ... } // ✅ OK: The function is static.
@Test func orderAllFoods() { ... } // ❌ ERROR: The suite type requires init().
}
```
The compiler emits an error when presented with a test suite that doesn’t meet this requirement.
### [Test suite types must always be available](https://developer.apple.com/documentation/testing/organizingtests\#Test-suite-types-must-always-be-available)
Although `@available` can be applied to a test function to limit its availability at runtime, a test suite type (and any types that contain it) must _not_ be annotated with the `@available` attribute:
```
@Suite struct FoodTruckTests { ... } // ✅ OK: The type is always available.
@available(macOS 11.0, *) // ❌ ERROR: The suite type must always be available.
@Suite struct CashRegisterTests { ... }
@available(macOS 11.0, *) struct MenuItemTests { // ❌ ERROR: The suite type's
// containing type must always
// be available too.
@Suite struct BurgerTests { ... }
}
```
The compiler emits an error when presented with a test suite that doesn’t meet this requirement.
## [See Also](https://developer.apple.com/documentation/testing/organizingtests\#see-also)
### [Essentials](https://developer.apple.com/documentation/testing/organizingtests\#Essentials)
[Defining test functions](https://developer.apple.com/documentation/testing/definingtests)
Define a test function to validate that code is working correctly.
[Migrating a test from XCTest](https://developer.apple.com/documentation/testing/migratingfromxctest)
Migrate an existing test method or test class written using XCTest.
[`macro Test(String?, any TestTrait...)`](https://developer.apple.com/documentation/testing/test(_:_:))
Declare a test.
[`struct Test`](https://developer.apple.com/documentation/testing/test)
A type representing a test or suite.
[`macro Suite(String?, any SuiteTrait...)`](https://developer.apple.com/documentation/testing/suite(_:_:))
Declare a test suite.
Current page is Organizing test functions with suite types
## Custom Test Argument Encoding
[Skip Navigation](https://developer.apple.com/documentation/testing/customtestargumentencodable#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- CustomTestArgumentEncodable
Protocol
# CustomTestArgumentEncodable
A protocol for customizing how arguments passed to parameterized tests are encoded, which is used to match against when running specific arguments.
iOSiPadOSMac CatalystmacOStvOSvisionOSwatchOSSwift 6.0+Xcode 16.0+
```
protocol CustomTestArgumentEncodable : Sendable
```
## [Mentioned in](https://developer.apple.com/documentation/testing/customtestargumentencodable\#mentions)
[Implementing parameterized tests](https://developer.apple.com/documentation/testing/parameterizedtesting)
## [Overview](https://developer.apple.com/documentation/testing/customtestargumentencodable\#overview)
The testing library checks whether a test argument conforms to this protocol, or any of several other known protocols, when running selected test cases. When a test argument conforms to this protocol, that conformance takes highest priority, and the testing library will then call [`encodeTestArgument(to:)`](https://developer.apple.com/documentation/testing/customtestargumentencodable/encodetestargument(to:)) on the argument. A type that conforms to this protocol is not required to conform to either `Encodable` or `Decodable`.
See [Implementing parameterized tests](https://developer.apple.com/documentation/testing/parameterizedtesting) for a list of the other supported ways to allow running selected test cases.
## [Topics](https://developer.apple.com/documentation/testing/customtestargumentencodable\#topics)
### [Instance Methods](https://developer.apple.com/documentation/testing/customtestargumentencodable\#Instance-Methods)
[`func encodeTestArgument(to: some Encoder) throws`](https://developer.apple.com/documentation/testing/customtestargumentencodable/encodetestargument(to:))
Encode this test argument.
**Required**
## [Relationships](https://developer.apple.com/documentation/testing/customtestargumentencodable\#relationships)
### [Inherits From](https://developer.apple.com/documentation/testing/customtestargumentencodable\#inherits-from)
- [`Sendable`](https://developer.apple.com/documentation/Swift/Sendable)
## [See Also](https://developer.apple.com/documentation/testing/customtestargumentencodable\#see-also)
### [Related Documentation](https://developer.apple.com/documentation/testing/customtestargumentencodable\#Related-Documentation)
[Implementing parameterized tests](https://developer.apple.com/documentation/testing/parameterizedtesting)
Specify different input parameters to generate multiple test cases from a test function.
### [Test parameterization](https://developer.apple.com/documentation/testing/customtestargumentencodable\#Test-parameterization)
[Implementing parameterized tests](https://developer.apple.com/documentation/testing/parameterizedtesting)
Specify different input parameters to generate multiple test cases from a test function.
[`macro Test<C>(String?, any TestTrait..., arguments: C)`](https://developer.apple.com/documentation/testing/test(_:_:arguments:)-8kn7a)
Declare a test parameterized over a collection of values.
[`macro Test<C1, C2>(String?, any TestTrait..., arguments: C1, C2)`](https://developer.apple.com/documentation/testing/test(_:_:arguments:_:))
Declare a test parameterized over two collections of values.
[`macro Test<C1, C2>(String?, any TestTrait..., arguments: Zip2Sequence<C1, C2>)`](https://developer.apple.com/documentation/testing/test(_:_:arguments:)-3rzok)
Declare a test parameterized over two zipped collections of values.
[`struct Case`](https://developer.apple.com/documentation/testing/test/case)
A single test case from a parameterized [`Test`](https://developer.apple.com/documentation/testing/test).
Current page is CustomTestArgumentEncodable
## Defining Test Functions
[Skip Navigation](https://developer.apple.com/documentation/testing/definingtests#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- Defining test functions
Article
# Defining test functions
Define a test function to validate that code is working correctly.
## [Overview](https://developer.apple.com/documentation/testing/definingtests\#Overview)
Defining a test function for a Swift package or project is straightforward.
### [Import the testing library](https://developer.apple.com/documentation/testing/definingtests\#Import-the-testing-library)
To import the testing library, add the following to the Swift source file that contains the test:
```
import Testing
```
### [Declare a test function](https://developer.apple.com/documentation/testing/definingtests\#Declare-a-test-function)
To declare a test function, write a Swift function declaration that doesn’t take any arguments, then prefix its name with the `@Test` attribute:
```
@Test func foodTruckExists() {
// Test logic goes here.
}
```
This test function can be present at file scope or within a type. A type containing test functions is automatically a _test suite_ and can be optionally annotated with the `@Suite` attribute. For more information about suites, see [Organizing test functions with suite types](https://developer.apple.com/documentation/testing/organizingtests).
Note that, while this function is a valid test function, it doesn’t actually perform any action or test any code. To check for expected values and outcomes in test functions, add [expectations](https://developer.apple.com/documentation/testing/expectations) to the test function.
### [Customize a test’s name](https://developer.apple.com/documentation/testing/definingtests\#Customize-a-tests-name)
To customize a test function’s name as presented in an IDE or at the command line, supply a string literal as an argument to the `@Test` attribute:
```
@Test("Food truck exists") func foodTruckExists() { ... }
```
To further customize the appearance and behavior of a test function, use [traits](https://developer.apple.com/documentation/testing/traits) such as [`tags(_:)`](https://developer.apple.com/documentation/testing/trait/tags(_:)).
### [Write concurrent or throwing tests](https://developer.apple.com/documentation/testing/definingtests\#Write-concurrent-or-throwing-tests)
As with other Swift functions, test functions can be marked `async` and `throws` to annotate them as concurrent or throwing, respectively. If a test is only safe to run in the main actor’s execution context (that is, from the main thread of the process), it can be annotated `@MainActor`:
```
@Test @MainActor func foodTruckExists() async throws { ... }
```
### [Limit the availability of a test](https://developer.apple.com/documentation/testing/definingtests\#Limit-the-availability-of-a-test)
If a test function can only run on newer versions of an operating system or of the Swift language, use the `@available` attribute when declaring it. Use the `message` argument of the `@available` attribute to specify a message to log if a test is unable to run due to limited availability:
```
@available(macOS 11.0, *)
@available(swift, introduced: 8.0, message: "Requires Swift 8.0 features to run")
@Test func foodTruckExists() { ... }
```
## [See Also](https://developer.apple.com/documentation/testing/definingtests\#see-also)
### [Essentials](https://developer.apple.com/documentation/testing/definingtests\#Essentials)
[Organizing test functions with suite types](https://developer.apple.com/documentation/testing/organizingtests)
Organize tests into test suites.
[Migrating a test from XCTest](https://developer.apple.com/documentation/testing/migratingfromxctest)
Migrate an existing test method or test class written using XCTest.
[`macro Test(String?, any TestTrait...)`](https://developer.apple.com/documentation/testing/test(_:_:))
Declare a test.
[`struct Test`](https://developer.apple.com/documentation/testing/test)
A type representing a test or suite.
[`macro Suite(String?, any SuiteTrait...)`](https://developer.apple.com/documentation/testing/suite(_:_:))
Declare a test suite.
Current page is Defining test functions
## Interpreting Bug Identifiers
[Skip Navigation](https://developer.apple.com/documentation/testing/bugidentifiers#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- [Traits](https://developer.apple.com/documentation/testing/traits)
- Interpreting bug identifiers
Article
# Interpreting bug identifiers
Examine how the testing library interprets bug identifiers provided by developers.
## [Overview](https://developer.apple.com/documentation/testing/bugidentifiers\#Overview)
The testing library supports two distinct ways to identify a bug:
1. A URL linking to more information about the bug; and
2. A unique identifier in the bug’s associated bug-tracking system.
A bug may have both an associated URL _and_ an associated unique identifier. It must have at least one or the other in order for the testing library to be able to interpret it correctly.
To create an instance of [`Bug`](https://developer.apple.com/documentation/testing/bug) with a URL, use the [`bug(_:_:)`](https://developer.apple.com/documentation/testing/trait/bug(_:_:)) trait. At compile time, the testing library will validate that the given string can be parsed as a URL according to [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt).
To create an instance of [`Bug`](https://developer.apple.com/documentation/testing/bug) with a bug’s unique identifier, use the [`bug(_:id:_:)`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-10yf5) trait. The testing library does not require that a bug’s unique identifier match any particular format, but will interpret unique identifiers starting with `"FB"` as referring to bugs tracked with the [Apple Feedback Assistant](https://feedbackassistant.apple.com/). For convenience, you can also directly pass an integer as a bug’s identifier using [`bug(_:id:_:)`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-3vtpl).
### [Examples](https://developer.apple.com/documentation/testing/bugidentifiers\#Examples)
| Trait Function | Inferred Bug-Tracking System |
| --- | --- |
| `.bug(id: 12345)` | None |
| `.bug(id: "12345")` | None |
| `.bug("https://www.example.com?id=12345", id: "12345")` | None |
| `.bug("https://github.com/swiftlang/swift/pull/12345")` | [GitHub Issues for the Swift project](https://github.com/swiftlang/swift/issues) |
| `.bug("https://bugs.webkit.org/show_bug.cgi?id=12345")` | [WebKit Bugzilla](https://bugs.webkit.org/) |
| `.bug(id: "FB12345")` | Apple Feedback Assistant |
## [See Also](https://developer.apple.com/documentation/testing/bugidentifiers\#see-also)
### [Annotating tests](https://developer.apple.com/documentation/testing/bugidentifiers\#Annotating-tests)
[Adding tags to tests](https://developer.apple.com/documentation/testing/addingtags)
Use tags to provide semantic information for organization, filtering, and customizing appearances.
[Adding comments to tests](https://developer.apple.com/documentation/testing/addingcomments)
Add comments to provide useful information about tests.
[Associating bugs with tests](https://developer.apple.com/documentation/testing/associatingbugs)
Associate bugs uncovered or verified by tests.
[`macro Tag()`](https://developer.apple.com/documentation/testing/tag())
Declare a tag that can be applied to a test function or test suite.
[`static func bug(String, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:_:))
Constructs a bug to track with a test.
[`static func bug(String?, id: String, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-10yf5)
Constructs a bug to track with a test.
[`static func bug(String?, id: some Numeric, Comment?) -> Self`](https://developer.apple.com/documentation/testing/trait/bug(_:id:_:)-3vtpl)
Constructs a bug to track with a test.
Current page is Interpreting bug identifiers
## Limiting Test Execution Time
[Skip Navigation](https://developer.apple.com/documentation/testing/limitingexecutiontime#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- [Traits](https://developer.apple.com/documentation/testing/traits)
- Limiting the running time of tests
Article
# Limiting the running time of tests
Set limits on how long a test can run for until it fails.
## [Overview](https://developer.apple.com/documentation/testing/limitingexecutiontime\#Overview)
Some tests may naturally run slowly: they may require significant system resources to complete, may rely on downloaded data from a server, or may otherwise be dependent on external factors.
If a test may hang indefinitely or may consume too many system resources to complete effectively, consider setting a time limit for it so that it’s marked as failing if it runs for an excessive amount of time. Use the [`timeLimit(_:)`](https://developer.apple.com/documentation/testing/trait/timelimit(_:)) trait as an upper bound:
```
@Test(.timeLimit(.minutes(60))
func serve100CustomersInOneHour() async {
for _ in 0 ..< 100 {
let customer = await Customer.next()
await customer.order()
...
}
}
```
If the above test function takes longer than an hour (60 x 60 seconds) to execute, the task in which it’s running is [cancelled](https://developer.apple.com/documentation/swift/task/cancel()) and the test fails with an issue of kind [`Issue.Kind.timeLimitExceeded(timeLimitComponents:)`](https://developer.apple.com/documentation/testing/issue/kind-swift.enum/timelimitexceeded(timelimitcomponents:)).
The testing library may adjust the specified time limit for performance reasons or to ensure tests have enough time to run. In particular, a granularity of (by default) one minute is applied to tests. The testing library can also be configured with a maximum time limit per test that overrides any applied time limit traits.
### [Time limits applied to test suites](https://developer.apple.com/documentation/testing/limitingexecutiontime\#Time-limits-applied-to-test-suites)
When a time limit is applied to a test suite, it’s recursively applied to all test functions and child test suites within that suite.
### [Time limits applied to parameterized tests](https://developer.apple.com/documentation/testing/limitingexecutiontime\#Time-limits-applied-to-parameterized-tests)
When a time limit is applied to a parameterized test function, it’s applied to each invocation _separately_ so that if only some arguments cause failures, then successful arguments aren’t incorrectly marked as failing too.
## [See Also](https://developer.apple.com/documentation/testing/limitingexecutiontime\#see-also)
### [Customizing runtime behaviors](https://developer.apple.com/documentation/testing/limitingexecutiontime\#Customizing-runtime-behaviors)
[Enabling and disabling tests](https://developer.apple.com/documentation/testing/enablinganddisabling)
Conditionally enable or disable individual tests before they run.
[`static func enabled(if: @autoclosure () throws -> Bool, Comment?, sourceLocation: SourceLocation) -> Self`](https://developer.apple.com/documentation/testing/trait/enabled(if:_:sourcelocation:))
Constructs a condition trait that disables a test if it returns `false`.
[`static func enabled(Comment?, sourceLocation: SourceLocation, () async throws -> Bool) -> Self`](https://developer.apple.com/documentation/testing/trait/enabled(_:sourcelocation:_:))
Constructs a condition trait that disables a test if it returns `false`.
[`static func disabled(Comment?, sourceLocation: SourceLocation) -> Self`](https://developer.apple.com/documentation/testing/trait/disabled(_:sourcelocation:))
Constructs a condition trait that disables a test unconditionally.
[`static func disabled(if: @autoclosure () throws -> Bool, Comment?, sourceLocation: SourceLocation) -> Self`](https://developer.apple.com/documentation/testing/trait/disabled(if:_:sourcelocation:))
Constructs a condition trait that disables a test if its value is true.
[`static func disabled(Comment?, sourceLocation: SourceLocation, () async throws -> Bool) -> Self`](https://developer.apple.com/documentation/testing/trait/disabled(_:sourcelocation:_:))
Constructs a condition trait that disables a test if its value is true.
[`static func timeLimit(TimeLimitTrait.Duration) -> Self`](https://developer.apple.com/documentation/testing/trait/timelimit(_:))
Construct a time limit trait that causes a test to time out if it runs for too long.
Current page is Limiting the running time of tests
## Test Scoping Protocol
[Skip Navigation](https://developer.apple.com/documentation/testing/testscoping#app-main)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- TestScoping
Protocol
# TestScoping
A protocol that tells the test runner to run custom code before or after it runs a test suite or test function.
Swift 6.1+Xcode 16.3+
```
protocol TestScoping : Sendable
```
## [Overview](https://developer.apple.com/documentation/testing/testscoping\#overview)
Provide custom scope for tests by implementing the [`scopeProvider(for:testCase:)`](https://developer.apple.com/documentation/testing/trait/scopeprovider(for:testcase:)) method, returning a type that conforms to this protocol. Create a custom scope to consolidate common set-up and tear-down logic for tests which have similar needs, which allows each test function to focus on the unique aspects of its test.
## [Topics](https://developer.apple.com/documentation/testing/testscoping\#topics)
### [Instance Methods](https://developer.apple.com/documentation/testing/testscoping\#Instance-Methods)
[`func provideScope(for: Test, testCase: Test.Case?, performing: () async throws -> Void) async throws`](https://developer.apple.com/documentation/testing/testscoping/providescope(for:testcase:performing:))
Provide custom execution scope for a function call which is related to the specified test or test case.
**Required**
## [Relationships](https://developer.apple.com/documentation/testing/testscoping\#relationships)
### [Inherits From](https://developer.apple.com/documentation/testing/testscoping\#inherits-from)