-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathTest.elm
1227 lines (986 loc) · 44.2 KB
/
Test.elm
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
module Review.Test exposing
( ReviewResult, run, runWithProjectData, runOnModules, runOnModulesWithProjectData
, ExpectedError, expectNoErrors, expectErrors, error, atExactly, whenFixed, expectErrorsForModules, expectErrorsForElmJson, expectErrorsForReadme
)
{-| Module that helps you test your rules, using [`elm-test`](https://package.elm-lang.org/packages/elm-explorations/test/latest/).
import Review.Test
import Test exposing (Test, describe, test)
import The.Rule.You.Want.To.Test exposing (rule)
tests : Test
tests =
describe "The.Rule.You.Want.To.Test"
[ test "should not report anything when <condition>" <|
\() ->
"""module A exposing (..)
a = foo n"""
|> Review.Test.run rule
|> Review.Test.expectNoErrors
, test "should report Debug.log use" <|
\() ->
"""module A exposing (..)
a = Debug.log "some" "message" """
|> Review.Test.run rule
|> Review.Test.expectErrors
[ Review.Test.error
{ message = "Remove the use of `Debug` before shipping to production"
, details = [ "Details about the error" ]
, under = "Debug.log"
}
]
]
# Strategies for effective testing
## Use Test-Driven Development
Writing a rule is a process that works really well with the Test-Driven
Development process loop, which is:
- Before writing any code, write a failing test.
- Run the test and make sure that it is failing, otherwise you can't be
sure that the test is well-written.
- Write the simplest (almost stupid) code to make the test pass
- Run the tests again and make sure that the test is passing, and that you
didn't break any previous tests
- Optionally, refactor your code but be sure not to change the behavior of the
implementation. You should not add support for new patterns, as you will
want to write tests for those first.
Then repeat for every pattern yoy wish to handle.
## Have a good title
A good test title explains
- what is tested - Probably the rule, but making it explicit
in a [`describe`](https://package.elm-lang.org/packages/elm-explorations/test/latest/Test#describe)
might improve your test report. Or maybe you are testing a sub-part of the rule,
and you can name it explictly.
- what should happen: (not) reporting an error, fix <something> by <doing something>, ...
- when: what is the situation that this test sets up?
Ideally, by only reading through the test titles, someone else should be able to
rewrite the rule you are testing.
## What should you test?
You should test the scenarios where you expect the rule to report something. At
the same time, you should also test when it shouldn't. I encourage writing tests
to make sure that things that are similar to what you want to report are not
reported.
For instance, if you wish to report uses of variables named `foo`, write a test
that ensures that the use of variables named differently does not get reported.
Tests are pretty cheap, and in the case of rules, it is probably better to have
too many tests rather than too few, since the behavior of a rule rarely changes
drastically.
# Design goals
If you are interested, you can read
[the design goals](https://github.com/jfmengels/elm-review/blob/master/documentation/design/test-module.md)
for this module.
# Running tests
@docs ReviewResult, run, runWithProjectData, runOnModules, runOnModulesWithProjectData
# Making assertions
@docs ExpectedError, expectNoErrors, expectErrors, error, atExactly, whenFixed, expectErrorsForModules, expectErrorsForElmJson, expectErrorsForReadme
-}
import Array exposing (Array)
import Elm.Syntax.Module as Module
import Elm.Syntax.Node as Node
import Elm.Syntax.Range exposing (Range)
import Expect exposing (Expectation)
import Review.Error as Error
import Review.Fix as Fix
import Review.Project as Project exposing (Project, ProjectModule)
import Review.Rule as Rule exposing (ReviewError, Rule)
import Review.Test.FailureMessage as FailureMessage
import Set exposing (Set)
import Vendor.ListExtra as ListExtra
-- REVIEW RESULT
{-| The result of running a rule on a `String` containing source code.
-}
type ReviewResult
= FailedRun String
| SuccessfulRun (List SuccessfulRunResult)
type alias SuccessfulRunResult =
{ moduleName : String
, inspector : CodeInspector
, errors : List ReviewError
}
type alias CodeInspector =
{ isModule : Bool
, source : String
, getCodeAtLocation : Range -> Maybe String
, checkIfLocationIsAmbiguous : ReviewError -> String -> Expectation
}
{-| An expectation for an error. Use [`error`](#error) to create one.
-}
type ExpectedError
= ExpectedError ExpectedErrorDetails
type alias ExpectedErrorDetails =
{ message : String
, details : List String
, under : Under
, fixedSource : Maybe String
}
type Under
= Under String
| UnderExactly String Range
type alias SourceCode =
String
{-| Run a `Rule` on a `String` containing source code. You can then use
[`expectNoErrors`](#expectNoErrors) or [`expectErrors`](#expectErrors) to assert
the errors reported by the rule.
import My.Rule exposing (rule)
import Review.Test
import Test exposing (Test, test)
all : Test
all =
test "test title" <|
\() ->
"""
module SomeModule exposing (a)
a = 1"""
|> Review.Test.run rule
|> Review.Test.expectNoErrors
The source code needs to be syntactically valid Elm code. If the code
can't be parsed, the test will fail regardless of the expectations you set on it.
Note that to be syntactically valid, you need at least a module declaration at the
top of the file (like `module A exposing (..)`) and one declaration (like `a = 1`).
You can't just have an expression like `1 + 2`.
Note: This is a simpler version of [`runWithProjectData`](#runWithProjectData).
If your rule is interested in project related details, then you should use
[`runWithProjectData`](#runWithProjectData) instead.
-}
run : Rule -> String -> ReviewResult
run rule source =
runWithProjectData Project.new rule source
{-| Run a `Rule` on a `String` containing source code, with data about the
project loaded, such as the contents of `elm.json` file.
import My.Rule exposing (rule)
import Review.Project as Project exposing (Project)
import Review.Test
import Test exposing (Test, test)
all : Test
all =
test "test title" <|
\() ->
let
project : Project
project =
Project.new
|> Project.addElmJson elmJsonToConstructManually
in
"""module SomeModule exposing (a)
a = 1"""
|> Review.Test.runWithProjectData project rule
|> Review.Test.expectNoErrors
The source code needs to be syntactically valid Elm code. If the code
can't be parsed, the test will fail regardless of the expectations you set on it.
Note that to be syntactically valid, you need at least a module declaration at the
top of the file (like `module A exposing (..)`) and one declaration (like `a = 1`).
You can't just have an expression like `1 + 2`.
Note: This is a more complex version of [`run`](#run). If your rule is not
interested in project related details, then you should use [`run`](#run) instead.
-}
runWithProjectData : Project -> Rule -> String -> ReviewResult
runWithProjectData project rule source =
runOnModulesWithProjectData project rule [ source ]
{-| Run a `Rule` on several modules. You can then use
[`expectNoErrors`](#expectNoErrors) or [`expectErrorsForModules`](#expectErrorsForModules) to assert
the errors reported by the rule.
This is the same as [`run`](#run), but you can pass several modules.
This is especially useful to test rules created with
[`Review.Rule.newProjectRuleSchema`](./Review-Rule#newProjectRuleSchema), that look at
several files, and where the context of the project is important.
import My.Rule exposing (rule)
import Review.Test
import Test exposing (Test, test)
all : Test
all =
test "test title" <|
\() ->
[ """
module A exposing (a)
a = 1""", """
module B exposing (a)
a = 1""" ]
|> Review.Test.runOnModules rule
|> Review.Test.expectNoErrors
The source codes need to be syntactically valid Elm code. If the code
can't be parsed, the test will fail regardless of the expectations you set on it.
Note that to be syntactically valid, you need at least a module declaration at the
top of each file (like `module A exposing (..)`) and one declaration (like `a = 1`).
You can't just have an expression like `1 + 2`.
Note: This is a simpler version of [`runOnModulesWithProjectData`](#runOnModulesWithProjectData).
If your rule is interested in project related details, then you should use
[`runOnModulesWithProjectData`](#runOnModulesWithProjectData) instead.
-}
runOnModules : Rule -> List String -> ReviewResult
runOnModules rule sources =
runOnModulesWithProjectData Project.new rule sources
{-| Run a `Rule` on several modules. You can then use
[`expectNoErrors`](#expectNoErrors) or [`expectErrorsForModules`](#expectErrorsForModules) to assert
the errors reported by the rule.
This is basically the same as [`run`](#run), but you can pass several modules.
This is especially useful to test rules created with
[`Review.Rule.newProjectRuleSchema`](./Review-Rule#newProjectRuleSchema), that look at
several modules, and where the context of the project is important.
import My.Rule exposing (rule)
import Review.Test
import Test exposing (Test, test)
all : Test
all =
test "test title" <|
\() ->
let
project : Project
project =
Project.new
|> Project.addElmJson elmJsonToConstructManually
in
[ """
module A exposing (a)
a = 1""", """
module B exposing (a)
a = 1""" ]
|> Review.Test.runOnModulesWithProjectData project rule
|> Review.Test.expectNoErrors
The source codes need to be syntactically valid Elm code. If the code
can't be parsed, the test will fail regardless of the expectations you set on it.
Note that to be syntactically valid, you need at least a module declaration at the
top of each file (like `module A exposing (..)`) and one declaration (like `a = 1`).
You can't just have an expression like `1 + 2`.
Note: This is a more complex version of [`runOnModules`](#runOnModules). If your rule is not
interested in project related details, then you should use [`runOnModules`](#runOnModules) instead.
-}
runOnModulesWithProjectData : Project -> Rule -> List String -> ReviewResult
runOnModulesWithProjectData project rule sources =
let
projectWithModules : Project
projectWithModules =
sources
|> List.indexedMap
(\index source ->
{ path = "TestContent_" ++ String.fromInt index ++ ".elm"
, source = source
}
)
|> List.foldl Project.addModule project
in
case Project.modulesThatFailedToParse projectWithModules of
{ source } :: _ ->
let
fileAndIndex : { source : String, index : Int }
fileAndIndex =
{ source = source
, index = indexOf source sources |> Maybe.withDefault -1
}
in
FailedRun <| FailureMessage.parsingFailure (List.length sources == 1) fileAndIndex
[] ->
let
modules : List ProjectModule
modules =
Project.modules projectWithModules
in
if List.isEmpty modules then
FailedRun FailureMessage.missingSources
else
case findDuplicateModuleNames Set.empty modules of
Just moduleName ->
FailedRun <| FailureMessage.duplicateModuleName moduleName
Nothing ->
let
errors : List ReviewError
errors =
projectWithModules
|> Rule.review [ rule ]
|> Tuple.first
in
case ListExtra.find (\err_ -> Rule.errorFilePath err_ == "GLOBAL ERROR") errors of
Just globalError ->
FailedRun <| FailureMessage.globalErrorInTest globalError
Nothing ->
List.concat
[ List.map (moduleToRunResult errors) modules
, elmJsonRunResult errors projectWithModules
, readmeRunResult errors projectWithModules
]
|> SuccessfulRun
moduleToRunResult : List ReviewError -> ProjectModule -> SuccessfulRunResult
moduleToRunResult errors projectModule =
{ moduleName =
projectModule.ast.moduleDefinition
|> Node.value
|> Module.moduleName
|> String.join "."
, inspector = codeInspectorForSource True projectModule.source
, errors =
errors
|> List.filter (\error_ -> Rule.errorFilePath error_ == projectModule.path)
|> List.sortWith compareErrorPositions
}
elmJsonRunResult : List ReviewError -> Project -> List SuccessfulRunResult
elmJsonRunResult errors project =
case Project.elmJson project of
Just elmJsonData ->
case List.filter (\error_ -> Rule.errorFilePath error_ == elmJsonData.path) errors of
[] ->
[]
errorsForElmJson ->
[ { moduleName = elmJsonData.path
, inspector = codeInspectorForSource False elmJsonData.raw
, errors = errorsForElmJson
}
]
Nothing ->
[]
readmeRunResult : List ReviewError -> Project -> List SuccessfulRunResult
readmeRunResult errors project =
case Project.readme project of
Just readme ->
case List.filter (\error_ -> Rule.errorFilePath error_ == readme.path) errors of
[] ->
[]
errorsForElmJson ->
[ { moduleName = readme.path
, inspector = codeInspectorForSource False readme.content
, errors = errorsForElmJson
}
]
Nothing ->
[]
indexOf : a -> List a -> Maybe Int
indexOf elementToFind aList =
case aList of
[] ->
Nothing
a :: rest ->
if a == elementToFind then
Just 0
else
indexOf elementToFind rest
|> Maybe.map ((+) 1)
codeInspectorForSource : Bool -> String -> CodeInspector
codeInspectorForSource isModule source =
{ isModule = isModule
, source = source
, getCodeAtLocation = getCodeAtLocationInSourceCode source
, checkIfLocationIsAmbiguous = checkIfLocationIsAmbiguousInSourceCode source
}
findDuplicateModuleNames : Set (List String) -> List ProjectModule -> Maybe (List String)
findDuplicateModuleNames previousModuleNames modules =
case modules of
[] ->
Nothing
{ ast } :: restOfModules ->
let
moduleName : List String
moduleName =
ast.moduleDefinition
|> Node.value
|> Module.moduleName
in
if Set.member moduleName previousModuleNames then
Just moduleName
else
findDuplicateModuleNames (Set.insert moduleName previousModuleNames) restOfModules
compareErrorPositions : ReviewError -> ReviewError -> Order
compareErrorPositions a b =
compareRange (Rule.errorRange a) (Rule.errorRange b)
compareRange : Range -> Range -> Order
compareRange a b =
if a.start.row < b.start.row then
LT
else if a.start.row > b.start.row then
GT
else
-- Start row is the same from here on
if
a.start.column < b.start.column
then
LT
else if a.start.column > b.start.column then
GT
else
-- Start row and column are the same from here on
if
a.end.row < b.end.row
then
LT
else if a.end.row > b.end.row then
GT
else
-- Start row and column, and end row are the same from here on
if
a.end.column < b.end.column
then
LT
else if a.end.column > b.end.column then
GT
else
EQ
{-| Assert that the rule reported no errors. Note, this is equivalent to using [`expectErrors`](#expectErrors)
like `expectErrors []`.
import Review.Test
import Test exposing (Test, describe, test)
import The.Rule.You.Want.To.Test exposing (rule)
tests : Test
tests =
describe "The.Rule.You.Want.To.Test"
[ test "should not report anything when <condition>" <|
\() ->
"""module A exposing (..)
a = foo n"""
|> Review.Test.run rule
|> Review.Test.expectNoErrors
]
-}
expectNoErrors : ReviewResult -> Expectation
expectNoErrors reviewResult =
case reviewResult of
FailedRun errorMessage ->
Expect.fail errorMessage
SuccessfulRun runResults ->
runResults
|> List.map
(\{ errors, moduleName } () ->
List.isEmpty errors
|> Expect.true (FailureMessage.didNotExpectErrors moduleName errors)
)
|> (\expectations -> Expect.all expectations ())
{-| Assert that the rule reported some errors, by specifying which ones.
Assert which errors are reported using [`error`](#error). The test will fail if
a different number of errors than expected are reported, or if the message or the
location is incorrect.
The errors should be in the order of where they appear in the source code. An error
at the start of the source code should appear earlier in the list than
an error at the end of the source code.
import Review.Test
import Test exposing (Test, describe, test)
import The.Rule.You.Want.To.Test exposing (rule)
tests : Test
tests =
describe "The.Rule.You.Want.To.Test"
[ test "should report Debug.log use" <|
\() ->
"""module A exposing (..)
a = Debug.log "some" "message"
"""
|> Review.Test.run rule
|> Review.Test.expectErrors
[ Review.Test.error
{ message = "Remove the use of `Debug` before shipping to production"
, details = [ "Details about the error" ]
, under = "Debug.log"
}
]
]
-}
expectErrors : List ExpectedError -> ReviewResult -> Expectation
expectErrors expectedErrors reviewResult =
case reviewResult of
FailedRun errorMessage ->
Expect.fail errorMessage
SuccessfulRun (runResult :: []) ->
checkAllErrorsMatch runResult expectedErrors
SuccessfulRun _ ->
Expect.fail FailureMessage.needToUsedExpectErrorsForModules
{-| Assert that the rule reported some errors, by specifying which ones and the
module for which they were reported.
This is the same as [`expectErrors`](#expectErrors), but for when you used
[`runOnModules`](#runOnModules) or [`runOnModulesWithProjectData`](#runOnModulesWithProjectData).
to create the test. When using those, the errors you expect need to be associated
with a module. If we don't specify this, your tests might pass because you
expected the right errors, but they may be reported for the wrong module!
The expected errors are tupled: the first element is the module name
(for example: `List` or `My.Module.Name`) and the second element is the list of
errors you expect to be reported.
Assert which errors are reported using [`error`](#error). The test will fail if
a different number of errors than expected are reported, or if the message or the
location is incorrect.
The errors should be in the order of where they appear in the source code. An error
at the start of the source code should appear earlier in the list than
an error at the end of the source code.
import Review.Test
import Test exposing (Test, describe, test)
import The.Rule.You.Want.To.Test exposing (rule)
all : Test
all =
test "should report an error when a module uses `Debug.log`" <|
\() ->
[ """
module ModuleA exposing (a)
a = 1""", """
module ModuleB exposing (a)
a = Debug.log "log" 1""" ]
|> Review.Test.runOnModules rule
|> Review.Test.expectErrorsForModules
[ ( "ModuleB"
, [ Review.Test.error
{ message = "Remove the use of `Debug` before shipping to production"
, details = [ "Details about the error" ]
, under = "Debug.log"
}
]
)
]
-}
expectErrorsForModules : List ( String, List ExpectedError ) -> ReviewResult -> Expectation
expectErrorsForModules expectedErrorsList reviewResult =
case reviewResult of
FailedRun errorMessage ->
Expect.fail errorMessage
SuccessfulRun runResults ->
let
maybeUnknownModule : Maybe String
maybeUnknownModule =
Set.diff
(expectedErrorsList |> List.map Tuple.first |> Set.fromList)
(runResults |> List.map .moduleName |> Set.fromList)
|> Set.toList
|> List.head
in
case maybeUnknownModule of
Just unknownModule ->
FailureMessage.unknownModulesInExpectedErrors unknownModule
|> Expect.fail
Nothing ->
runResults
|> List.map
(\runResult ->
let
expectedErrors : List ExpectedError
expectedErrors =
expectedErrorsList
|> ListExtra.find (\( moduleName_, _ ) -> moduleName_ == runResult.moduleName)
|> Maybe.map Tuple.second
|> Maybe.withDefault []
in
\() -> checkAllErrorsMatch runResult expectedErrors
)
|> (\expectations -> Expect.all expectations ())
{-| Assert that the rule reported some errors for the `elm.json` file, by specifying which ones.
test "report an error when a module is unused" <|
\() ->
let
project : Project
project =
Project.new
|> Project.addElmJson elmJsonToConstructManually
in
"""
module ModuleA exposing (a)
a = 1"""
|> Review.Test.runWithProjectData project rule
|> Review.Test.expectErrorsForElmJson
[ Review.Test.error
{ message = "Unused dependency `author/package`"
, details = [ "Dependency should be removed" ]
, under = "author/package"
}
]
Alternatively, or if you need to specify errors for other files too, you can use [`expectErrorsForModules`](#expectErrorsForModules), specifying `elm.json` as the module name.
sourceCode
|> Review.Test.runOnModulesWithProjectData project rule
|> Review.Test.expectErrorsForModules
[ ( "ModuleB", [ Review.Test.error someErrorModuleB ] )
, ( "elm.json", [ Review.Test.error someErrorForElmJson ] )
]
Assert which errors are reported using [`error`](#error). The test will fail if
a different number of errors than expected are reported, or if the message or the
location is incorrect.
-}
expectErrorsForElmJson : List ExpectedError -> ReviewResult -> Expectation
expectErrorsForElmJson expectedErrors reviewResult =
expectErrorsForModules [ ( "elm.json", expectedErrors ) ] reviewResult
{-| Assert that the rule reported some errors for the `README.md` file, by specifying which ones.
test "report an error when a module is unused" <|
\() ->
let
project : Project
project =
Project.new
|> Project.addReadme { path = "README.md", context = "# Project\n..." }
in
"""
module ModuleA exposing (a)
a = 1"""
|> Review.Test.runWithProjectData project rule
|> Review.Test.expectErrorsForReadme
[ Review.Test.error
{ message = "Invalid link"
, details = [ "README contains an invalid link" ]
, under = "htt://example.com"
}
]
Alternatively, or if you need to specify errors for other files too, you can use [`expectErrorsForModules`](#expectErrorsForModules), specifying `README.md` as the module name.
sourceCode
|> Review.Test.runOnModulesWithProjectData project rule
|> Review.Test.expectErrorsForModules
[ ( "ModuleB", [ Review.Test.error someErrorModuleB ] )
, ( "README.md", [ Review.Test.error someErrorForReadme ] )
]
Assert which errors are reported using [`error`](#error). The test will fail if
a different number of errors than expected are reported, or if the message or the
location is incorrect.
-}
expectErrorsForReadme : List ExpectedError -> ReviewResult -> Expectation
expectErrorsForReadme expectedErrors reviewResult =
expectErrorsForModules [ ( "README.md", expectedErrors ) ] reviewResult
{-| Create an expectation for an error.
`message` should be the message you're expecting to be shown to the user.
`under` is the part of the code where you are expecting the error to be shown to
the user. If it helps, imagine `under` to be the text under which the squiggly
lines will appear if the error appeared in an editor.
tests : Test
tests =
describe "The.Rule.You.Want.To.Test"
[ test "should report Debug.log use" <|
\() ->
"""module A exposing (..)
a = Debug.log "some" "message\""""
|> Review.Test.run rule
|> Review.Test.expectErrors
[ Review.Test.error
{ message = "Remove the use of `Debug` before shipping to production"
, details = [ "Details about the error" ]
, under = "Debug.log"
}
]
]
If there are multiple locations where the value of `under` appears, the test will
fail unless you use [`atExactly`](#atExactly) to remove any ambiguity of where the
error should be used.
-}
error : { message : String, details : List String, under : String } -> ExpectedError
error input =
ExpectedError
{ message = input.message
, details = input.details
, under = Under input.under
, fixedSource = Nothing
}
{-| Precise the exact position where the error should be shown to the user. This
is only necessary when the `under` field is ambiguous.
`atExactly` takes a record with start and end positions.
tests : Test
tests =
describe "The.Rule.You.Want.To.Test"
[ test "should report multiple Debug.log calls" <|
\() ->
"""module A exposing (..)
a = Debug.log "foo" z
b = Debug.log "foo" z
"""
|> Review.Test.run rule
|> Review.Test.expectErrors
[ Review.Test.error
{ message = "Remove the use of `Debug` before shipping to production"
, details = [ "Details about the error" ]
, under = "Debug.log"
}
|> Review.Test.atExactly { start = { row = 4, column = 5 }, end = { row = 4, column = 14 } }
, Review.Test.error
{ message = "Remove the use of `Debug` before shipping to production"
, details = [ "Details about the error" ]
, under = "Debug.log"
}
|> Review.Test.atExactly { start = { row = 5, column = 5 }, end = { row = 5, column = 14 } }
]
]
Tip: By default, do not use this function. If the test fails because there is some
ambiguity, the test error will give you a recommendation of what to use as a parameter
of `atExactly`, so you do not have to bother writing this hard-to-write argument yourself.
-}
atExactly : { start : { row : Int, column : Int }, end : { row : Int, column : Int } } -> ExpectedError -> ExpectedError
atExactly range ((ExpectedError expectedError_) as expectedError) =
ExpectedError { expectedError_ | under = UnderExactly (getUnder expectedError) range }
{-| Create an expectation that the error provides an automatic fix, meaning that it used
functions like [`errorWithFix`](./Review-Rule#errorWithFix), and an expectation of what the source
code should be after the error's fix have been applied.
In the absence of `whenFixed`, the test will fail if the error provides a fix.
In other words, you only need to use this function if the error provides a fix.
tests : Test
tests =
describe "The.Rule.You.Want.To.Test"
[ test "should report multiple Debug.log calls" <|
\() ->
"""module A exposing (..)
a = 1
b = Debug.log "foo" 2
"""
|> Review.Test.run rule
|> Review.Test.expectErrors
[ Review.Test.error
{ message = "Remove the use of `Debug` before shipping to production"
, details = [ "Details about the error" ]
, under = "Debug.log"
}
|> Review.Test.whenFixed """module SomeModule exposing (b)
a = 1
b = 2
"""
]
]
-}
whenFixed : String -> ExpectedError -> ExpectedError
whenFixed fixedSource (ExpectedError expectedError) =
ExpectedError { expectedError | fixedSource = Just fixedSource }
getUnder : ExpectedError -> String
getUnder (ExpectedError expectedError) =
case expectedError.under of
Under str ->
str
UnderExactly str _ ->
str
getCodeAtLocationInSourceCode : SourceCode -> Range -> Maybe String
getCodeAtLocationInSourceCode sourceCode =
let
lines : Array String
lines =
String.lines sourceCode
|> Array.fromList
in
\{ start, end } ->
if start.row == end.row then
Array.get (start.row - 1) lines
|> Maybe.map (String.slice (start.column - 1) (end.column - 1))
else
let
firstLine : String
firstLine =
case Array.get (start.row - 1) lines of
Just str ->
String.dropLeft (start.column - 1) str
Nothing ->
""
lastLine : String
lastLine =
case Array.get (end.row - 1) lines of
Just str ->
String.left end.column str
Nothing ->
""
resultingLines : List String
resultingLines =
if start.row + 1 == end.row then
[ firstLine
, lastLine
]
else
[ firstLine
, Array.slice start.row (end.row - 1) lines
|> Array.toList
|> String.join "\n"
, lastLine
]
in
resultingLines
|> String.join "\n"
|> Just
checkIfLocationIsAmbiguousInSourceCode : SourceCode -> ReviewError -> String -> Expectation
checkIfLocationIsAmbiguousInSourceCode sourceCode error_ under =
let
occurrencesInSourceCode : List Int
occurrencesInSourceCode =
String.indexes under sourceCode
in
(List.length occurrencesInSourceCode == 1)
|> Expect.true (FailureMessage.locationIsAmbiguousInSourceCode sourceCode error_ under occurrencesInSourceCode)
-- RUNNING THE CHECKS
type alias ReorderState =
{ expectedErrors : List ExpectedError
, reviewErrors : List ReviewError
, pairs : List ( ExpectedError, ReviewError )
, expectedErrorsWithNoMatch : List ExpectedError
}
reorderErrors : CodeInspector -> ReorderState -> ( List ExpectedError, List ReviewError )
reorderErrors codeInspector reorderState =
case reorderState.expectedErrors of
[] ->
( List.reverse <| reorderState.expectedErrorsWithNoMatch ++ List.map Tuple.first reorderState.pairs
, List.reverse <| reorderState.reviewErrors ++ List.map Tuple.second reorderState.pairs
)
((ExpectedError expectedErrorDetails) as expectedError) :: restOfExpectedErrors ->
case findBestMatchingReviewError codeInspector expectedErrorDetails reorderState.reviewErrors { error = Nothing, confidenceLevel = 0 } of
Just reviewError ->
reorderErrors codeInspector
{ reorderState
| pairs = ( expectedError, reviewError ) :: reorderState.pairs
, reviewErrors = removeFirstOccurrence reviewError reorderState.reviewErrors
, expectedErrors = restOfExpectedErrors
}
Nothing ->