Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ module MyTypeExtensions =
* `COSMOS_EMULATOR_KEY` overrides the emulator key the tests authenticate with.
* `COSMOS_EMULATOR_PARTITION_COUNT` is the number of partitions the emulator offers (default `25`, the Windows emulator's default `/PartitionCount`); the fixtures keep at most that many test containers at a time, one partition each.
* `COSMOS_TEST_LEFTOVER_AGE_MINUTES` is how many minutes a `fsac-test-` database must stay unmodified before the leftover sweep of `[<AssemblyInitialize>]` and `[<AssemblyCleanup>]` deletes it (default `60`), so that the live databases of another test process on the same emulator are kept; `0` deletes every test database and is safe only while no other test process uses the emulator.
* `COSMOS_REWRITE_BASELINES` set to `1` or `true` makes a test that compares SQL with its golden baseline (`Baseline.assertMatches`, files under `Baselines/<suite>/` of the test project) write what it produced into the baseline instead of comparing; the test then reports itself inconclusive, the rewritten files are reviewed in the diff, and CI refuses to rewrite.
* `COSMOS_REWRITE_BASELINES` set to `1` or `true` makes a test that compares a text with its golden baseline (`Baseline.assertMatches` for SQL, `Baseline.assertTextMatches` with an extension such as `groovy` for another language, files under `Baselines/<suite>/` of the test project) write what it produced into the baseline instead of comparing; the test then reports itself inconclusive, the rewritten files are reviewed in the diff, and CI refuses to rewrite.
* Every test project under `tests/` references `tests/Cosmos.Tests.Infrastructure` through `tests/Directory.Build.props`; a new test project gets it without a `ProjectReference` of its own.
* Property tests are methods of `[<TestClass>]` types marked `[<Property>]` (from `Hedgehog.MSTest`), whose parameters Hedgehog generates; never call `Property.check` inside a `[<TestMethod>]`. A test project with property tests references the `Hedgehog` and `Hedgehog.MSTest` packages, as `tests/Cosmos.Tests` does. A property is an instance method that returns `unit`, `Task` or `ValueTask` and fails by throwing: MSTest 4 rejects static methods and other return types, and one such method fails the discovery of the whole assembly, which `--list-tests` shows before a run. MSTest creates the test class and runs `[<TestInitialize>]` and `[<TestCleanup>]` for every generated case and every shrink step. A failed property reports a `[<Recheck("…")>]` to add next to its `Property` attribute, which then replays the counterexample. Hedgehog 2.0.4 cannot generate `DateOnly` and `TimeOnly`: the generators of [hedgehogqa/fsharp-hedgehog#488](https://github.com/hedgehogqa/fsharp-hedgehog/pull/488) are merged and not released, so a parameter of either type, or of a type that holds one, needs a generator from a `GenAttribute` or an `AutoGenConfig`.
* `CollectionAssert` cannot work with F# lists – use F# array syntax (`[| ... |]`) instead.
Expand Down
191 changes: 148 additions & 43 deletions tests/Cosmos.Tests.Infrastructure/Baseline.fs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
/// <summary>
/// Golden baselines: the SQL text and the parameters a test produces, compared with files checked into the test project,
/// <c>Baselines/&lt;suite&gt;/&lt;case&gt;.sql</c> and <c>Baselines/&lt;suite&gt;/&lt;case&gt;.params.json</c>.
/// Golden baselines: the text and the parameters a test produces, compared with files checked into the test project,
/// <c>Baselines/&lt;suite&gt;/&lt;case&gt;.&lt;extension&gt;</c> and <c>Baselines/&lt;suite&gt;/&lt;case&gt;.params.json</c>.
/// The extension tells the language of the text: <see cref="SqlExtension"/> for a query of Cosmos DB, or another
/// extension, for example <c>groovy</c> for a Gremlin script.
/// </summary>
/// <remarks>
/// <para>
/// The SQL is compared after <see cref="normalizeSql"/> has collapsed its whitespace, so that a baseline may be laid out
/// for reading, and the parameters are compared as JSON, so that their layout does not matter either. A query without
/// parameters has no parameter file.
/// A query of Cosmos DB is compared after <see cref="normalizeSql"/> has collapsed its whitespace, so that its baseline
/// may be laid out for reading. Another text is compared after <see cref="normalizeText"/>, which keeps its line breaks
/// and its spaces. In another language, they can change the meaning: in Groovy, a line break ends a comment. The
/// parameters are compared as JSON, so that their layout does not matter. A text without parameters has no parameter
/// file.
/// </para>
/// <para>
/// With the environment variable <see cref="RewriteVariable"/> set to <c>1</c> or <c>true</c>, a test writes what it
Expand All @@ -31,17 +35,25 @@ open Microsoft.VisualStudio.TestTools.UnitTesting
[<Literal>]
let RewriteVariable = "COSMOS_REWRITE_BASELINES"

/// The extension of a baseline that holds a query of Cosmos DB.
[<Literal>]
let SqlExtension = "sql"

// The extension of the parameter file. A text file with this extension would be the parameter file.
[<Literal>]
let private ParametersExtension = "params.json"

/// The result of comparing what a test produced with its baseline.
[<RequireQualifiedAccess>]
type Comparison =
/// The produced SQL and parameters match the baseline.
/// The produced text and parameters match the baseline.
| Matches
/// The baseline does not exist yet; the path is that of its SQL file.
| Missing of sqlPath : string
/// The produced SQL or parameters differ from the baseline, both given in the form they were compared in.
/// The baseline does not exist yet; the path is that of its text file.
| Missing of textPath : string
/// The produced text or parameters differ from the baseline, both given in the form they were compared in.
| Differs of expected : string * actual : string
/// The baseline was written from what the test produced; the path is that of its SQL file.
| Rewritten of sqlPath : string
/// The baseline was written from what the test produced; the path is that of its text file.
| Rewritten of textPath : string

// Characters that make a suite or case name unusable as part of a file path on any platform
let private invalidNameCharacters =
Expand All @@ -59,6 +71,25 @@ let private ensureValidName (parameterName : string) (name : string) =
then
invalidArg parameterName $"'{name}' cannot be part of the name of a baseline file."

// Windows removes a dot or a space at the end of a file or directory name. Thus the extension 'params.json.' would
// give the parameter file, and the suite 'Suite.' would give the directory 'Suite'.
if
name.EndsWith (".", StringComparison.Ordinal)
|| name.EndsWith (" ", StringComparison.Ordinal)
then
invalidArg parameterName $"'{name}' ends with a dot or a space, which Windows removes from a file or directory name."

let private ensureValidExtension (extension : string) =
ensureValidName (nameof extension) extension

if extension.StartsWith (".", StringComparison.Ordinal) then
invalidArg (nameof extension) $"Write the extension '{extension}' without the leading dot."

// Windows and macOS do not compare the case of file names. Thus on these systems, a text file with this extension
// is the parameter file.
if String.Equals (extension, ParametersExtension, StringComparison.OrdinalIgnoreCase) then
invalidArg (nameof extension) $"'{extension}' is the extension of the parameter file of a baseline."
Comment thread
xperiandri marked this conversation as resolved.
Resolved

// LF on every platform, so that a baseline does not change with the system that rewrote it
let private indented = JsonSerializerOptions (WriteIndented = true, NewLine = "\n")

Expand All @@ -85,6 +116,12 @@ let normalizeSql (sql : string) : string =

builder.ToString ()

/// <summary>
/// Changes every line break in <paramref name="text"/> to a line feed and removes the whitespace at both ends. The
/// other whitespace stays: in a language other than SQL, a line break or a space can change the meaning of a text.
/// </summary>
let normalizeText (text : string) : string = text.ReplaceLineEndings("\n").Trim()

/// <summary>
/// Finds the <c>Baselines</c> directory of the test project that built <paramref name="assembly"/>: the directory next
/// to the project file, found by walking up from the directory the assembly runs from.
Expand All @@ -106,61 +143,97 @@ let directoryOf (assembly : Assembly) : string =
| null -> find null
| assemblyDirectory -> find (DirectoryInfo assemblyDirectory)

/// <summary>
/// Compares <paramref name="sql"/> and <paramref name="parameters"/>, the parameter names mapped to their values, with
/// the baseline <paramref name="caseName"/> of <paramref name="suite"/> under <paramref name="directory"/>, or, when
/// <paramref name="rewrite"/> is <see langword="true"/>, writes them as that baseline.
/// </summary>
/// <exception cref="ArgumentException">The suite or the case name cannot be part of a file name.</exception>
let compare
// Compares a text and its parameters with their baseline, or writes them as the baseline. The two texts are compared in
// the form that normalize gives them.
let private compareWith
(normalize : string -> string)
(extension : string)
(rewrite : bool)
(directory : string)
(suite : string)
(caseName : string)
(sql : string)
(text : string)
(parameters : JsonObject)
: Comparison =
ensureValidExtension extension
ensureValidName (nameof suite) suite
ensureValidName (nameof caseName) caseName
let suiteDirectory = Path.Combine (directory, suite)
let sqlPath = Path.Combine (suiteDirectory, $"{caseName}.sql")
let parametersPath = Path.Combine (suiteDirectory, $"{caseName}.params.json")
let textPath = Path.Combine (suiteDirectory, $"{caseName}.{extension}")
let parametersPath = Path.Combine (suiteDirectory, $"{caseName}.{ParametersExtension}")

if rewrite then
Directory.CreateDirectory suiteDirectory |> ignore
File.WriteAllText (sqlPath, sql.Trim () + "\n")
File.WriteAllText (textPath, text.Trim () + "\n")

if parameters.Count = 0 then
// A query that lost its parameters must not keep a parameter file from before
// A text that lost its parameters must not keep a parameter file from before
File.Delete parametersPath
else
File.WriteAllText (parametersPath, parameters.ToJsonString indented + "\n")

Comparison.Rewritten sqlPath
elif not (File.Exists sqlPath) then
Comparison.Missing sqlPath
Comparison.Rewritten textPath
elif not (File.Exists textPath) then
Comparison.Missing textPath
else
let expectedSql = normalizeSql (File.ReadAllText sqlPath)
let expectedText = normalize (File.ReadAllText textPath)

let expectedParameters =
if File.Exists parametersPath then
nonNull (JsonNode.Parse (File.ReadAllText parametersPath))
else
JsonObject ()

let actualSql = normalizeSql sql
let actualText = normalize text

if
String.Equals (expectedSql, actualSql, StringComparison.Ordinal)
String.Equals (expectedText, actualText, StringComparison.Ordinal)
&& JsonNode.DeepEquals (expectedParameters, parameters)
then
Comparison.Matches
else
Comparison.Differs (
$"{expectedSql}\n{expectedParameters.ToJsonString ()}",
$"{actualSql}\n{parameters.ToJsonString ()}"
$"{expectedText}\n{expectedParameters.ToJsonString ()}",
$"{actualText}\n{parameters.ToJsonString ()}"
)

/// <summary>
/// Compares <paramref name="text"/> and <paramref name="parameters"/>, the parameter names mapped to their values, with
/// the baseline <paramref name="caseName"/> of <paramref name="suite"/> under <paramref name="directory"/>, whose text
/// file has the extension <paramref name="extension"/>, or, when <paramref name="rewrite"/> is
/// <see langword="true"/>, writes them as that baseline. The texts are compared after <see cref="normalizeText"/>.
/// </summary>
/// <exception cref="ArgumentException">
/// The suite or the case name cannot be part of a file name, or the extension cannot be the extension of a text file.
/// </exception>
let compareText
(extension : string)
(rewrite : bool)
(directory : string)
(suite : string)
(caseName : string)
(text : string)
(parameters : JsonObject)
: Comparison =
compareWith normalizeText extension rewrite directory suite caseName text parameters

/// <summary>
/// Compares <paramref name="sql"/> and <paramref name="parameters"/> with a baseline of a query of Cosmos DB, whose text
/// file has the extension <see cref="SqlExtension"/>, or, when <paramref name="rewrite"/> is <see langword="true"/>,
/// writes them as that baseline. The queries are compared after <see cref="normalizeSql"/>, so that a baseline may be
/// laid out for reading.
/// </summary>
/// <exception cref="ArgumentException">The suite or the case name cannot be part of a file name.</exception>
let compare
(rewrite : bool)
(directory : string)
(suite : string)
(caseName : string)
(sql : string)
(parameters : JsonObject)
: Comparison =
compareWith normalizeSql SqlExtension rewrite directory suite caseName sql parameters

let private isSet (variable : string) =
match Environment.GetEnvironmentVariable variable with
| null -> false
Expand All @@ -170,26 +243,58 @@ let private isSet (variable : string) =
|| value.Equals ("true", StringComparison.OrdinalIgnoreCase)

/// <summary>
/// Fails the test unless <paramref name="sql"/> and <paramref name="parameters"/> match the baseline
/// <paramref name="caseName"/> of <paramref name="suite"/> under <paramref name="directory"/>, usually
/// <see cref="directoryOf"/> the test assembly. With <see cref="RewriteVariable"/> set, writes the baseline instead and
/// reports the test inconclusive.
/// Whether <see cref="RewriteVariable"/> is set to <c>1</c> or <c>true</c>, so that the assertions write the baselines
/// instead of comparing them. A test of the comparison itself is inconclusive then.
/// </summary>
let assertMatches (directory : string) (suite : string) (caseName : string) (sql : string) (parameters : JsonObject) =
let rewrite = isSet RewriteVariable
let isRewriting () : bool = isSet RewriteVariable

// Whether the assertions write the baselines instead of comparing them. A run on CI never does.
let private isRewriteRequested () =
let rewrite = isRewriting ()

if rewrite && isSet "CI" then
Assert.Fail $"{RewriteVariable} is set on CI, where baselines are never rewritten."

match compare rewrite directory suite caseName sql parameters with
rewrite

// Makes the test fail, pass or be inconclusive by the result of the comparison with its baseline
let private report (extension : string) (suite : string) (caseName : string) (comparison : Comparison) =
match comparison with
| Comparison.Matches -> ()
| Comparison.Missing sqlPath ->
Assert.Fail $"There is no baseline at {sqlPath}. Run the test with {RewriteVariable}=1 to write it, then review it."
| Comparison.Missing textPath ->
Assert.Fail $"There is no baseline at {textPath}. Run the test with {RewriteVariable}=1 to write it, then review it."
| Comparison.Differs (expected, actual) ->
Assert.AreEqual (
expected,
actual,
$"The SQL or the parameters of {suite}/{caseName} differ from the baseline. Run the test with {RewriteVariable}=1 to accept them, then review the diff."
$"The text or the parameters of {suite}/{caseName}.{extension} differ from the baseline. Run the test with {RewriteVariable}=1 to accept them, then review the diff."
)
| Comparison.Rewritten sqlPath ->
Assert.Inconclusive $"Rewrote the baseline at {sqlPath}. Review it and run the test again without {RewriteVariable}."
| Comparison.Rewritten textPath ->
Assert.Inconclusive $"Rewrote the baseline at {textPath}. Review it and run the test again without {RewriteVariable}."

/// <summary>
/// Fails the test unless <paramref name="text"/> and <paramref name="parameters"/> match the baseline
/// <paramref name="caseName"/> of <paramref name="suite"/> under <paramref name="directory"/>, usually
/// <see cref="directoryOf"/> the test assembly, whose text file has the extension <paramref name="extension"/>. The
/// texts are compared as <see cref="compareText"/> compares them. With <see cref="RewriteVariable"/> set, writes the
/// baseline instead and reports the test inconclusive.
/// </summary>
let assertTextMatches
(extension : string)
(directory : string)
(suite : string)
(caseName : string)
(text : string)
(parameters : JsonObject)
=
compareText extension (isRewriteRequested ()) directory suite caseName text parameters
|> report extension suite caseName

/// <summary>
/// Fails the test unless <paramref name="sql"/> and <paramref name="parameters"/> match a baseline of a query of
/// Cosmos DB, compared as <see cref="compare"/> compares them. With <see cref="RewriteVariable"/> set, writes the
/// baseline instead and reports the test inconclusive.
/// </summary>
let assertMatches (directory : string) (suite : string) (caseName : string) (sql : string) (parameters : JsonObject) =
compare (isRewriteRequested ()) directory suite caseName sql parameters
|> report SqlExtension suite caseName
Loading
Loading