diff --git a/server/app/app.go b/server/app/app.go index 2c2912eeba..00603cf325 100644 --- a/server/app/app.go +++ b/server/app/app.go @@ -32,10 +32,10 @@ import ( "github.com/kubeshop/tracetest/server/resourcemanager" "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/testdb" - "github.com/kubeshop/tracetest/server/tests" "github.com/kubeshop/tracetest/server/tracedb" "github.com/kubeshop/tracetest/server/traces" "github.com/kubeshop/tracetest/server/tracing" + "github.com/kubeshop/tracetest/server/transaction" "go.opentelemetry.io/otel/trace" ) @@ -150,7 +150,8 @@ func (app *App) Start(opts ...appOption) error { log.Fatal(err) } - transactionsRepository := tests.NewTransactionsRepository(db, testDB) + transactionsRepository := transaction.NewRepository(db, testDB) + transactionRunRepository := transaction.NewRunRepository(db, testDB) subscriptionManager := subscription.NewManager() app.subscribeToConfigChanges(subscriptionManager) @@ -206,7 +207,7 @@ func (app *App) Start(opts ...appOption) error { dataStoreRepo, linterRepo, testDB, - transactionsRepository, + transactionRunRepository, applicationTracer, tracer, subscriptionManager, @@ -245,7 +246,7 @@ func (app *App) Start(opts ...appOption) error { provisioner := provisioning.New() - router, mappers := controller(app.cfg, testDB, transactionsRepository, tracer, environmentRepo, rf, triggerRegistry) + router, mappers := controller(app.cfg, testDB, transactionsRepository, transactionRunRepository, tracer, environmentRepo, rf, triggerRegistry) registerWSHandler(router, mappers, subscriptionManager) // use the analytics middleware on complete router @@ -367,10 +368,10 @@ func registerlinterResource(linterRepo *linterResource.Repository, router *mux.R provisioner.AddResourceProvisioner(manager) } -func registerTransactionResource(repo *tests.TransactionsRepository, router *mux.Router, provisioner *provisioning.Provisioner, tracer trace.Tracer) { - manager := resourcemanager.New[tests.Transaction]( - tests.TransactionResourceName, - tests.TransactionResourceNamePlural, +func registerTransactionResource(repo *transaction.Repository, router *mux.Router, provisioner *provisioning.Provisioner, tracer trace.Tracer) { + manager := resourcemanager.New[transaction.Transaction]( + transaction.TransactionResourceName, + transaction.TransactionResourceNamePlural, repo, resourcemanager.CanBeAugmented(), resourcemanager.WithTracer(tracer), @@ -467,7 +468,8 @@ func registerWSHandler(router *mux.Router, mappers mappings.Mappings, subscripti func controller( cfg httpServerConfig, testDB model.Repository, - transactions *tests.TransactionsRepository, + transactionRepository *transaction.Repository, + transactionRunRepository *transaction.RunRepository, tracer trace.Tracer, environmentRepo *environment.Repository, rf *runnerFacade, @@ -475,7 +477,7 @@ func controller( ) (*mux.Router, mappings.Mappings) { mappers := mappings.New(tracesConversionConfig(), comparator.DefaultRegistry(), testDB) - router := openapi.NewRouter(httpRouter(cfg, testDB, transactions, tracer, environmentRepo, rf, mappers, triggerRegistry)) + router := openapi.NewRouter(httpRouter(cfg, testDB, transactionRepository, transactionRunRepository, tracer, environmentRepo, rf, mappers, triggerRegistry)) return router, mappers } @@ -483,14 +485,15 @@ func controller( func httpRouter( cfg httpServerConfig, testDB model.Repository, - transactions *tests.TransactionsRepository, + transactionRepo *transaction.Repository, + transactionRunRepo *transaction.RunRepository, tracer trace.Tracer, environmentRepo *environment.Repository, rf *runnerFacade, mappers mappings.Mappings, triggerRegistry *trigger.Registry, ) openapi.Router { - controller := httpServer.NewController(testDB, transactions, tracedb.Factory(testDB), rf, mappers, environmentRepo, triggerRegistry, tracer, Version) + controller := httpServer.NewController(testDB, transactionRepo, transactionRunRepo, tracedb.Factory(testDB), rf, mappers, environmentRepo, triggerRegistry, tracer, Version) apiApiController := openapi.NewApiApiController(controller) customController := httpServer.NewCustomController(controller, apiApiController, openapi.DefaultErrorHandler, tracer) httpRouter := customController diff --git a/server/app/facade.go b/server/app/facade.go index 0cadace26f..b78b7cb2bf 100644 --- a/server/app/facade.go +++ b/server/app/facade.go @@ -12,8 +12,8 @@ import ( "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/subscription" - "github.com/kubeshop/tracetest/server/tests" "github.com/kubeshop/tracetest/server/tracedb" + "github.com/kubeshop/tracetest/server/transaction" "go.opentelemetry.io/otel/trace" ) @@ -42,7 +42,7 @@ func (rf runnerFacade) RunTest(ctx context.Context, test model.Test, rm model.Ru return rf.runner.Run(ctx, test, rm, env) } -func (rf runnerFacade) RunTransaction(ctx context.Context, tr tests.Transaction, rm model.RunMetadata, env environment.Environment) tests.TransactionRun { +func (rf runnerFacade) RunTransaction(ctx context.Context, tr transaction.Transaction, rm model.RunMetadata, env environment.Environment) transaction.TransactionRun { return rf.transactionRunner.Run(ctx, tr, rm, env) } @@ -55,7 +55,7 @@ func newRunnerFacades( dsRepo *datastore.Repository, lintRepo *linterResource.Repository, testDB model.Repository, - transactions *tests.TransactionsRepository, + transactionRunRepository *transaction.RunRepository, appTracer trace.Tracer, tracer trace.Tracer, subscriptionManager *subscription.Manager, @@ -119,7 +119,7 @@ func newRunnerFacades( transactionRunner := executor.NewTransactionRunner( runner, testDB, - transactions, + transactionRunRepository, subscriptionManager, ) diff --git a/server/executor/transaction_run_updater.go b/server/executor/transaction_run_updater.go index d40b1ab515..765da7e31f 100644 --- a/server/executor/transaction_run_updater.go +++ b/server/executor/transaction_run_updater.go @@ -5,11 +5,11 @@ import ( "fmt" "github.com/kubeshop/tracetest/server/subscription" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" ) type TransactionRunUpdater interface { - Update(context.Context, tests.TransactionRun) error + Update(context.Context, transaction.TransactionRun) error } type CompositeTransactionUpdater struct { @@ -23,7 +23,7 @@ func (u CompositeTransactionUpdater) Add(l TransactionRunUpdater) CompositeTrans var _ TransactionRunUpdater = CompositeTransactionUpdater{} -func (u CompositeTransactionUpdater) Update(ctx context.Context, run tests.TransactionRun) error { +func (u CompositeTransactionUpdater) Update(ctx context.Context, run transaction.TransactionRun) error { for _, l := range u.listeners { if err := l.Update(ctx, run); err != nil { return fmt.Errorf("composite updating error: %w", err) @@ -38,14 +38,14 @@ type dbTransactionUpdater struct { } type transactionUpdater interface { - UpdateRun(context.Context, tests.TransactionRun) error + UpdateRun(context.Context, transaction.TransactionRun) error } func NewDBTranasctionUpdater(repo transactionUpdater) TransactionRunUpdater { return dbTransactionUpdater{repo} } -func (u dbTransactionUpdater) Update(ctx context.Context, run tests.TransactionRun) error { +func (u dbTransactionUpdater) Update(ctx context.Context, run transaction.TransactionRun) error { return u.repo.UpdateRun(ctx, run) } @@ -57,7 +57,7 @@ func NewSubscriptionTransactionUpdater(manager *subscription.Manager) Transactio return subscriptionTransactionUpdater{manager} } -func (u subscriptionTransactionUpdater) Update(ctx context.Context, run tests.TransactionRun) error { +func (u subscriptionTransactionUpdater) Update(ctx context.Context, run transaction.TransactionRun) error { u.manager.PublishUpdate(subscription.Message{ ResourceID: run.ResourceID(), Type: "result_update", diff --git a/server/executor/transaction_runner.go b/server/executor/transaction_runner.go index cbf83e1653..991e9a55dd 100644 --- a/server/executor/transaction_runner.go +++ b/server/executor/transaction_runner.go @@ -8,11 +8,11 @@ import ( "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/subscription" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" ) type TransactionRunner interface { - Run(context.Context, tests.Transaction, model.RunMetadata, environment.Environment) tests.TransactionRun + Run(context.Context, transaction.Transaction, model.RunMetadata, environment.Environment) transaction.TransactionRun } type PersistentTransactionRunner interface { @@ -22,7 +22,7 @@ type PersistentTransactionRunner interface { type transactionRunRepository interface { transactionUpdater - CreateRun(context.Context, tests.TransactionRun) (tests.TransactionRun, error) + CreateRun(context.Context, transaction.TransactionRun) (transaction.TransactionRun, error) } func NewTransactionRunner( @@ -48,8 +48,8 @@ func NewTransactionRunner( type transactionRunJob struct { ctx context.Context - transaction tests.Transaction - run tests.TransactionRun + transaction transaction.Transaction + run transaction.TransactionRun } type persistentTransactionRunner struct { @@ -62,7 +62,7 @@ type persistentTransactionRunner struct { exit chan bool } -func (r persistentTransactionRunner) Run(ctx context.Context, transaction tests.Transaction, metadata model.RunMetadata, environment environment.Environment) tests.TransactionRun { +func (r persistentTransactionRunner) Run(ctx context.Context, transaction transaction.Transaction, metadata model.RunMetadata, environment environment.Environment) transaction.TransactionRun { run := transaction.NewRun() run.Metadata = metadata run.Environment = environment @@ -104,18 +104,18 @@ func (r persistentTransactionRunner) Start(workers int) { } } -func (r persistentTransactionRunner) runTransaction(ctx context.Context, transaction tests.Transaction, run tests.TransactionRun) error { - run.State = tests.TransactionRunStateExecuting +func (r persistentTransactionRunner) runTransaction(ctx context.Context, tran transaction.Transaction, run transaction.TransactionRun) error { + run.State = transaction.TransactionRunStateExecuting var err error - for step, test := range transaction.Steps { + for step, test := range tran.Steps { run, err = r.runTransactionStep(ctx, run, step, test) if err != nil { return fmt.Errorf("could not execute step %d of transaction %s: %w", step, run.TransactionID, err) } - if run.State == tests.TransactionRunStateFailed { + if run.State == transaction.TransactionRunStateFailed { break } @@ -126,18 +126,18 @@ func (r persistentTransactionRunner) runTransaction(ctx context.Context, transac } } - if run.State != tests.TransactionRunStateFailed { - run.State = tests.TransactionRunStateFinished + if run.State != transaction.TransactionRunStateFailed { + run.State = transaction.TransactionRunStateFinished } return r.updater.Update(ctx, run) } -func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr tests.TransactionRun, step int, test model.Test) (tests.TransactionRun, error) { +func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr transaction.TransactionRun, step int, test model.Test) (transaction.TransactionRun, error) { testRun := r.testRunner.Run(ctx, test, tr.Metadata, tr.Environment) tr, err := r.updateStepRun(ctx, tr, step, testRun) if err != nil { - return tests.TransactionRun{}, fmt.Errorf("could not update transaction run: %w", err) + return transaction.TransactionRun{}, fmt.Errorf("could not update transaction run: %w", err) } done := make(chan bool) @@ -146,7 +146,7 @@ func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr func(m subscription.Message) error { testRun := m.Content.(model.Run) if testRun.LastError != nil { - tr.State = tests.TransactionRunStateFailed + tr.State = transaction.TransactionRunStateFailed tr.LastError = testRun.LastError } @@ -175,7 +175,7 @@ func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr return tr, err } -func (r persistentTransactionRunner) updateStepRun(ctx context.Context, tr tests.TransactionRun, step int, run model.Run) (tests.TransactionRun, error) { +func (r persistentTransactionRunner) updateStepRun(ctx context.Context, tr transaction.TransactionRun, step int, run model.Run) (transaction.TransactionRun, error) { if len(tr.Steps) <= step { tr.Steps = append(tr.Steps, model.Run{}) } @@ -183,7 +183,7 @@ func (r persistentTransactionRunner) updateStepRun(ctx context.Context, tr tests tr.Steps[step] = run err := r.updater.Update(ctx, tr) if err != nil { - return tests.TransactionRun{}, fmt.Errorf("could not update transaction run: %w", err) + return transaction.TransactionRun{}, fmt.Errorf("could not update transaction run: %w", err) } return tr, nil diff --git a/server/executor/transaction_runner_test.go b/server/executor/transaction_runner_test.go index 40ffc9e525..d018b0ab87 100644 --- a/server/executor/transaction_runner_test.go +++ b/server/executor/transaction_runner_test.go @@ -16,7 +16,7 @@ import ( "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/testdb" "github.com/kubeshop/tracetest/server/testmock" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -68,8 +68,8 @@ func (r *fakeTestRunner) Run(ctx context.Context, test model.Test, metadata mode func TestTransactionRunner(t *testing.T) { t.Run("NoErrors", func(t *testing.T) { - runTransactionRunnerTest(t, false, func(t *testing.T, actual tests.TransactionRun) { - assert.Equal(t, tests.TransactionRunStateFinished, actual.State) + runTransactionRunnerTest(t, false, func(t *testing.T, actual transaction.TransactionRun) { + assert.Equal(t, transaction.TransactionRunStateFinished, actual.State) assert.Len(t, actual.Steps, 2) assert.Equal(t, actual.Steps[0].State, model.RunStateFinished) assert.Equal(t, actual.Steps[1].State, model.RunStateFinished) @@ -91,8 +91,8 @@ func TestTransactionRunner(t *testing.T) { }) t.Run("WithErrors", func(t *testing.T) { - runTransactionRunnerTest(t, true, func(t *testing.T, actual tests.TransactionRun) { - assert.Equal(t, tests.TransactionRunStateFailed, actual.State) + runTransactionRunnerTest(t, true, func(t *testing.T, actual transaction.TransactionRun) { + assert.Equal(t, transaction.TransactionRunStateFailed, actual.State) require.Len(t, actual.Steps, 1) assert.Equal(t, model.RunStateTriggerFailed, actual.Steps[0].State) }) @@ -107,7 +107,7 @@ func getDB() (model.Repository, *sql.DB) { return db, rawDB } -func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *testing.T, actual tests.TransactionRun)) { +func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *testing.T, actual transaction.TransactionRun)) { ctx := context.Background() db, rawDB := getDB() @@ -127,14 +127,15 @@ func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *test require.NoError(t, err) testsRepo, _ := testdb.Postgres(testdb.WithDB(rawDB)) - transactionsRepo := tests.NewTransactionsRepository(rawDB, testsRepo) - transaction, err := transactionsRepo.Create(ctx, tests.Transaction{ + transactionsRepo := transaction.NewRepository(rawDB, testsRepo) + transactionRunRepo := transaction.NewRunRepository(rawDB, testsRepo) + tran, err := transactionsRepo.Create(ctx, transaction.Transaction{ Name: "transaction", StepIDs: []id.ID{test1.ID, test2.ID}, }) require.NoError(t, err) - transaction, err = transactionsRepo.GetAugmented(context.TODO(), transaction.ID) + tran, err = transactionsRepo.GetAugmented(context.TODO(), tran.ID) require.NoError(t, err) metadata := model.RunMetadata{ @@ -154,17 +155,17 @@ func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *test }) require.NoError(t, err) - runner := executor.NewTransactionRunner(testRunner, db, transactionsRepo, subscriptionManager) + runner := executor.NewTransactionRunner(testRunner, db, transactionRunRepo, subscriptionManager) runner.Start(1) ctxWithTimeout, cancel := context.WithTimeout(ctx, 1*time.Second) defer cancel() - transactionRun := runner.Run(ctxWithTimeout, transaction, metadata, env) + transactionRun := runner.Run(ctxWithTimeout, tran, metadata, env) - done := make(chan tests.TransactionRun, 1) + done := make(chan transaction.TransactionRun, 1) sf := subscription.NewSubscriberFunction(func(m subscription.Message) error { - tr := m.Content.(tests.TransactionRun) + tr := m.Content.(transaction.TransactionRun) if tr.State.IsFinal() { done <- tr } @@ -173,7 +174,7 @@ func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *test }) subscriptionManager.Subscribe(transactionRun.ResourceID(), sf) - var finalRun tests.TransactionRun + var finalRun transaction.TransactionRun select { case finalRun = <-done: subscriptionManager.Unsubscribe(transactionRun.ResourceID(), sf.ID()) //cleanup to avoid race conditions diff --git a/server/http/controller.go b/server/http/controller.go index ebbc883945..57930a01c5 100644 --- a/server/http/controller.go +++ b/server/http/controller.go @@ -23,8 +23,8 @@ import ( "github.com/kubeshop/tracetest/server/openapi" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/testdb" - "github.com/kubeshop/tracetest/server/tests" "github.com/kubeshop/tracetest/server/tracedb" + "github.com/kubeshop/tracetest/server/transaction" "go.opentelemetry.io/otel/trace" ) @@ -38,31 +38,34 @@ type controller struct { triggerRegistry *trigger.Registry version string - testDB model.Repository - transactions transactionsRepository - environmentGetter environmentGetter + testDB model.Repository + transactionRepository transactionsRepository + transactionRunRepository transactionRunRepository + environmentGetter environmentGetter } type transactionsRepository interface { - SetID(tests.Transaction, id.ID) tests.Transaction + SetID(transaction.Transaction, id.ID) transaction.Transaction IDExists(ctx context.Context, id id.ID) (bool, error) - ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]tests.Transaction, error) - GetAugmented(context.Context, id.ID) (tests.Transaction, error) + ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]transaction.Transaction, error) + GetAugmented(context.Context, id.ID) (transaction.Transaction, error) Count(ctx context.Context, query string) (int, error) - Get(context.Context, id.ID) (tests.Transaction, error) - GetVersion(context.Context, id.ID, int) (tests.Transaction, error) - Create(context.Context, tests.Transaction) (tests.Transaction, error) - Update(context.Context, tests.Transaction) (tests.Transaction, error) + Get(context.Context, id.ID) (transaction.Transaction, error) + GetVersion(context.Context, id.ID, int) (transaction.Transaction, error) + Create(context.Context, transaction.Transaction) (transaction.Transaction, error) + Update(context.Context, transaction.Transaction) (transaction.Transaction, error) +} - GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (tests.TransactionRun, error) - GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]tests.TransactionRun, error) - DeleteTransactionRun(ctx context.Context, tr tests.TransactionRun) error +type transactionRunRepository interface { + GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (transaction.TransactionRun, error) + GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]transaction.TransactionRun, error) + DeleteTransactionRun(ctx context.Context, tr transaction.TransactionRun) error } type runner interface { StopTest(testID id.ID, runID int) RunTest(ctx context.Context, test model.Test, rm model.RunMetadata, env environment.Environment) model.Run - RunTransaction(ctx context.Context, tr tests.Transaction, rm model.RunMetadata, env environment.Environment) tests.TransactionRun + RunTransaction(ctx context.Context, tr transaction.Transaction, rm model.RunMetadata, env environment.Environment) transaction.TransactionRun RunAssertions(ctx context.Context, request executor.AssertionRequest) } @@ -72,7 +75,8 @@ type environmentGetter interface { func NewController( testDB model.Repository, - transactions transactionsRepository, + transactionRepository transactionsRepository, + transactionRunRepository transactionRunRepository, newTraceDBFn func(ds datastore.DataStore) (tracedb.TraceDB, error), runner runner, mappers mappings.Mappings, @@ -82,15 +86,16 @@ func NewController( version string, ) openapi.ApiApiServicer { return &controller{ - tracer: tracer, - testDB: testDB, - transactions: transactions, - environmentGetter: envGetter, - runner: runner, - newTraceDBFn: newTraceDBFn, - mappers: mappers, - triggerRegistry: triggerRegistry, - version: version, + tracer: tracer, + testDB: testDB, + transactionRepository: transactionRepository, + transactionRunRepository: transactionRunRepository, + environmentGetter: envGetter, + runner: runner, + newTraceDBFn: newTraceDBFn, + mappers: mappers, + triggerRegistry: triggerRegistry, + version: version, } } @@ -532,12 +537,12 @@ func (c *controller) ExecuteDefinition(ctx context.Context, testDefinition opena return openapi.Response(http.StatusUnprocessableEntity, nil), nil } -func (c *controller) executeTransaction(ctx context.Context, transaction tests.Transaction, runInfo openapi.RunInformation) (openapi.ImplResponse, error) { +func (c *controller) executeTransaction(ctx context.Context, tran transaction.Transaction, runInfo openapi.RunInformation) (openapi.ImplResponse, error) { // create or update transaction - resp, err := c.doCreateTransaction(ctx, transaction) + resp, err := c.doCreateTransaction(ctx, tran) if err != nil { if errors.Is(err, errTransactionExists) { - resp, err = c.doUpdateTransaction(ctx, transaction.ID, transaction) + resp, err = c.doUpdateTransaction(ctx, tran.ID, tran) if err != nil { return resp, err } @@ -546,10 +551,10 @@ func (c *controller) executeTransaction(ctx context.Context, transaction tests.T } } else { // the transaction was created, make sure we have the correct ID - transaction = resp.Body.(tests.Transaction) + tran = resp.Body.(transaction.Transaction) } - transactionID := transaction.ID + transactionID := tran.ID // transaction ready, execute it resp, err = c.RunTransaction(ctx, transactionID.String(), runInfo) @@ -565,7 +570,7 @@ func (c *controller) executeTransaction(ctx context.Context, transaction tests.T return openapi.Response(200, res), nil } -func (c *controller) upsertTransaction(ctx context.Context, transaction tests.Transaction) (openapi.ImplResponse, error) { +func (c *controller) upsertTransaction(ctx context.Context, transaction transaction.Transaction) (openapi.ImplResponse, error) { resp, err := c.doCreateTransaction(ctx, transaction) var status int if err != nil { @@ -594,10 +599,10 @@ func (c *controller) upsertTransaction(ctx context.Context, transaction tests.Tr var errTransactionExists = errors.New("transaction already exists") -func (c *controller) doCreateTransaction(ctx context.Context, transaction tests.Transaction) (openapi.ImplResponse, error) { +func (c *controller) doCreateTransaction(ctx context.Context, transaction transaction.Transaction) (openapi.ImplResponse, error) { // if they try to create a transaction with preset ID, we need to make sure that ID doesn't exists already if transaction.HasID() { - exists, err := c.transactions.IDExists(ctx, transaction.ID) + exists, err := c.transactionRepository.IDExists(ctx, transaction.ID) if err != nil { return handleDBError(err), err } @@ -610,14 +615,14 @@ func (c *controller) doCreateTransaction(ctx context.Context, transaction tests. return openapi.Response(http.StatusBadRequest, r), err } } else { - transaction = c.transactions.SetID(transaction, id.GenerateID()) + transaction = c.transactionRepository.SetID(transaction, id.GenerateID()) } - transaction, err := c.transactions.Create(ctx, transaction) + transaction, err := c.transactionRepository.Create(ctx, transaction) if err != nil { return handleDBError(err), err } - transaction, err = c.transactions.GetAugmented(ctx, transaction.ID) + transaction, err = c.transactionRepository.GetAugmented(ctx, transaction.ID) if err != nil { return handleDBError(err), err } @@ -626,7 +631,7 @@ func (c *controller) doCreateTransaction(ctx context.Context, transaction tests. } func (c *controller) GetTransactionVersionDefinitionFile(ctx context.Context, transactionId string, version int32) (openapi.ImplResponse, error) { - transaction, err := c.transactions.GetVersion(ctx, id.ID(transactionId), int(version)) + transaction, err := c.transactionRepository.GetVersion(ctx, id.ID(transactionId), int(version)) if err != nil { return openapi.Response(http.StatusBadRequest, err.Error()), err } @@ -634,8 +639,8 @@ func (c *controller) GetTransactionVersionDefinitionFile(ctx context.Context, tr return openapi.Response(200, transaction), nil } -func (c *controller) doUpdateTransaction(ctx context.Context, transactionID id.ID, updated tests.Transaction) (openapi.ImplResponse, error) { - transaction, err := c.transactions.Get(ctx, transactionID) +func (c *controller) doUpdateTransaction(ctx context.Context, transactionID id.ID, updated transaction.Transaction) (openapi.ImplResponse, error) { + transaction, err := c.transactionRepository.Get(ctx, transactionID) if err != nil { return handleDBError(err), err } @@ -643,7 +648,7 @@ func (c *controller) doUpdateTransaction(ctx context.Context, transactionID id.I updated.Version = transaction.Version updated.ID = transaction.ID - _, err = c.transactions.Update(ctx, updated) + _, err = c.transactionRepository.Update(ctx, updated) if err != nil { return handleDBError(err), err } @@ -812,7 +817,7 @@ func (c *controller) buildDataStores(ctx context.Context, info openapi.ResolveRe } func (c *controller) GetTransactionVersion(ctx context.Context, tID string, version int32) (openapi.ImplResponse, error) { - transaction, err := c.transactions.GetVersion(ctx, id.ID(tID), int(version)) + transaction, err := c.transactionRepository.GetVersion(ctx, id.ID(tID), int(version)) if err != nil { return handleDBError(err), err @@ -823,7 +828,7 @@ func (c *controller) GetTransactionVersion(ctx context.Context, tID string, vers // RunTransaction implements openapi.ApiApiServicer func (c *controller) RunTransaction(ctx context.Context, transactionID string, runInformation openapi.RunInformation) (openapi.ImplResponse, error) { - transaction, err := c.transactions.GetAugmented(ctx, id.ID(transactionID)) + transaction, err := c.transactionRepository.GetAugmented(ctx, id.ID(transactionID)) if err != nil { return handleDBError(err), err } @@ -853,7 +858,7 @@ func (c *controller) RunTransaction(ctx context.Context, transactionID string, r } func (c *controller) GetTransactionRun(ctx context.Context, transactionId string, runId int32) (openapi.ImplResponse, error) { - run, err := c.transactions.GetTransactionRun(ctx, id.ID(transactionId), int(runId)) + run, err := c.transactionRunRepository.GetTransactionRun(ctx, id.ID(transactionId), int(runId)) if err != nil { return handleDBError(err), err } @@ -863,7 +868,7 @@ func (c *controller) GetTransactionRun(ctx context.Context, transactionId string } func (c *controller) GetTransactionRuns(ctx context.Context, transactionId string, take, skip int32) (openapi.ImplResponse, error) { - runs, err := c.transactions.GetTransactionsRuns(ctx, id.ID(transactionId), take, skip) + runs, err := c.transactionRunRepository.GetTransactionsRuns(ctx, id.ID(transactionId), take, skip) if err != nil { return handleDBError(err), err } @@ -877,12 +882,12 @@ func (c *controller) GetTransactionRuns(ctx context.Context, transactionId strin } func (c *controller) DeleteTransactionRun(ctx context.Context, transactionId string, runId int32) (openapi.ImplResponse, error) { - run, err := c.transactions.GetTransactionRun(ctx, id.ID(transactionId), int(runId)) + run, err := c.transactionRunRepository.GetTransactionRun(ctx, id.ID(transactionId), int(runId)) if err != nil { return handleDBError(err), err } - err = c.transactions.DeleteTransactionRun(ctx, run) + err = c.transactionRunRepository.DeleteTransactionRun(ctx, run) if err != nil { return handleDBError(err), err } @@ -893,7 +898,7 @@ func (c *controller) DeleteTransactionRun(ctx context.Context, transactionId str func (c *controller) GetResources(ctx context.Context, take, skip int32, query, sortBy, sortDirection string) (openapi.ImplResponse, error) { // TODO: this is endpoint is a hack to unblock the team quickly. // This is not production ready because it might take too long to respond if there are numerous - // transactions and tests. + // transactions and transaction. if take == 0 { take = 20 @@ -901,12 +906,12 @@ func (c *controller) GetResources(ctx context.Context, take, skip int32, query, newTake := take + skip - transactions, err := c.transactions.ListAugmented(ctx, int(newTake), 0, query, sortBy, sortDirection) + transactions, err := c.transactionRepository.ListAugmented(ctx, int(newTake), 0, query, sortBy, sortDirection) if err != nil { return handleDBError(err), err } - transactionCount, err := c.transactions.Count(ctx, query) + transactionCount, err := c.transactionRepository.Count(ctx, query) if err != nil { return handleDBError(err), err } @@ -931,7 +936,7 @@ func (c *controller) GetResources(ctx context.Context, take, skip int32, query, return openapi.Response(http.StatusOK, paginatedResponse), nil } -func takeResources(transactions []tests.Transaction, tests []openapi.Test, take, skip int32) []openapi.Resource { +func takeResources(transactions []transaction.Transaction, tests []openapi.Test, take, skip int32) []openapi.Resource { numItems := len(transactions) + len(tests) items := make([]openapi.Resource, numItems) maxNumItems := len(transactions) + len(tests) diff --git a/server/http/controller_test.go b/server/http/controller_test.go index 1d329e40a9..eff3d1b64f 100644 --- a/server/http/controller_test.go +++ b/server/http/controller_test.go @@ -120,6 +120,7 @@ func setupController(t *testing.T) controllerFixture { nil, nil, nil, + nil, mappings.New(traces.NewConversionConfig(), comparator.DefaultRegistry(), mdb), nil, &trigger.Registry{}, diff --git a/server/http/mappings/tests.go b/server/http/mappings/tests.go index d359d2d9fb..81550ea438 100644 --- a/server/http/mappings/tests.go +++ b/server/http/mappings/tests.go @@ -12,8 +12,8 @@ import ( "github.com/kubeshop/tracetest/server/openapi" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/maps" - "github.com/kubeshop/tracetest/server/tests" "github.com/kubeshop/tracetest/server/traces" + "github.com/kubeshop/tracetest/server/transaction" "go.opentelemetry.io/otel/trace" ) @@ -31,7 +31,7 @@ func optionalTime(in time.Time) *time.Time { return &in } -func (m OpenAPI) TransactionRun(in tests.TransactionRun) openapi.TransactionRun { +func (m OpenAPI) TransactionRun(in transaction.TransactionRun) openapi.TransactionRun { steps := make([]openapi.TestRun, 0, len(in.Steps)) for _, step := range in.Steps { diff --git a/server/http/validation/variable.go b/server/http/validation/variable.go index b2f0c9c06c..57331d6c81 100644 --- a/server/http/validation/variable.go +++ b/server/http/validation/variable.go @@ -9,7 +9,7 @@ import ( "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/openapi" "github.com/kubeshop/tracetest/server/testdb" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" ) var ErrMissingVariables = errors.New("variables are missing") @@ -86,7 +86,7 @@ func getPreviousEnvironmentValues(ctx context.Context, db model.Repository, test return map[string]environment.EnvironmentValue{}, nil } -func ValidateMissingVariablesFromTransaction(ctx context.Context, db model.Repository, transaction tests.Transaction, env environment.Environment) (openapi.MissingVariablesError, error) { +func ValidateMissingVariablesFromTransaction(ctx context.Context, db model.Repository, transaction transaction.Transaction, env environment.Environment) (openapi.MissingVariablesError, error) { missingVariables := make([]openapi.MissingVariable, 0) for _, step := range transaction.Steps { stepValidationResult, err := ValidateMissingVariables(ctx, db, step, env) diff --git a/server/http/websocket/subscribe.go b/server/http/websocket/subscribe.go index 12283b1ccc..76e09eeabf 100644 --- a/server/http/websocket/subscribe.go +++ b/server/http/websocket/subscribe.go @@ -8,7 +8,7 @@ import ( "github.com/kubeshop/tracetest/server/http/mappings" "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/subscription" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" ) type subscriptionMessage struct { @@ -63,9 +63,9 @@ func (e subscribeCommandExecutor) ResourceUpdatedEvent(resource interface{}) Eve mapped = e.mappers.Out.Run(&v) case *model.Run: mapped = e.mappers.Out.Run(v) - case tests.TransactionRun: + case transaction.TransactionRun: mapped = e.mappers.Out.TransactionRun(v) - case *tests.TransactionRun: + case *transaction.TransactionRun: mapped = e.mappers.Out.TransactionRun(*v) case model.TestRunEvent: mapped = e.mappers.Out.TestRunEvent(v) diff --git a/server/model/yaml/file_test.go b/server/model/yaml/file_test.go index 571562cd32..e79d5edaa5 100644 --- a/server/model/yaml/file_test.go +++ b/server/model/yaml/file_test.go @@ -7,7 +7,7 @@ import ( "github.com/kubeshop/tracetest/server/model/yaml" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/maps" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -331,7 +331,7 @@ func TestTransactionModel(t *testing.T) { cases := []struct { name string in yaml.Transaction - expected tests.Transaction + expected transaction.Transaction }{ { name: "Basic", @@ -341,7 +341,7 @@ func TestTransactionModel(t *testing.T) { Description: "Some transaction", Steps: []string{"345"}, }, - expected: tests.Transaction{ + expected: transaction.Transaction{ ID: id.ID("123"), Name: "Transaction", Description: "Some transaction", diff --git a/server/model/yaml/transaction.go b/server/model/yaml/transaction.go index 7b67727742..ec005cc8c3 100644 --- a/server/model/yaml/transaction.go +++ b/server/model/yaml/transaction.go @@ -5,7 +5,7 @@ import ( dc "github.com/fluidtruck/deepcopy" "github.com/kubeshop/tracetest/server/pkg/id" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" ) type Transaction struct { @@ -16,8 +16,8 @@ type Transaction struct { Steps []string `mapstructure:"steps"` } -func (t Transaction) Model() tests.Transaction { - mt := tests.Transaction{} +func (t Transaction) Model() transaction.Transaction { + mt := transaction.Transaction{} dc.DeepCopy(t, &mt) mt.StepIDs = make([]id.ID, 0, len(t.Steps)) for _, stepID := range t.Steps { diff --git a/server/testdb/mock.go b/server/testdb/mock.go index d8cc3f722b..6d7980eb04 100644 --- a/server/testdb/mock.go +++ b/server/testdb/mock.go @@ -6,7 +6,7 @@ import ( "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/maps" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" "github.com/stretchr/testify/mock" "go.opentelemetry.io/otel/trace" ) @@ -129,24 +129,24 @@ func (m *MockRepository) Drop() error { return args.Error(0) } -func (m *MockRepository) CreateTransaction(_ context.Context, transaction tests.Transaction) (tests.Transaction, error) { - args := m.Called(transaction) - return args.Get(0).(tests.Transaction), args.Error(1) +func (m *MockRepository) CreateTransaction(_ context.Context, t transaction.Transaction) (transaction.Transaction, error) { + args := m.Called(t) + return args.Get(0).(transaction.Transaction), args.Error(1) } -func (m *MockRepository) UpdateTransaction(_ context.Context, transaction tests.Transaction) (tests.Transaction, error) { - args := m.Called(transaction) - return args.Get(0).(tests.Transaction), args.Error(1) +func (m *MockRepository) UpdateTransaction(_ context.Context, t transaction.Transaction) (transaction.Transaction, error) { + args := m.Called(t) + return args.Get(0).(transaction.Transaction), args.Error(1) } -func (m *MockRepository) DeleteTransaction(_ context.Context, transaction tests.Transaction) error { +func (m *MockRepository) DeleteTransaction(_ context.Context, transaction transaction.Transaction) error { args := m.Called(transaction) return args.Error(1) } -func (m *MockRepository) GetLatestTransactionVersion(_ context.Context, id id.ID) (tests.Transaction, error) { +func (m *MockRepository) GetLatestTransactionVersion(_ context.Context, id id.ID) (transaction.Transaction, error) { args := m.Called(id) - return args.Get(0).(tests.Transaction), args.Error(1) + return args.Get(0).(transaction.Transaction), args.Error(1) } func (m *MockRepository) TransactionIDExists(_ context.Context, id id.ID) (bool, error) { @@ -154,15 +154,15 @@ func (m *MockRepository) TransactionIDExists(_ context.Context, id id.ID) (bool, return args.Bool(0), args.Error(1) } -func (m *MockRepository) GetTransactionVersion(_ context.Context, id id.ID, version int) (tests.Transaction, error) { +func (m *MockRepository) GetTransactionVersion(_ context.Context, id id.ID, version int) (transaction.Transaction, error) { args := m.Called(id, version) - return args.Get(0).(tests.Transaction), args.Error(1) + return args.Get(0).(transaction.Transaction), args.Error(1) } -func (m *MockRepository) GetTransactions(_ context.Context, take, skip int32, query, sortBy, sortDirection string) (model.List[tests.Transaction], error) { +func (m *MockRepository) GetTransactions(_ context.Context, take, skip int32, query, sortBy, sortDirection string) (model.List[transaction.Transaction], error) { args := m.Called(take, skip, query, sortBy, sortDirection) - transactions := args.Get(0).([]tests.Transaction) - list := model.List[tests.Transaction]{ + transactions := args.Get(0).([]transaction.Transaction) + list := model.List[transaction.Transaction]{ Items: transactions, TotalCount: len(transactions), } @@ -170,35 +170,35 @@ func (m *MockRepository) GetTransactions(_ context.Context, take, skip int32, qu } // DeleteTransactionRun implements model.Repository -func (m *MockRepository) DeleteTransactionRun(ctx context.Context, run tests.TransactionRun) error { +func (m *MockRepository) DeleteTransactionRun(ctx context.Context, run transaction.TransactionRun) error { args := m.Called(ctx, run) return args.Error(0) } // GetTransactionRun implements model.Repository -func (m *MockRepository) GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (tests.TransactionRun, error) { +func (m *MockRepository) GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (transaction.TransactionRun, error) { args := m.Called(ctx, transactionID, runID) - return args.Get(0).(tests.TransactionRun), args.Error(1) + return args.Get(0).(transaction.TransactionRun), args.Error(1) } -func (m *MockRepository) GetLatestRunByTransactionVersion(_ context.Context, transactionID id.ID, version int) (tests.TransactionRun, error) { +func (m *MockRepository) GetLatestRunByTransactionVersion(_ context.Context, transactionID id.ID, version int) (transaction.TransactionRun, error) { args := m.Called(transactionID, version) - return args.Get(0).(tests.TransactionRun), args.Error(1) + return args.Get(0).(transaction.TransactionRun), args.Error(1) } // GetTransactionsRuns implements model.Repository -func (m *MockRepository) GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]tests.TransactionRun, error) { +func (m *MockRepository) GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]transaction.TransactionRun, error) { args := m.Called(ctx, transactionID, take, skip) - return args.Get(0).([]tests.TransactionRun), args.Error(1) + return args.Get(0).([]transaction.TransactionRun), args.Error(1) } // UpdateTransactionRun implements model.Repository -func (m *MockRepository) UpdateTransactionRun(ctx context.Context, run tests.TransactionRun) error { +func (m *MockRepository) UpdateTransactionRun(ctx context.Context, run transaction.TransactionRun) error { args := m.Called(ctx, run) return args.Error(0) } -func (m *MockRepository) CreateTransactionRun(ctx context.Context, run tests.TransactionRun) error { +func (m *MockRepository) CreateTransactionRun(ctx context.Context, run transaction.TransactionRun) error { args := m.Called(ctx, run) return args.Error(0) } diff --git a/server/testdb/runs.go b/server/testdb/runs.go index 9e500ff5b3..326d8c90fa 100644 --- a/server/testdb/runs.go +++ b/server/testdb/runs.go @@ -13,7 +13,7 @@ import ( "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/id" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" "go.opentelemetry.io/otel/trace" ) @@ -583,7 +583,7 @@ func readRunRow(row scanner) (model.Run, error) { } } -func (td *postgresDB) GetTransactionRunSteps(ctx context.Context, tr tests.TransactionRun) ([]model.Run, error) { +func (td *postgresDB) GetTransactionRunSteps(ctx context.Context, tr transaction.TransactionRun) ([]model.Run, error) { query := selectRunQuery + ` WHERE transaction_run_steps.transaction_run_id = $1 AND transaction_run_steps.transaction_run_transaction_id = $2 ORDER BY test_runs.completed_at ASC diff --git a/server/testdb/tests.go b/server/testdb/tests.go index c906e3f065..5847809dd4 100644 --- a/server/testdb/tests.go +++ b/server/testdb/tests.go @@ -10,7 +10,7 @@ import ( "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/id" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" ) var _ model.TestRepository = &postgresDB{} @@ -381,7 +381,7 @@ func (td *postgresDB) readTestRow(ctx context.Context, row scanner) (model.Test, } } -func (td *postgresDB) GetTransactionSteps(ctx context.Context, transaction tests.Transaction) ([]model.Test, error) { +func (td *postgresDB) GetTransactionSteps(ctx context.Context, transaction transaction.Transaction) ([]model.Test, error) { stmt, err := td.db.Prepare(getTestSQL + testMaxVersionQuery + ` INNER JOIN transaction_steps ts ON t.id = ts.test_id WHERE ts.transaction_id = $1 AND ts.transaction_version = $2 ORDER BY ts.step_number ASC`) if err != nil { diff --git a/server/tests/main_test.go b/server/transaction/main_test.go similarity index 89% rename from server/tests/main_test.go rename to server/transaction/main_test.go index e368a950d9..28c597549a 100644 --- a/server/tests/main_test.go +++ b/server/transaction/main_test.go @@ -1,4 +1,4 @@ -package tests_test +package transaction_test import ( "os" diff --git a/server/transaction/transaction_entities.go b/server/transaction/transaction_entities.go new file mode 100644 index 0000000000..23a4df98d0 --- /dev/null +++ b/server/transaction/transaction_entities.go @@ -0,0 +1,83 @@ +package transaction + +import ( + "time" + + "github.com/kubeshop/tracetest/server/model" + "github.com/kubeshop/tracetest/server/pkg/id" +) + +const ( + TransactionResourceName = "Transaction" + TransactionResourceNamePlural = "Transactions" +) + +type Transaction struct { + ID id.ID `json:"id"` + CreatedAt *time.Time `json:"createdAt,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + Version *int `json:"version,omitempty"` + StepIDs []id.ID `json:"steps"` + Steps []model.Test `json:"fullSteps,omitempty"` + Summary *model.Summary `json:"summary,omitempty"` +} + +func setVersion(t *Transaction, v int) { + t.Version = &v +} + +func (t Transaction) GetVersion() int { + if t.Version == nil { + return 0 + } + return *t.Version +} + +func setCreatedAt(t *Transaction, d time.Time) { + t.CreatedAt = &d +} + +func (t Transaction) GetCreatedAt() time.Time { + if t.CreatedAt == nil { + return time.Time{} + } + return *t.CreatedAt +} + +func (t Transaction) HasID() bool { + return t.ID != "" +} + +func (t Transaction) GetID() id.ID { + return t.ID +} + +func (t Transaction) Validate() error { + return nil +} + +func (t Transaction) NewRun() TransactionRun { + + return TransactionRun{ + TransactionID: t.ID, + TransactionVersion: t.GetVersion(), + CreatedAt: time.Now().UTC(), + State: TransactionRunStateCreated, + Steps: make([]model.Run, 0, len(t.StepIDs)), + CurrentTest: 0, + } +} + +type TransactionRunState string + +const ( + TransactionRunStateCreated TransactionRunState = "CREATED" + TransactionRunStateExecuting TransactionRunState = "EXECUTING" + TransactionRunStateFailed TransactionRunState = "FAILED" + TransactionRunStateFinished TransactionRunState = "FINISHED" +) + +func (rs TransactionRunState) IsFinal() bool { + return rs == TransactionRunStateFailed || rs == TransactionRunStateFinished +} diff --git a/server/tests/transactions.go b/server/transaction/transaction_repository.go similarity index 68% rename from server/tests/transactions.go rename to server/transaction/transaction_repository.go index 6fc27a23d2..406e1f9594 100644 --- a/server/tests/transactions.go +++ b/server/transaction/transaction_repository.go @@ -1,4 +1,4 @@ -package tests +package transaction import ( "context" @@ -9,132 +9,18 @@ import ( "strings" "time" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/sqlutil" ) -const ( - TransactionResourceName = "Transaction" - TransactionResourceNamePlural = "Transactions" -) - -type Transaction struct { - ID id.ID `json:"id"` - CreatedAt *time.Time `json:"createdAt,omitempty"` - Name string `json:"name"` - Description string `json:"description"` - Version *int `json:"version,omitempty"` - StepIDs []id.ID `json:"steps"` - Steps []model.Test `json:"fullSteps,omitempty"` - Summary *model.Summary `json:"summary,omitempty"` -} - -func setVersion(t *Transaction, v int) { - t.Version = &v -} - -func (t Transaction) GetVersion() int { - if t.Version == nil { - return 0 - } - return *t.Version -} - -func setCreatedAt(t *Transaction, d time.Time) { - t.CreatedAt = &d -} - -func (t Transaction) GetCreatedAt() time.Time { - if t.CreatedAt == nil { - return time.Time{} - } - return *t.CreatedAt -} - -func (t Transaction) HasID() bool { - return t.ID != "" -} - -func (t Transaction) GetID() id.ID { - return t.ID -} - -func (t Transaction) Validate() error { - return nil -} - -func (t Transaction) NewRun() TransactionRun { - - return TransactionRun{ - TransactionID: t.ID, - TransactionVersion: t.GetVersion(), - CreatedAt: time.Now().UTC(), - State: TransactionRunStateCreated, - Steps: make([]model.Run, 0, len(t.StepIDs)), - CurrentTest: 0, - } -} - -type TransactionRunState string - -const ( - TransactionRunStateCreated TransactionRunState = "CREATED" - TransactionRunStateExecuting TransactionRunState = "EXECUTING" - TransactionRunStateFailed TransactionRunState = "FAILED" - TransactionRunStateFinished TransactionRunState = "FINISHED" -) - -func (rs TransactionRunState) IsFinal() bool { - return rs == TransactionRunStateFailed || rs == TransactionRunStateFinished -} - -type TransactionRun struct { - ID int - TransactionID id.ID - TransactionVersion int - - // Timestamps - CreatedAt time.Time - CompletedAt time.Time - - // steps - StepIDs []int - Steps []model.Run - - // trigger params - State TransactionRunState - CurrentTest int - - // result info - LastError error - Pass int - Fail int - - Metadata model.RunMetadata - - // environment - Environment environment.Environment -} - -func (tr TransactionRun) ResourceID() string { - return fmt.Sprintf("transaction/%s/run/%d", tr.TransactionID, tr.ID) -} - -func (tr TransactionRun) ResultsCount() (pass, fail int) { - if tr.Steps == nil { - return - } - - for _, step := range tr.Steps { - stepPass, stepFail := step.ResultsCount() - - pass += stepPass - fail += stepFail +func NewRepository(db *sql.DB, stepsRepository stepsRepository) *Repository { + repo := &Repository{ + db: db, + stepsRepository: stepsRepository, } - return + return repo } type stepsRepository interface { @@ -142,37 +28,28 @@ type stepsRepository interface { GetTransactionRunSteps(context.Context, TransactionRun) ([]model.Run, error) } -func NewTransactionsRepository(db *sql.DB, stepsRepository stepsRepository) *TransactionsRepository { - repo := &TransactionsRepository{ - db: db, - stepsRepository: stepsRepository, - } - - return repo -} - -type TransactionsRepository struct { +type Repository struct { db *sql.DB stepsRepository stepsRepository } // needed for test -func (r *TransactionsRepository) DB() *sql.DB { +func (r *Repository) DB() *sql.DB { return r.db } -func (r *TransactionsRepository) SetID(t Transaction, id id.ID) Transaction { +func (r *Repository) SetID(t Transaction, id id.ID) Transaction { t.ID = id return t } -func (r *TransactionsRepository) Provision(ctx context.Context, transaction Transaction) error { +func (r *Repository) Provision(ctx context.Context, transaction Transaction) error { _, err := r.Create(ctx, transaction) return err } -func (r *TransactionsRepository) Create(ctx context.Context, transaction Transaction) (Transaction, error) { +func (r *Repository) Create(ctx context.Context, transaction Transaction) (Transaction, error) { setVersion(&transaction, 1) if transaction.CreatedAt == nil { setCreatedAt(&transaction, time.Now()) @@ -187,7 +64,7 @@ func (r *TransactionsRepository) Create(ctx context.Context, transaction Transac return t, nil } -func (r *TransactionsRepository) Update(ctx context.Context, transaction Transaction) (Transaction, error) { +func (r *Repository) Update(ctx context.Context, transaction Transaction) (Transaction, error) { oldTransaction, err := r.GetLatestVersion(ctx, transaction.ID) if err != nil { return Transaction{}, fmt.Errorf("could not get latest test version while updating test: %w", err) @@ -215,7 +92,7 @@ func (r *TransactionsRepository) Update(ctx context.Context, transaction Transac return t, nil } -func (r *TransactionsRepository) checkIDExists(ctx context.Context, id id.ID) error { +func (r *Repository) checkIDExists(ctx context.Context, id id.ID) error { exists, err := r.IDExists(ctx, id) if err != nil { return err @@ -227,7 +104,7 @@ func (r *TransactionsRepository) checkIDExists(ctx context.Context, id id.ID) er return nil } -func (r *TransactionsRepository) Delete(ctx context.Context, id id.ID) error { +func (r *Repository) Delete(ctx context.Context, id id.ID) error { if err := r.checkIDExists(ctx, id); err != nil { return err } @@ -265,7 +142,7 @@ func (r *TransactionsRepository) Delete(ctx context.Context, id id.ID) error { return tx.Commit() } -func (r *TransactionsRepository) IDExists(ctx context.Context, id id.ID) (bool, error) { +func (r *Repository) IDExists(ctx context.Context, id id.ID) (bool, error) { exists := false row := r.db.QueryRowContext( ctx, @@ -300,7 +177,7 @@ const transactionMaxVersionQuery = ` WHERE t.version = latest_transactions.latest_version ` -func (r *TransactionsRepository) SortingFields() []string { +func (r *Repository) SortingFields() []string { return []string{ "name", "created", @@ -308,15 +185,15 @@ func (r *TransactionsRepository) SortingFields() []string { } } -func (r *TransactionsRepository) ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Transaction, error) { +func (r *Repository) ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Transaction, error) { return r.list(ctx, take, skip, query, sortBy, sortDirection, true) } -func (r *TransactionsRepository) List(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Transaction, error) { +func (r *Repository) List(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Transaction, error) { return r.list(ctx, take, skip, query, sortBy, sortDirection, false) } -func (r *TransactionsRepository) list(ctx context.Context, take, skip int, query, sortBy, sortDirection string, augmented bool) ([]Transaction, error) { +func (r *Repository) list(ctx context.Context, take, skip int, query, sortBy, sortDirection string, augmented bool) ([]Transaction, error) { q, params := listQuery(querySelect(), query, []any{take, skip}) sortingFields := map[string]string{ @@ -372,7 +249,7 @@ func querySelect() string { `) } -func (r *TransactionsRepository) Count(ctx context.Context, query string) (int, error) { +func (r *Repository) Count(ctx context.Context, query string) (int, error) { sql, params := listQuery(queryCount(), query, []any{}) count := 0 @@ -387,15 +264,15 @@ func (r *TransactionsRepository) Count(ctx context.Context, query string) (int, return count, nil } -func (r *TransactionsRepository) GetAugmented(ctx context.Context, id id.ID) (Transaction, error) { +func (r *Repository) GetAugmented(ctx context.Context, id id.ID) (Transaction, error) { return r.get(ctx, id, true) } -func (r *TransactionsRepository) Get(ctx context.Context, id id.ID) (Transaction, error) { +func (r *Repository) Get(ctx context.Context, id id.ID) (Transaction, error) { return r.get(ctx, id, false) } -func (r *TransactionsRepository) get(ctx context.Context, id id.ID, augmented bool) (Transaction, error) { +func (r *Repository) get(ctx context.Context, id id.ID, augmented bool) (Transaction, error) { stmt, err := r.db.Prepare(querySelect() + " WHERE t.id = $1 ORDER BY t.version DESC LIMIT 1") if err != nil { return Transaction{}, fmt.Errorf("prepare: %w", err) @@ -410,7 +287,7 @@ func (r *TransactionsRepository) get(ctx context.Context, id id.ID, augmented bo return transaction, nil } -func (r *TransactionsRepository) GetVersion(ctx context.Context, id id.ID, version int) (Transaction, error) { +func (r *Repository) GetVersion(ctx context.Context, id id.ID, version int) (Transaction, error) { stmt, err := r.db.Prepare(querySelect() + " WHERE t.id = $1 AND t.version = $2") if err != nil { return Transaction{}, fmt.Errorf("prepare 1: %w", err) @@ -435,7 +312,7 @@ func listQuery(baseSQL, query string, params []any) (string, []any) { return sql, params } -func (r *TransactionsRepository) GetLatestVersion(ctx context.Context, id id.ID) (Transaction, error) { +func (r *Repository) GetLatestVersion(ctx context.Context, id id.ID) (Transaction, error) { stmt, err := r.db.Prepare(querySelect() + " WHERE t.id = $1 ORDER BY t.version DESC LIMIT 1") if err != nil { return Transaction{}, fmt.Errorf("prepare: %w", err) @@ -459,7 +336,7 @@ INSERT INTO transactions ( "created_at" ) VALUES ($1, $2, $3, $4, $5)` -func (r *TransactionsRepository) insertIntoTransactions(ctx context.Context, transaction Transaction) (Transaction, error) { +func (r *Repository) insertIntoTransactions(ctx context.Context, transaction Transaction) (Transaction, error) { tx, err := r.db.BeginTx(ctx, &sql.TxOptions{}) defer tx.Rollback() if err != nil { @@ -487,7 +364,7 @@ func (r *TransactionsRepository) insertIntoTransactions(ctx context.Context, tra return r.setTransactionSteps(ctx, tx, transaction) } -func (r *TransactionsRepository) setTransactionSteps(ctx context.Context, tx *sql.Tx, transaction Transaction) (Transaction, error) { +func (r *Repository) setTransactionSteps(ctx context.Context, tx *sql.Tx, transaction Transaction) (Transaction, error) { // delete existing steps stmt, err := tx.Prepare("DELETE FROM transaction_steps WHERE transaction_id = $1 AND transaction_version = $2") if err != nil { @@ -520,7 +397,7 @@ func (r *TransactionsRepository) setTransactionSteps(ctx context.Context, tx *sq return transaction, tx.Commit() } -func (r *TransactionsRepository) readRows(ctx context.Context, rows *sql.Rows, augmented bool) ([]Transaction, error) { +func (r *Repository) readRows(ctx context.Context, rows *sql.Rows, augmented bool) ([]Transaction, error) { transactions := []Transaction{} for rows.Next() { @@ -539,7 +416,7 @@ type scanner interface { Scan(dest ...interface{}) error } -func (r *TransactionsRepository) readRow(ctx context.Context, row scanner, augmented bool) (Transaction, error) { +func (r *Repository) readRow(ctx context.Context, row scanner, augmented bool) (Transaction, error) { transaction := Transaction{ Summary: &model.Summary{}, } diff --git a/server/tests/transactions_test.go b/server/transaction/transaction_repository_test.go similarity index 87% rename from server/tests/transactions_test.go rename to server/transaction/transaction_repository_test.go index 0d8f585f5e..10ede6892e 100644 --- a/server/tests/transactions_test.go +++ b/server/transaction/transaction_repository_test.go @@ -1,4 +1,4 @@ -package tests_test +package transaction_test import ( "context" @@ -14,7 +14,7 @@ import ( rmtests "github.com/kubeshop/tracetest/server/resourcemanager/testutil" "github.com/kubeshop/tracetest/server/testdb" "github.com/kubeshop/tracetest/server/testmock" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -141,12 +141,13 @@ func TestDeleteTestsRelatedToTransactions(t *testing.T) { if err != nil { panic(err) } - transactionRepo := tests.NewTransactionsRepository(db, testsDB) + transactionRepo := transaction.NewRepository(db, testsDB) + transactionRunRepo := transaction.NewRunRepository(db, testsDB) transactionRepo.Create(context.TODO(), transactionSample) f := setupTransactionFixture(t, db) - createTransactionRun(transactionRepo, transactionSample, f.testRun) + createTransactionRun(transactionRepo, transactionRunRepo, transactionSample, f.testRun) testsDB.DeleteTest(context.TODO(), f.t1) testsDB.DeleteTest(context.TODO(), f.t2) @@ -157,7 +158,7 @@ func TestDeleteTestsRelatedToTransactions(t *testing.T) { } -var transactionSample = tests.Transaction{ +var transactionSample = transaction.Transaction{ ID: "NiWVnxP4R", Name: "Verify Import", Description: "check the working of the import flow", @@ -168,7 +169,7 @@ var transactionSample = tests.Transaction{ } func TestTransactions(t *testing.T) { - // sample2 := tests.Transaction{ + // sample2 := transaction.Transaction{ // ID: "sample2", // Name: "Some Transaction", // Description: "Do important stuff", @@ -177,7 +178,7 @@ func TestTransactions(t *testing.T) { // }, // } - // sample3 := tests.Transaction{ + // sample3 := transaction.Transaction{ // ID: "sample3", // Name: "Some Transaction", // Description: "Do important stuff", @@ -187,18 +188,18 @@ func TestTransactions(t *testing.T) { // } rmtests.TestResourceType(t, rmtests.ResourceTypeTest{ - ResourceTypeSingular: tests.TransactionResourceName, - ResourceTypePlural: tests.TransactionResourceNamePlural, + ResourceTypeSingular: transaction.TransactionResourceName, + ResourceTypePlural: transaction.TransactionResourceNamePlural, RegisterManagerFn: func(router *mux.Router, db *sql.DB) resourcemanager.Manager { testsDB, err := testdb.Postgres(testdb.WithDB(db)) if err != nil { panic(err) } - transactionsRepo := tests.NewTransactionsRepository(db, testsDB) + transactionsRepo := transaction.NewRepository(db, testsDB) - manager := resourcemanager.New[tests.Transaction]( - tests.TransactionResourceName, - tests.TransactionResourceNamePlural, + manager := resourcemanager.New[transaction.Transaction]( + transaction.TransactionResourceName, + transaction.TransactionResourceNamePlural, transactionsRepo, resourcemanager.CanBeAugmented(), ) @@ -207,8 +208,10 @@ func TestTransactions(t *testing.T) { return manager }, Prepare: func(t *testing.T, op rmtests.Operation, manager resourcemanager.Manager) { - transactionRepo := manager.Handler().(*tests.TransactionsRepository) + transactionRepo := manager.Handler().(*transaction.Repository) testsDB, err := testdb.Postgres(testdb.WithDB(transactionRepo.DB())) + runRepo := transaction.NewRunRepository(transactionRepo.DB(), testsDB) + if err != nil { panic(err) } @@ -223,17 +226,17 @@ func TestTransactions(t *testing.T) { // test delete with more than 1 run run := setupTests(t, transactionRepo.DB()) - createTransactionRun(transactionRepo, transactionSample, run) + createTransactionRun(transactionRepo, runRepo, transactionSample, run) run = copyRun(testsDB, run) - createTransactionRun(transactionRepo, transactionSample, run) + createTransactionRun(transactionRepo, runRepo, transactionSample, run) case rmtests.OperationListAugmentedSuccess, rmtests.OperationGetAugmentedSuccess: transactionRepo.Create(context.TODO(), transactionSample) run := setupTests(t, transactionRepo.DB()) - createTransactionRun(transactionRepo, transactionSample, run) + createTransactionRun(transactionRepo, runRepo, transactionSample, run) // TODO: reenable this tests when we figure out how to test it // problems: @@ -395,19 +398,19 @@ func compareJSON(t require.TestingT, operation rmtests.Operation, firstValue, se require.JSONEq(t, expected, actual) } -func createTransactionRun(repo *tests.TransactionsRepository, tran tests.Transaction, run model.Run) { - updated, err := repo.GetAugmented(context.TODO(), tran.ID) +func createTransactionRun(transactionRepo *transaction.Repository, runRepo *transaction.RunRepository, tran transaction.Transaction, run model.Run) { + updated, err := transactionRepo.GetAugmented(context.TODO(), tran.ID) if err != nil { panic(err) } - tr, err := repo.CreateRun(context.TODO(), updated.NewRun()) + tr, err := runRepo.CreateRun(context.TODO(), updated.NewRun()) if err != nil { panic(err) } tr.Steps = []model.Run{run} - err = repo.UpdateRun(context.TODO(), tr) + err = runRepo.UpdateRun(context.TODO(), tr) if err != nil { panic(err) } diff --git a/server/transaction/transaction_run_entities.go b/server/transaction/transaction_run_entities.go new file mode 100644 index 0000000000..af17922c71 --- /dev/null +++ b/server/transaction/transaction_run_entities.go @@ -0,0 +1,57 @@ +package transaction + +import ( + "fmt" + "time" + + "github.com/kubeshop/tracetest/server/environment" + "github.com/kubeshop/tracetest/server/model" + "github.com/kubeshop/tracetest/server/pkg/id" +) + +type TransactionRun struct { + ID int + TransactionID id.ID + TransactionVersion int + + // Timestamps + CreatedAt time.Time + CompletedAt time.Time + + // steps + StepIDs []int + Steps []model.Run + + // trigger params + State TransactionRunState + CurrentTest int + + // result info + LastError error + Pass int + Fail int + + Metadata model.RunMetadata + + // environment + Environment environment.Environment +} + +func (tr TransactionRun) ResourceID() string { + return fmt.Sprintf("transaction/%s/run/%d", tr.TransactionID, tr.ID) +} + +func (tr TransactionRun) ResultsCount() (pass, fail int) { + if tr.Steps == nil { + return + } + + for _, step := range tr.Steps { + stepPass, stepFail := step.ResultsCount() + + pass += stepPass + fail += stepFail + } + + return +} diff --git a/server/tests/transaction_runs.go b/server/transaction/transaction_run_repository.go similarity index 87% rename from server/tests/transaction_runs.go rename to server/transaction/transaction_run_repository.go index c026951d7b..5933ff4fda 100644 --- a/server/tests/transaction_runs.go +++ b/server/transaction/transaction_run_repository.go @@ -1,4 +1,4 @@ -package tests +package transaction import ( "context" @@ -12,6 +12,18 @@ import ( "github.com/kubeshop/tracetest/server/pkg/id" ) +func NewRunRepository(db *sql.DB, stepsRepository stepsRepository) *RunRepository { + return &RunRepository{ + db: db, + stepsRepository: stepsRepository, + } +} + +type RunRepository struct { + db *sql.DB + stepsRepository stepsRepository +} + const createTransactionRunQuery = ` INSERT INTO transaction_runs ( "id", @@ -78,7 +90,7 @@ func replaceTransactionRunSequenceName(sql string, transactionID id.ID) string { return strings.ReplaceAll(sql, runSequenceName, seqName) } -func (td *TransactionsRepository) CreateRun(ctx context.Context, tr TransactionRun) (TransactionRun, error) { +func (td *RunRepository) CreateRun(ctx context.Context, tr TransactionRun) (TransactionRun, error) { jsonMetadata, err := json.Marshal(tr.Metadata) if err != nil { return TransactionRun{}, fmt.Errorf("failed to marshal transaction run metadata: %w", err) @@ -150,7 +162,7 @@ UPDATE transaction_runs SET WHERE id = $9 AND transaction_id = $10 ` -func (td *TransactionsRepository) UpdateRun(ctx context.Context, tr TransactionRun) error { +func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error { tx, err := td.db.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("sql beginTx: %w", err) @@ -201,7 +213,7 @@ func (td *TransactionsRepository) UpdateRun(ctx context.Context, tr TransactionR return td.setTransactionRunSteps(ctx, tx, tr) } -func (td *TransactionsRepository) setTransactionRunSteps(ctx context.Context, tx *sql.Tx, tr TransactionRun) error { +func (td *RunRepository) setTransactionRunSteps(ctx context.Context, tx *sql.Tx, tr TransactionRun) error { // delete existing steps stmt, err := tx.Prepare("DELETE FROM transaction_run_steps WHERE transaction_run_id = $1 AND transaction_run_transaction_id = $2") if err != nil { @@ -237,7 +249,7 @@ func (td *TransactionsRepository) setTransactionRunSteps(ctx context.Context, tx return tx.Commit() } -func (td *TransactionsRepository) DeleteTransactionRun(ctx context.Context, tr TransactionRun) error { +func (td *RunRepository) DeleteTransactionRun(ctx context.Context, tr TransactionRun) error { tx, err := td.db.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("sql beginTx: %w", err) @@ -286,7 +298,7 @@ SELECT FROM transaction_runs ` -func (td *TransactionsRepository) GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (TransactionRun, error) { +func (td *RunRepository) GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (TransactionRun, error) { stmt, err := td.db.Prepare(selectTransactionRunQuery + " WHERE id = $1 AND transaction_id = $2") if err != nil { return TransactionRun{}, fmt.Errorf("prepare: %w", err) @@ -303,7 +315,7 @@ func (td *TransactionsRepository) GetTransactionRun(ctx context.Context, transac return run, nil } -func (td *TransactionsRepository) GetLatestRunByTransactionVersion(ctx context.Context, transactionID id.ID, version int) (TransactionRun, error) { +func (td *RunRepository) GetLatestRunByTransactionVersion(ctx context.Context, transactionID id.ID, version int) (TransactionRun, error) { stmt, err := td.db.Prepare(selectTransactionRunQuery + " WHERE transaction_id = $1 AND transaction_version = $2 ORDER BY created_at DESC LIMIT 1") if err != nil { return TransactionRun{}, fmt.Errorf("prepare: %w", err) @@ -320,7 +332,7 @@ func (td *TransactionsRepository) GetLatestRunByTransactionVersion(ctx context.C return run, nil } -func (td *TransactionsRepository) GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]TransactionRun, error) { +func (td *RunRepository) GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]TransactionRun, error) { stmt, err := td.db.Prepare(selectTransactionRunQuery + " WHERE transaction_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3") if err != nil { return []TransactionRun{}, fmt.Errorf("prepare: %w", err) @@ -343,7 +355,7 @@ func (td *TransactionsRepository) GetTransactionsRuns(ctx context.Context, trans return runs, nil } -func (td *TransactionsRepository) readRunRow(row scanner) (TransactionRun, error) { +func (td *RunRepository) readRunRow(row scanner) (TransactionRun, error) { r := TransactionRun{} var ( diff --git a/server/tests/transactions_runs_test.go b/server/transaction/transaction_run_repository_test.go similarity index 56% rename from server/tests/transactions_runs_test.go rename to server/transaction/transaction_run_repository_test.go index ec137972c2..5e6e0babe4 100644 --- a/server/tests/transactions_runs_test.go +++ b/server/transaction/transaction_run_repository_test.go @@ -1,4 +1,4 @@ -package tests_test +package transaction_test import ( "context" @@ -8,7 +8,7 @@ import ( "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/testdb" "github.com/kubeshop/tracetest/server/testmock" - "github.com/kubeshop/tracetest/server/tests" + "github.com/kubeshop/tracetest/server/transaction" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -33,7 +33,7 @@ func createTestWithName(t *testing.T, db model.TestRepository, name string) mode return updated } -func getRepos() (*tests.TransactionsRepository, model.Repository) { +func getRepos() (*transaction.Repository, *transaction.RunRepository, model.Repository) { db := testmock.GetRawTestingDatabase() testsRepo, err := testdb.Postgres(testdb.WithDB(db)) @@ -41,15 +41,17 @@ func getRepos() (*tests.TransactionsRepository, model.Repository) { panic(err) } - transactionRepo := tests.NewTransactionsRepository(db, testsRepo) + transactionRepo := transaction.NewRepository(db, testsRepo) - return transactionRepo, testsRepo + runRepo := transaction.NewRunRepository(db, testsRepo) + + return transactionRepo, runRepo, testsRepo } -func getTransaction(t *testing.T, transactionRepo *tests.TransactionsRepository, testsRepo model.TestRepository) (tests.Transaction, transactionFixture) { +func getTransaction(t *testing.T, transactionRepo *transaction.Repository, testsRepo model.TestRepository) (transaction.Transaction, transactionFixture) { f := setupTransactionFixture(t, transactionRepo.DB()) - transaction := tests.Transaction{ + transaction := transaction.Transaction{ ID: id.NewRandGenerator().ID(), Name: "first test", Description: "description", @@ -69,52 +71,52 @@ func getTransaction(t *testing.T, transactionRepo *tests.TransactionsRepository, } func TestCreateTransactionRun(t *testing.T) { - transactionRepo, testsRepo := getRepos() - transaction, _ := getTransaction(t, transactionRepo, testsRepo) + transactionRepo, transactionRunRepo, testsRepo := getRepos() + transactionObject, _ := getTransaction(t, transactionRepo, testsRepo) - tr, err := transactionRepo.CreateRun(context.TODO(), transaction.NewRun()) + tr, err := transactionRunRepo.CreateRun(context.TODO(), transactionObject.NewRun()) require.NoError(t, err) - assert.Equal(t, tr.TransactionID, transaction.ID) - assert.Equal(t, tr.State, tests.TransactionRunStateCreated) + assert.Equal(t, tr.TransactionID, transactionObject.ID) + assert.Equal(t, tr.State, transaction.TransactionRunStateCreated) assert.Len(t, tr.Steps, 0) } func TestUpdateTransactionRun(t *testing.T) { - transactionRepo, testsRepo := getRepos() - transaction, fixture := getTransaction(t, transactionRepo, testsRepo) + transactionRepo, transactionRunRepo, testsRepo := getRepos() + transactionObject, fixture := getTransaction(t, transactionRepo, testsRepo) - tr, err := transactionRepo.CreateRun(context.TODO(), transaction.NewRun()) + tr, err := transactionRunRepo.CreateRun(context.TODO(), transactionObject.NewRun()) require.NoError(t, err) - tr.State = tests.TransactionRunStateExecuting + tr.State = transaction.TransactionRunStateExecuting tr.Steps = []model.Run{fixture.testRun} - err = transactionRepo.UpdateRun(context.TODO(), tr) + err = transactionRunRepo.UpdateRun(context.TODO(), tr) require.NoError(t, err) - updatedRun, err := transactionRepo.GetTransactionRun(context.TODO(), transaction.ID, tr.ID) + updatedRun, err := transactionRunRepo.GetTransactionRun(context.TODO(), transactionObject.ID, tr.ID) require.NoError(t, err) - assert.Equal(t, tr.TransactionID, transaction.ID) - assert.Equal(t, tests.TransactionRunStateExecuting, updatedRun.State) + assert.Equal(t, tr.TransactionID, transactionObject.ID) + assert.Equal(t, transaction.TransactionRunStateExecuting, updatedRun.State) assert.Len(t, tr.Steps, 1) } func TestDeleteTransactionRun(t *testing.T) { - transactionRepo, testsRepo := getRepos() + transactionRepo, transactionRunRepo, testsRepo := getRepos() transaction, _ := getTransaction(t, transactionRepo, testsRepo) - tr, err := transactionRepo.CreateRun(context.TODO(), transaction.NewRun()) + tr, err := transactionRunRepo.CreateRun(context.TODO(), transaction.NewRun()) require.NoError(t, err) - err = transactionRepo.DeleteTransactionRun(context.TODO(), tr) + err = transactionRunRepo.DeleteTransactionRun(context.TODO(), tr) require.NoError(t, err) - _, err = transactionRepo.GetTransactionRun(context.TODO(), transaction.ID, tr.ID) + _, err = transactionRunRepo.GetTransactionRun(context.TODO(), transaction.ID, tr.ID) require.ErrorContains(t, err, "no rows in result set") } -func createTransaction(t *testing.T, repo *tests.TransactionsRepository, tran tests.Transaction) tests.Transaction { +func createTransaction(t *testing.T, repo *transaction.Repository, tran transaction.Transaction) transaction.Transaction { one := 1 tran.ID = id.GenerateID() tran.Version = &one @@ -131,9 +133,9 @@ func createTransaction(t *testing.T, repo *tests.TransactionsRepository, tran te } func TestListTransactionRun(t *testing.T) { - transactionRepo, testsRepo := getRepos() + transactionRepo, transactionRunRepo, testsRepo := getRepos() - t1 := createTransaction(t, transactionRepo, tests.Transaction{ + t1 := createTransaction(t, transactionRepo, transaction.Transaction{ Name: "first test", Description: "description", Steps: []model.Test{ @@ -142,7 +144,7 @@ func TestListTransactionRun(t *testing.T) { }, }) - t2 := createTransaction(t, transactionRepo, tests.Transaction{ + t2 := createTransaction(t, transactionRepo, transaction.Transaction{ Name: "second transaction", Description: "description", Steps: []model.Test{ @@ -151,16 +153,16 @@ func TestListTransactionRun(t *testing.T) { }, }) - run1, err := transactionRepo.CreateRun(context.TODO(), t1.NewRun()) + run1, err := transactionRunRepo.CreateRun(context.TODO(), t1.NewRun()) require.NoError(t, err) - run2, err := transactionRepo.CreateRun(context.TODO(), t1.NewRun()) + run2, err := transactionRunRepo.CreateRun(context.TODO(), t1.NewRun()) require.NoError(t, err) - _, err = transactionRepo.CreateRun(context.TODO(), t2.NewRun()) + _, err = transactionRunRepo.CreateRun(context.TODO(), t2.NewRun()) require.NoError(t, err) - runs, err := transactionRepo.GetTransactionsRuns(context.TODO(), t1.ID, 20, 0) + runs, err := transactionRunRepo.GetTransactionsRuns(context.TODO(), t1.ID, 20, 0) require.NoError(t, err) assert.Len(t, runs, 2) @@ -169,11 +171,11 @@ func TestListTransactionRun(t *testing.T) { } func TestBug(t *testing.T) { - transactionRepo, testsRepo := getRepos() + transactionRepo, transactionRunRepo, testsRepo := getRepos() ctx := context.TODO() - transaction := createTransaction(t, transactionRepo, tests.Transaction{ + transaction := createTransaction(t, transactionRepo, transaction.Transaction{ Name: "first test", Description: "description", Steps: []model.Test{ @@ -182,13 +184,13 @@ func TestBug(t *testing.T) { }, }) - run1, err := transactionRepo.CreateRun(ctx, transaction.NewRun()) + run1, err := transactionRunRepo.CreateRun(ctx, transaction.NewRun()) require.NoError(t, err) - run2, err := transactionRepo.CreateRun(ctx, transaction.NewRun()) + run2, err := transactionRunRepo.CreateRun(ctx, transaction.NewRun()) require.NoError(t, err) - runs, err := transactionRepo.GetTransactionsRuns(ctx, transaction.ID, 20, 0) + runs, err := transactionRunRepo.GetTransactionsRuns(ctx, transaction.ID, 20, 0) require.NoError(t, err) assert.Equal(t, runs[0].ID, run2.ID) assert.Equal(t, runs[1].ID, run1.ID) @@ -200,10 +202,10 @@ func TestBug(t *testing.T) { newTransaction, err := transactionRepo.GetAugmented(context.TODO(), transaction.ID) require.NoError(t, err) - run3, err := transactionRepo.CreateRun(ctx, newTransaction.NewRun()) + run3, err := transactionRunRepo.CreateRun(ctx, newTransaction.NewRun()) require.NoError(t, err) - runs, err = transactionRepo.GetTransactionsRuns(ctx, newTransaction.ID, 20, 0) + runs, err = transactionRunRepo.GetTransactionsRuns(ctx, newTransaction.ID, 20, 0) require.NoError(t, err) assert.Len(t, runs, 3)