From 7aa9e1bd61df377601a728b68dfdf302d7caba50 Mon Sep 17 00:00:00 2001 From: Leonardo Taglialegne Date: Sat, 14 Dec 2024 17:02:11 +0100 Subject: [PATCH] Use Fuzz.oneOfValues when possible Fixes #17 --- src/Internal/Builtin/Fuzzer.elm | 23 ++++++++++++++++++++++- tests/FuzzerCodeGenTest.elm | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/Internal/Builtin/Fuzzer.elm b/src/Internal/Builtin/Fuzzer.elm index 7ead39c..b199545 100644 --- a/src/Internal/Builtin/Fuzzer.elm +++ b/src/Internal/Builtin/Fuzzer.elm @@ -2,6 +2,9 @@ module Internal.Builtin.Fuzzer exposing (codeGen) import CodeGenerator exposing (CodeGenerator) import Elm.CodeGen as CG +import Elm.Syntax.Expression as Expression +import Elm.Syntax.Node exposing (Node(..)) +import Maybe.Extra import String.Extra import TypePattern exposing (TypePattern(..)) @@ -19,7 +22,15 @@ codeGen = , typePattern = Typed [ "Fuzz" ] "Fuzzer" [ Target ] , makeName = \name -> String.Extra.decapitalize name ++ "Fuzzer" } - [ CodeGenerator.customType (\_ exps -> CG.apply [ fuzz "oneOf", CG.list (List.map Tuple.second exps) ]) + [ CodeGenerator.customType + (\_ exps -> + case Maybe.Extra.combineMap extractFromConstant exps of + Just constants -> + CG.apply [ fuzz "oneOfValues", CG.list constants ] + + Nothing -> + CG.apply [ fuzz "oneOf", CG.list (List.map Tuple.second exps) ] + ) , CodeGenerator.pipeline (\c -> CG.apply [ fuzz "constant", c ]) (\m -> CG.apply [ fuzz "andMap", m ]) , CodeGenerator.mapN 8 (\name a bs -> CG.apply (fuzz name :: a :: bs)) , CodeGenerator.map (\a b -> CG.apply [ fuzz "map", a, b ]) @@ -31,3 +42,13 @@ codeGen = , CodeGenerator.char (fuzz "char") , CodeGenerator.lambdaBreaker (\inner -> CG.apply [ fuzz "lazy", CG.lambda [ CG.unitPattern ] inner ]) ] + + +extractFromConstant : ( String, CG.Expression ) -> Maybe CG.Expression +extractFromConstant ( _, expr ) = + case expr of + Expression.Application [ Node _ (Expression.FunctionOrValue [ "Fuzz" ] "constant"), Node _ inner ] -> + Just inner + + _ -> + Nothing diff --git a/tests/FuzzerCodeGenTest.elm b/tests/FuzzerCodeGenTest.elm index 36bf2e4..446ef6d 100644 --- a/tests/FuzzerCodeGenTest.elm +++ b/tests/FuzzerCodeGenTest.elm @@ -143,5 +143,27 @@ columnConstraintFuzzer = innerColumnConstraintFuzzer : Fuzzer CreateTable.InnerColumnConstraint innerColumnConstraintFuzzer = Debug.todo "" +""" + , codeGenTest "Issue #17" + [ elmJson ] + [] + [ """module A exposing (..) +import Fuzz exposing (Fuzzer) + +type Semaphore = Red | Yellow | Green + +fuzzer : Fuzzer Semaphore +fuzzer = + Debug.todo "" +""" + ] + """module A exposing (..) +import Fuzz exposing (Fuzzer) + +type Semaphore = Red | Yellow | Green + +fuzzer : Fuzzer Semaphore +fuzzer = + Fuzz.oneOfValues [ Red, Yellow, Green ] """ ]