From 02c825177d3e1255adc43e7ec19c6f95f127c851 Mon Sep 17 00:00:00 2001 From: Suyash Kumar Date: Thu, 27 Jun 2024 16:21:55 -0700 Subject: [PATCH] Set EvalConfig.EvaluationTimestamp to time.Now() if it is empty (zero value), as described in the config comments. PiperOrigin-RevId: 647481250 --- cql.go | 6 +++++- cql_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/cql.go b/cql.go index eb2987d..17eff71 100644 --- a/cql.go +++ b/cql.go @@ -97,12 +97,16 @@ type EvalConfig struct { // should not be called from multiple goroutines on a single *ELM. // Errors returned by Eval will always be a result.EngineError. func (e *ELM) Eval(ctx context.Context, retriever retriever.Retriever, config EvalConfig) (result.Libraries, error) { + evalTS := config.EvaluationTimestamp + if config.EvaluationTimestamp.IsZero() { + evalTS = time.Now() + } c := interpreter.Config{ DataModels: e.dataModels, Parameters: e.parsedParams, Retriever: retriever, Terminology: config.Terminology, - EvaluationTimestamp: config.EvaluationTimestamp, + EvaluationTimestamp: evalTS, ReturnPrivateDefs: config.ReturnPrivateDefs, } diff --git a/cql_test.go b/cql_test.go index 7973bf7..c223b2a 100644 --- a/cql_test.go +++ b/cql_test.go @@ -18,6 +18,7 @@ import ( "context" "errors" "testing" + "time" "github.com/google/cql" "github.com/google/cql/model" @@ -115,6 +116,40 @@ func TestCQL(t *testing.T) { } } +func TestCQL_EvalEmptyTimestamp(t *testing.T) { + // This test checks that an empty EvalConfig.EvaluationTimestamp is set to time.Now() at the start + // of the eval request. We do this by sanity checking the result of Now() is within 2 mins of the + // test assertion time. + cqlSources := []string{dedent.Dedent(` + library TESTLIB version '1.0.0' + define TESTRESULT: Now()`)} + parserConfig := cql.ParseConfig{} + evalConfig := cql.EvalConfig{} + + elm, err := cql.Parse(context.Background(), cqlSources, parserConfig) + if err != nil { + t.Fatalf("Parse returned unexpected error: %v", err) + } + + results, err := elm.Eval(context.Background(), nil, evalConfig) + if err != nil { + t.Fatalf("Eval returned unexpected error: %v", err) + } + + gotResult := getTESTRESULTWithSources(t, results) + dt, err := result.ToDateTime(gotResult) + if err != nil { + t.Errorf("returned result is not a DateTime, err: %v", err) + } + + // Check that the dt is within [time.Now()-2min, time.Now()] + end := time.Now() + start := end.Add(-2 * time.Minute) + if dt.Date.Before(start) || dt.Date.After(end) { + t.Errorf("returned CQL Now() result is not within 2 mins of time.Now()") + } +} + func TestCQL_ParseErrors(t *testing.T) { tests := []struct { name string