diff --git a/amber/src/test/scala/org/apache/texera/web/ExecutionDatabaseTestSupport.scala b/amber/src/test/scala/org/apache/texera/web/ExecutionDatabaseTestSupport.scala index 1b633e41bbe..9800da2dbed 100644 --- a/amber/src/test/scala/org/apache/texera/web/ExecutionDatabaseTestSupport.scala +++ b/amber/src/test/scala/org/apache/texera/web/ExecutionDatabaseTestSupport.scala @@ -21,12 +21,18 @@ package org.apache.texera.web import org.apache.texera.dao.MockTexeraDB import org.apache.texera.dao.jooq.generated.Tables._ -import org.apache.texera.dao.jooq.generated.enums.{UserRoleEnum, WorkflowComputingUnitTypeEnum} +import org.apache.texera.dao.jooq.generated.enums.{ + PrivilegeEnum, + UserRoleEnum, + WorkflowComputingUnitTypeEnum +} import org.apache.texera.dao.jooq.generated.tables.daos.{ UserDao, WorkflowComputingUnitDao, WorkflowDao, WorkflowExecutionsDao, + WorkflowOfUserDao, + WorkflowUserAccessDao, WorkflowVersionDao } import org.apache.texera.dao.jooq.generated.tables.pojos.{ @@ -34,6 +40,8 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ Workflow, WorkflowComputingUnit, WorkflowExecutions, + WorkflowOfUser, + WorkflowUserAccess, WorkflowVersion } @@ -83,6 +91,13 @@ trait ExecutionDatabaseTestSupport { this: MockTexeraDB => workflow } + protected def insertWorkflowOfUser(uid: Int, wid: Int): Unit = + new WorkflowOfUserDao(getDSLContext.configuration()).insert(new WorkflowOfUser(uid, wid)) + + protected def insertWorkflowUserAccess(uid: Int, wid: Int, privilege: PrivilegeEnum): Unit = + new WorkflowUserAccessDao(getDSLContext.configuration()) + .insert(new WorkflowUserAccess(uid, wid, privilege)) + protected def insertWorkflowVersion( wid: Int, vidOpt: Option[Int] = None, diff --git a/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala index b9a3a6908ff..5fd8c72d174 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/CollaborationResourceSpec.scala @@ -20,7 +20,7 @@ package org.apache.texera.web.resource import org.apache.texera.amber.util.JSONUtils -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.{USER, WORKFLOW, WORKFLOW_USER_ACCESS} import org.apache.texera.dao.jooq.generated.enums.{PrivilegeEnum, UserRoleEnum} import org.apache.texera.dao.jooq.generated.tables.daos.{ @@ -32,9 +32,6 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{User, Workflow, Workfl import org.apache.texera.web.model.collab.request._ import org.apache.texera.web.resource.CollaborationResource._ import org.scalamock.scalatest.MockFactory -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers import java.sql.Timestamp import java.util.concurrent.{Future => JFuture} @@ -59,13 +56,7 @@ import scala.collection.mutable.ArrayBuffer // throws where TryLockRequest copes. Case (2) predates this spec and is pinned // by "AcquireLockRequest should rethrow when the holder slot holds the null // sentinel" as current behaviour, not as desired behaviour. -class CollaborationResourceSpec - extends AnyFlatSpec - with Matchers - with MockFactory - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class CollaborationResourceSpec extends DatabaseFlatSpec(cleanupAfterEach = true) with MockFactory { private var resource: CollaborationResource = _ @@ -79,31 +70,18 @@ class CollaborationResourceSpec // session: with one uid the privilege predicate cannot be observed at all. private val readOnlyUid = 8202 - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - } - - override protected def afterAll(): Unit = { - closeConnectionPool() - } - // The five maps live on the companion object, i.e. they are JVM-wide mutable // state shared by every test in the suite. Clearing them here is what keeps // this spec order-independent. - override def beforeEach(): Unit = { + override protected def onBeforeEach(): Unit = { sessionIdSessionMap.clear() sessionIdWIdMap.clear() sessionIdUIdMap.clear() wIdSessionIdsMap.clear() wIdLockHolderSessionIdMap.clear() - cleanupAccess() resource = new CollaborationResource() } - override def afterEach(): Unit = { - cleanupAccess() - } - // Seeds user accessUid + workflow accessWid + a workflow_user_access row with // the given privilege, so WorkflowAccess.getPrivilege(accessWid, // accessUid) returns it. @@ -135,7 +113,7 @@ class CollaborationResourceSpec ) } - private def cleanupAccess(): Unit = { + override protected def cleanup(): Unit = { getDSLContext .deleteFrom(WORKFLOW_USER_ACCESS) .where(WORKFLOW_USER_ACCESS.WID.eq(accessWid)) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala index 8de8f124e79..4d35bd3c529 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/DatasetSearchQueryBuilderSpec.scala @@ -22,7 +22,7 @@ package org.apache.texera.web.resource.dashboard import com.sun.net.httpserver.{HttpExchange, HttpServer} import org.apache.texera.auth.SessionUser import org.apache.texera.common.config.StorageConfig -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.enums.{PrivilegeEnum, UserRoleEnum} import org.apache.texera.dao.jooq.generated.tables.daos.{DatasetDao, DatasetUserAccessDao, UserDao} import org.apache.texera.dao.jooq.generated.tables.pojos.{Dataset, DatasetUserAccess, User} @@ -30,10 +30,13 @@ import org.apache.texera.web.resource.dashboard.DashboardResource.{ DashboardClickableFileEntry, SearchQueryParams } +import org.apache.texera.web.resource.dashboard.VersionedSearchQuerySupport.{ + assertProjection, + params, + renderSearch +} import org.jooq.Record -import org.scalatest.{BeforeAndAfterAll, OptionValues} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.scalatest.OptionValues import java.io.IOException import java.net.{InetSocketAddress, URI} @@ -42,132 +45,20 @@ import java.util.concurrent.{ExecutorService, Executors} import scala.jdk.CollectionConverters._ /** - * Covers `DatasetSearchQueryBuilder` from both ends: the shape of the SQL it builds, and the - * `DashboardClickableFileEntry` it turns a fetched row into. - * - * == Part 1: which datasets a caller may see == - * - * Every member of the builder is `override protected`, so the query side is reachable only through - * the trait's `final constructQuery`, and what it returns can be rendered to SQL and inspected - * without executing it — those are assertions about the query's *shape*. Three branches decide - * visibility and nothing else tests them: - * - * - the join predicate `.and(if (uid == null) DSL.falseCondition() else DATASET_USER_ACCESS.UID.eq(uid))`, - * which scopes the grant rows to the caller. Without the `eq(uid)` the `UID.isNotNull` check - * below matches *anyone's* grant row, which is a complete sharing bypass; - * - the anonymous arm, which must restrict to public datasets and nothing else; - * - `includePublic == false`, which must return only explicitly-granted datasets and must not - * leak public ones in. - * - * == Part 2: what a row becomes == - * - * `toEntryImpl` is `override protected` here (the workflow and project siblings widen theirs to - * `override def`), so it is not directly callable. The route in is the trait's public `toEntry`, - * which first runs `UnifiedResourceSchema.translateRecord` — so the record handed to it must carry - * the *aliased* select fields, not raw `DATASET.*` fields. Rather than hand-build that record, - * these tests fetch the builder's own query and pass a real row, which is exactly what - * `DashboardResource.searchAllResources` does. - * - * A record permutation is invisible from this end. `translateRecord` writes each aliased value back - * to the very column the schema paired it with (`UnifiedResourceSchema:174`), so ANY swap of two - * same-typed schema assignments — `name`/`description`, `is_public`/`is_downloadable`, - * `did`/`ownerId` — cancels out exactly and produces a byte-identical entry. What the entry-level - * column assertions below really pin is that each slot still references *some* `DATASET` column - * (wire a slot to a literal and `translateRecord` drops the field, so the value reads back null). - * The projections are pinned where a permutation is actually visible: the SQL-shape test - * "project every dataset column under the alias its schema slot names". - * - * `toEntryImpl` also calls `LakeFSStorageClient.retrieveRepositorySize`, which is a live HTTP call - * with no injectable seam. Two non-obvious things make it testable anyway: - * - * - **The stub binds AT the configured endpoint** (`StorageConfig.lakefsEndpoint`, i.e. - * `localhost:8000`) instead of repointing that endpoint at an ephemeral port. This is - * deliberate. `LakeFSStorageClient.apiClient` is a `lazy val` that captures the endpoint once - * per JVM, and `amber/build.sbt` runs every suite in ONE unforked JVM - * (`Tags.limit(Tags.Test, 1)` serializes them but does not isolate them). Mutating the global - * `StorageConfig.lakefsEndpoint` here would therefore be order-dependent — any earlier suite - * that forced `apiClient` wins — and would leave the client bound to a dead port for every - * later suite. Binding at the address the config already names is order-independent and - * memoizes nothing wrongly. The price is that the port is machine-global: if something else - * holds it (a local `bin/local-dev.sh up` lakeFS, or a sibling worktree running these tests), - * the six tests that need a *successful* size `cancel` rather than fail. CI has no lakeFS in - * this job, so it is deterministic there. - * - * A cancel is louder than it looks, and the sbt log shows it only as `canceled 6` while the - * build stays green. It disarms the whole `toEntry` half of this suite: not just its coverage - * (which falls back toward the ~59% this file had before), but every assertion protecting - * `toEntryImpl` — the owner-email pair included, so the `new User` mutant this suite otherwise - * kills goes unnoticed too. Measured: with the port held, mutating `size` to `0L` in - * `VersionedResourceTables.hydrate` leaves `succeeded 18, failed 0, canceled 6` and sbt printing - * "All tests passed" at exit 0. The - * assertions in the SQL-shape tests are unaffected, because they render rather than fetch and - * never call lakeFS — that is the half that stays armed everywhere (verified: with the port - * held, breaking a projection or a where-clause connective still fails the build). - * - **The `null`-return test needs no stub at all.** Connection-refused, 404 and 501 all surface - * as `io.lakefs.clients.sdk.ApiException` (`ApiClient` wraps `IOException` in one, and non-2xx - * throws one directly), so that test behaves identically whether the stub bound or not. - * - * The stub is ~50 lines duplicated in spirit from - * `common/workflow-core/.../LakeFSStorageClientSpec`. It cannot be shared: `build.sbt` gives - * `WorkflowExecutionService` a test->test dependency on `DAO` and `Auth` only, so workflow-core's - * test tree is not on this module's test classpath. + * Pins the rendered visibility and projection rules and hydrates rows fetched through the + * production builder. SQL assertions catch swapped aliases that translateRecord can reverse + * during hydration, and distinguish the owner join from a join on the caller's access row. * - * The keyword tests RENDER a full-text predicate (they do not fetch one), and rendering reads the - * JVM-global `FulltextSearchQueryUtils.usePgroonga`: the `pgroonga_condition(...)` arm while it - * holds `true`, the `to_tsvector`/`to_tsquery` arm while it holds `false`. That flag is a plain - * mutable `var` and amber has no `Test / fork`, so its value here is whatever the suites sharing - * this JVM have left it at — not something this spec controls or should assume. This suite - * therefore neither touches nor restores it, and every keyword assertion here is deliberately - * branch-independent. Two things reach both arms: the `coalesce(...) || ' ' || coalesce(...)` - * expression, built in `FulltextSearchQueryUtils` as `combinedFields` before the `if (usePgroonga)` - * branch and embedded verbatim by either arm, and each INDIVIDUAL keyword token. Their JOINING does - * not — the `true` arm space-joins the full keyword list into one literal (rendering - * `pgroonga_condition('alpha beta', ...)`), while the `false` arm emits one predicate per keyword - * and joins the words *inside* a keyword with ` & ` (rendering `to_tsquery('english', 'alpha & beta')`). - * `to_tsquery('english', 'alpha & beta')`). So assert on individual tokens — never on a joined - * multi-token string, and never on one arm's own output; either would tie this spec's result to - * whichever other suites wrote the flag first. + * Keyword assertions work under either full-text mode: they match tokens and the shared field + * expression because usePgroonga is JVM-wide and may have been set by another suite. * - * The owner email read in `VersionedResourceTables.hydrate` used to be unobservable. The dataset - * schema left `UnifiedResourceSchema`'s `userEmail` at its - * `DSL.inline("")` default, so the translated record carried no `USER` column, - * `DashboardDataset.ownerEmail` was ALWAYS null for dataset search results, and the owner - * `leftJoin(USER)` was a join that was selected from and never read. Replacing that read with a bare - * `new User` therefore changed nothing. The schema now names `userEmail = USER.EMAIL` and the value - * is asserted below, which kills that mutant; the owner-email tests are the ones that hold it dead, - * so a schema slot silently dropped again fails them. - * - * The slot now lives in the base rather than here, which is what stops the next versioned resource - * from repeating the bug: `hydrate` is `final` on `VersionedResourceTables` and reads `USER.EMAIL` - * for EVERY versioned resource, so `VersionedResourceSearchQueryBuilder` builds the whole projection - * — `userEmail` included — as a `final lazy val` a subclass cannot replace, and takes only the three - * columns its descriptor does not already name. A new resource type therefore gets the owner email - * whether or not its author thinks about it, and the projection assertion below guards the base for - * every subclass instead of just this one. - * - * Not covered, and not coverable from a test: - * - `constructFromClause`'s `includePublic: Boolean = false` default. `scalac` emits - * `constructFromClause$default$3`, but `constructQuery` always passes all three arguments, so - * it has zero call sites and the method is `protected`. - * - the `LazyLogging` `logger` lazy-val bitmap on the `object` line, and scala-logging's - * `if (underlying.isErrorEnabled)` guard around `logger.error`. Only the enabled arm ever runs. - * - three of the six branch arms of `dataset.getOwnerUid == uid` (JaCoCo reports cb=3, mb=3). - * They are the null-safe boxed-`Integer` equality's null checks, and they describe a null - * `owner_uid` — a state `INT NOT NULL` plus an FK to `"user"(uid)` forbids. - * - `class DatasetSearchQueryBuilder {}` at the bottom of the file: a vestigial empty class with - * zero references repo-wide. It should be deleted, not instantiated by a test. - * - * Covered but unconstrainable, so no reviewer should count it as pinned behaviour: - * - the `.filter(_.nonEmpty)` after the keyword split. `getFullTextSearchFilter` re-applies - * `keywords.map(_.trim).filter(_.nonEmpty)` itself (`FulltextSearchQueryUtils:43`), so - * dropping it here is an equivalent mutation — no observable differs. + * LakeFS caches its configured endpoint. The stub binds there for the duration of this suite + * without changing StorageConfig. If the port is occupied, successful hydration cases cancel + * while the SQL tests and missing-repository case still run. */ class DatasetSearchQueryBuilderSpec - extends AnyFlatSpec - with Matchers - with OptionValues - with BeforeAndAfterAll - with MockTexeraDB { + extends DatabaseFlatSpec(cleanupBeforeEach = false) + with OptionValues { private val uid: Integer = Integer.valueOf(42) @@ -292,9 +183,7 @@ class DatasetSearchQueryBuilderSpec access } - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - + override protected def onBeforeAll(): Unit = { val cfg = getDSLContext.configuration() new UserDao(cfg) .insert(user(ownerUid, "dataset_search_owner"), user(otherUid, "dataset_search_other")) @@ -318,11 +207,9 @@ class DatasetSearchQueryBuilderSpec } } - override protected def afterAll(): Unit = { - try { - if (server != null) server.stop(0) - if (serverPool != null) serverPool.shutdownNow() - } finally shutdownDB() + override protected def onAfterAll(): Unit = { + if (server != null) server.stop(0) + if (serverPool != null) serverPool.shutdownNow() } /** Runs `body` with the owner's own grant row replaced by `privilege`, or removed, then restores it. */ @@ -337,22 +224,12 @@ class DatasetSearchQueryBuilderSpec } } - private def params(keywords: String*): SearchQueryParams = - SearchQueryParams(keywords = keywords.toList.asJava) - - /** - * The query rendered with its bind values inlined, lower-cased and with the identifier quoting - * stripped, so assertions read as `dataset.is_public` rather than `"texera_db"."dataset"."is_public"`. - */ private def sqlFor( - callerUid: Integer, + uid: Integer, includePublic: Boolean, p: SearchQueryParams = params() ): String = - getDSLContext - .renderInlined(DatasetSearchQueryBuilder.constructQuery(callerUid, p, includePublic)) - .toLowerCase - .replace("\"", "") + renderSearch(getDSLContext, DatasetSearchQueryBuilder, uid, p, includePublic) /** One row of the builder's own query, narrowed to a single dataset id. */ private def rowFor(callerUid: Integer, did: Integer): Record = { @@ -533,40 +410,8 @@ class DatasetSearchQueryBuilderSpec } it should "project every dataset column under the alias its schema slot names" in { - // `toEntry` cannot see a mistake here at all. `UnifiedResourceSchema.translateRecord` writes - // every alias back to the column the schema paired it with, so swapping ANY two same-typed - // assignments — name/description, is_public/is_downloadable, did/ownerId — cancels out by the - // time `toEntryImpl` reads the record and yields a byte-identical entry. The rendered SELECT is - // the only place a permutation is visible. - // - // A permutation is not harmless downstream. `DashboardResource.getOrderFields` sorts on - // `resourceName` (its "Name" case, DashboardResource:168) and on `resourceCreationTime` (its - // "CreateTime" case), both by alias, so a swap silently re-points dashboard sorting. It is NOT - // the frontend that reads these aliases: `searchAllResources` consumes each record into a - // `DashboardClickableFileEntry` and returns those, so no alias survives into the HTTP response. - // `resourceDescription` in fact has no production reader at all today — - // `UnifiedResourceSchema.resourceDescriptionField` is referenced nowhere and `getColumnField` - // has no "Description" case — which is worth an issue of its own; it is pinned here anyway - // because the schema slot is what a copy-paste between builders gets wrong. val sql = sqlFor(uid, includePublic = true) - - sql should include("dataset.name as resourcename") - sql should include("dataset.description as resourcedescription") - sql should include("dataset.creation_time as resourcecreationtime") - sql should include("dataset.owner_uid as resourceownerid") - sql should include("dataset.repository_name as repository_name") - // The id/publicity/privilege/cover slots are shared with the other versioned resources, - // so their aliases are resource-neutral while the columns feeding them are the dataset's. - sql should include("dataset.did as versioned_resource_id") - sql should include("dataset.is_public as is_versioned_resource_public") - sql should include("dataset.is_downloadable as is_versioned_resource_downloadable") - sql should include("dataset_user_access.privilege as user_versioned_resource_access") - sql should include("dataset.cover_image as versioned_resource_cover_image") - // The one projected column that is not a DATASET column, and the one this schema used to leave - // at its `DSL.inline("")` default. It gets an assertion of its own rather than trusting the - // entry-level test because it is now the base class's slot, not this builder's: dropping it from - // `VersionedResourceSearchQueryBuilder` renders `'' as email` for every versioned resource, and - // this names the missing slot instead of surfacing as a null three layers downstream. + assertProjection(sql, "dataset", "did") sql should include("user.email as email") } @@ -707,7 +552,6 @@ class DatasetSearchQueryBuilderSpec // from them; without it a dataset whose repository is gone is shown to the user as 0 bytes. DatasetSearchQueryBuilder.toEntry(ownerUid, rowFor(ownerUid, goneDid)) shouldBe null } - // The search's side of that null, and no stub needed for the same reason. "DashboardResource.searchAllResources" should "flag a mismatch for a dataset lakeFS rejects" in { val result = DashboardResource.searchAllResources( diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/ModelSearchQueryBuilderSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/ModelSearchQueryBuilderSpec.scala index 10a06ff2d28..de1e45671d5 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/ModelSearchQueryBuilderSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/ModelSearchQueryBuilderSpec.scala @@ -19,11 +19,13 @@ package org.apache.texera.web.resource.dashboard -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec +import org.apache.texera.web.resource.dashboard.VersionedSearchQuerySupport.{ + assertProjection, + params, + renderSearch +} import org.apache.texera.web.resource.dashboard.DashboardResource.SearchQueryParams -import org.scalatest.BeforeAndAfterAll -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers import scala.jdk.CollectionConverters._ @@ -38,50 +40,21 @@ import scala.jdk.CollectionConverters._ * `FulltextSearchQueryUtils` builds before its pgroonga/tsvector branch — an assertion on either * arm would depend on which suites ran earlier in the JVM. */ -class ModelSearchQueryBuilderSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with MockTexeraDB { +class ModelSearchQueryBuilderSpec extends DatabaseFlatSpec(cleanupBeforeEach = false) { private val callerUid: Integer = Integer.valueOf(9201) - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - } - - override protected def afterAll(): Unit = { - shutdownDB() - } - - private def params(keywords: String*): SearchQueryParams = - SearchQueryParams(keywords = keywords.toList.asJava) - private def sqlFor( uid: Integer, includePublic: Boolean, p: SearchQueryParams = params() ): String = - getDSLContext - .renderInlined(ModelSearchQueryBuilder.constructQuery(uid, p, includePublic)) - .toLowerCase - .replace("\"", "") + renderSearch(getDSLContext, ModelSearchQueryBuilder, uid, p, includePublic) "the projection" should "carry every model column under the alias its schema slot names" in { val sql = sqlFor(callerUid, includePublic = true) - sql should include("'model' as resourcetype") - sql should include("model.name as resourcename") - sql should include("model.description as resourcedescription") - sql should include("model.creation_time as resourcecreationtime") - sql should include("model.owner_uid as resourceownerid") - sql should include("model.repository_name as repository_name") - // Shared with the other versioned resources, hence the resource-neutral aliases. - sql should include("model.mid as versioned_resource_id") - sql should include("model.is_public as is_versioned_resource_public") - sql should include("model.is_downloadable as is_versioned_resource_downloadable") - sql should include("model_user_access.privilege as user_versioned_resource_access") - sql should include("model.cover_image as versioned_resource_cover_image") + assertProjection(sql, "model", "mid") } it should "carry framework and format, which no other resource projects" in { @@ -92,7 +65,7 @@ class ModelSearchQueryBuilderSpec } it should "leave the workflow and dataset-only slots null" in { - // The union requires all builders to project the same 23 columns in the same order. + // The union requires all builders to project the same columns in the same order. val sql = sqlFor(callerUid, includePublic = true) sql should include("cast(null as int) as wid") diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/UserDashboardFixtureSupport.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/UserDashboardFixtureSupport.scala new file mode 100644 index 00000000000..0c9da2363d3 --- /dev/null +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/UserDashboardFixtureSupport.scala @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.web.resource.dashboard + +import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.jooq.generated.tables.daos._ +import org.apache.texera.dao.jooq.generated.tables.pojos._ +import org.apache.texera.web.ExecutionDatabaseTestSupport +import org.jooq.DSLContext + +import java.sql.Timestamp +import java.util.UUID + +private[dashboard] trait DashboardWorkflowFixtureSupport extends ExecutionDatabaseTestSupport { + self: MockTexeraDB => + protected lazy val workflowDao = new WorkflowDao(getDSLContext.configuration()) + + protected def uniqueSuffix: String = UUID.randomUUID().toString.substring(0, 8) + protected def now: Timestamp = new Timestamp(System.currentTimeMillis()) + + protected def fixtureUser(uid: Int, name: String): User = { + val user = new User + user.setUid(uid) + user.setName(name) + user.setEmail(s"$name@test.com") + user + } + + protected def fixtureWorkflow( + wid: Int, + name: String, + description: String, + isPublic: java.lang.Boolean + ): Workflow = { + val workflow = new Workflow + workflow.setWid(wid) + workflow.setName(name) + workflow.setContent("{}") + workflow.setDescription(description) + workflow.setIsPublic(isPublic) + workflow.setCreationTime(now) + workflow.setLastModifiedTime(now) + workflow + } +} + +private[dashboard] trait UserDashboardFixtureSupport extends DashboardWorkflowFixtureSupport { + self: MockTexeraDB => + protected lazy val userDao = new UserDao(getDSLContext.configuration()) + private lazy val datasetDao = new DatasetDao(getDSLContext.configuration()) + + protected def seedDataset(uid: Int, namePrefix: String): Dataset = { + val dataset = new Dataset + dataset.setOwnerUid(uid) + dataset.setName(namePrefix + uniqueSuffix) + dataset.setRepositoryName("repo-" + uniqueSuffix) + dataset.setIsPublic(false) + dataset.setIsDownloadable(true) + dataset.setDescription("") + dataset.setCreationTime(now) + datasetDao.insert(dataset) + dataset + } +} + +/** Creates the accounts used by warehouse endpoint and workflow selection tests. */ +private[web] object WarehouseAccountFixture { + def seed(context: DSLContext, name: String, avatar: Option[String] = None): User = { + val user = new User + user.setName(name) + user.setEmail(s"user_${UUID.randomUUID()}@example.com") + avatar.foreach(user.setAvatar) + new UserDao(context.configuration()).insert(user) + user + } +} diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala index abd7e486d77..98812e90856 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedResourceTablesSpec.scala @@ -19,14 +19,13 @@ package org.apache.texera.web.resource.dashboard -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum import org.apache.texera.dao.jooq.generated.tables.pojos.{Dataset, Model} import org.apache.texera.web.resource.dashboard.DashboardResource.SearchQueryParams +import org.apache.texera.web.resource.dashboard.VersionedSearchQuerySupport.renderSql import org.apache.texera.web.resource.dashboard.hub.EntityTables -import org.scalatest.BeforeAndAfterAll -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.jooq.Record import scala.jdk.CollectionConverters._ @@ -35,25 +34,11 @@ import scala.jdk.CollectionConverters._ * wrong column still compiles and runs — it just queries the wrong field. SQL is rendered, * never executed. `repositorySize` is uncovered: live LakeFS call, no mockable seam. */ -class VersionedResourceTablesSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with MockTexeraDB { +class VersionedResourceTablesSpec extends DatabaseFlatSpec(cleanupBeforeEach = false) { private val tables = VersionedResourceTables.DatasetTables private val modelTables = VersionedResourceTables.ModelTables - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - } - - override protected def afterAll(): Unit = { - shutdownDB() - } - - private def rendered(sql: String): String = sql.toLowerCase.replace("\"", "") - private def model(mid: Int, ownerUid: Int, repositoryName: String): Model = { val m = new Model m.setMid(Integer.valueOf(mid)) @@ -70,14 +55,33 @@ class VersionedResourceTablesSpec d } + private def assertColumns[R <: Record, P]( + descriptor: VersionedResourceTables[R, P], + table: String, + id: String + ): Unit = { + descriptor.table.getName shouldBe table + descriptor.idColumn.getName shouldBe id + descriptor.isPublicColumn.getName shouldBe "is_public" + descriptor.nameColumn.getName shouldBe "name" + descriptor.descriptionColumn.getName shouldBe "description" + descriptor.creationTimeColumn.getName shouldBe "creation_time" + descriptor.ownerUidColumn.getName shouldBe "owner_uid" + } + + private def assertAccessAndOwnerJoin[R <: Record, P]( + descriptor: VersionedResourceTables[R, P], + table: String, + id: String + ): Unit = { + val sql = renderSql(getDSLContext.render(descriptor.joinWithAccessAndOwner(None))) + sql should include regex (s"${table}_user_access\\.$id = [\\w.]*$table\\.$id") + sql should include regex (s"user\\.uid = [\\w.]*$table\\.owner_uid") + sql.split("left outer join").length shouldBe 3 + } + "DatasetTables" should "name every column the shared query logic reads" in { - tables.table.getName shouldBe "dataset" - tables.idColumn.getName shouldBe "did" - tables.isPublicColumn.getName shouldBe "is_public" - tables.nameColumn.getName shouldBe "name" - tables.descriptionColumn.getName shouldBe "description" - tables.creationTimeColumn.getName shouldBe "creation_time" - tables.ownerUidColumn.getName shouldBe "owner_uid" + assertColumns(tables, "dataset", "did") } it should "share the hub's access table rather than naming it twice" in { @@ -118,25 +122,19 @@ class VersionedResourceTablesSpec } "joinWithAccessAndOwner" should "join the access rows and the owner" in { - // Rendered names are schema-qualified (texera_db.dataset.did), hence the regex. - val sql = rendered(getDSLContext.render(tables.joinWithAccessAndOwner(None))) - - sql should include regex "dataset_user_access\\.did = [\\w.]*dataset\\.did" - sql should include regex "user\\.uid = [\\w.]*dataset\\.owner_uid" - // Both joins are outer: a resource with no grant row must still appear. - sql.split("left outer join").length shouldBe 3 + assertAccessAndOwnerJoin(tables, "dataset", "did") } it should "leave the access rows unfiltered when no condition is given" in { // The hub's call: every grant row. - val sql = rendered(getDSLContext.render(tables.joinWithAccessAndOwner(None))) + val sql = renderSql(getDSLContext.render(tables.joinWithAccessAndOwner(None))) sql should not include "dataset_user_access.uid =" } it should "narrow the access rows when a condition is given" in { // The search's call. Without the predicate, `uid is not null` matches anybody's grant. - val sql = rendered( + val sql = renderSql( getDSLContext.renderInlined( tables.joinWithAccessAndOwner(Some(tables.access.uidColumn.eq(Integer.valueOf(42)))) ) @@ -147,25 +145,19 @@ class VersionedResourceTablesSpec "joinWithViewerAccessAndOwner" should "narrow the access rows to the viewer, or to none when anonymous" in { val forViewer = - rendered( + renderSql( getDSLContext.renderInlined(tables.joinWithViewerAccessAndOwner(Integer.valueOf(42))) ) forViewer should include("dataset_user_access.uid = 42") val forAnonymous = - rendered(getDSLContext.renderInlined(tables.joinWithViewerAccessAndOwner(null))) + renderSql(getDSLContext.renderInlined(tables.joinWithViewerAccessAndOwner(null))) forAnonymous should not include "dataset_user_access.uid =" forAnonymous should include("false") } "ModelTables" should "name every column the shared query logic reads" in { - modelTables.table.getName shouldBe "model" - modelTables.idColumn.getName shouldBe "mid" - modelTables.isPublicColumn.getName shouldBe "is_public" - modelTables.nameColumn.getName shouldBe "name" - modelTables.descriptionColumn.getName shouldBe "description" - modelTables.creationTimeColumn.getName shouldBe "creation_time" - modelTables.ownerUidColumn.getName shouldBe "owner_uid" + assertColumns(modelTables, "model", "mid") } it should "share the hub's access table rather than naming it twice" in { @@ -209,11 +201,6 @@ class VersionedResourceTablesSpec } it should "join the model's own access and owner rows" in { - val sql = rendered(getDSLContext.render(modelTables.joinWithAccessAndOwner(None))) - - sql should include regex "model_user_access\\.mid = [\\w.]*model\\.mid" - sql should include regex "user\\.uid = [\\w.]*model\\.owner_uid" - sql.split("left outer join").length shouldBe 3 + assertAccessAndOwnerJoin(modelTables, "model", "mid") } - } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedSearchQuerySupport.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedSearchQuerySupport.scala new file mode 100644 index 00000000000..8c702e469c0 --- /dev/null +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/VersionedSearchQuerySupport.scala @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.texera.web.resource.dashboard + +import org.apache.texera.web.resource.dashboard.DashboardResource.SearchQueryParams +import org.jooq.DSLContext +import org.scalatest.matchers.should.Matchers + +import scala.jdk.CollectionConverters._ + +private[dashboard] object VersionedSearchQuerySupport extends Matchers { + def params(keywords: String*): SearchQueryParams = + SearchQueryParams(keywords = keywords.toList.asJava) + + def renderSearch( + context: DSLContext, + builder: SearchQueryBuilder, + uid: Integer, + params: SearchQueryParams, + includePublic: Boolean + ): String = renderSql(context.renderInlined(builder.constructQuery(uid, params, includePublic))) + + def renderSql(sql: String): String = sql.toLowerCase.replace("\"", "") + + // Compare against literals independent of the production projection. Hydration alone cannot + // detect an alias swap that translateRecord reverses when it recreates the original columns. + def assertProjection(sql: String, table: String, id: String): Unit = { + val fieldAliases = Seq( + "name" -> "resourcename", + "description" -> "resourcedescription", + "creation_time" -> "resourcecreationtime", + "owner_uid" -> "resourceownerid", + "repository_name" -> "repository_name", + id -> "versioned_resource_id", + "is_public" -> "is_versioned_resource_public", + "is_downloadable" -> "is_versioned_resource_downloadable", + "cover_image" -> "versioned_resource_cover_image" + ) + fieldAliases.foreach { + case (column, alias) => + withClue(s"$table.$column: ") { + sql should include(s"$table.$column as $alias") + } + } + sql should include(s"${table}_user_access.privilege as user_versioned_resource_access") + } +} diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilderSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilderSpec.scala index bc9d1587596..b313e5497db 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilderSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/WorkflowSearchQueryBuilderSpec.scala @@ -128,6 +128,13 @@ class WorkflowSearchQueryBuilderSpec extends AnyFlatSpec with Matchers { record } + private def pinnedMetadata(grantedAccess: java.lang.Boolean): Record = + translatedRecord( + grantedAccess = grantedAccess, + publishedName = "as-published", + publishedDescription = "described-as-published" + ) + private def workflowOf(record: Record, uid: Integer): DashboardWorkflow = WorkflowSearchQueryBuilder.toEntryImpl(uid, record).workflow.get @@ -136,11 +143,7 @@ class WorkflowSearchQueryBuilderSpec extends AnyFlatSpec with Matchers { "toEntryImpl" should "serve the published name and description to a viewer without granted access" in { // Publishing pins what the public sees, and a listing is where the public meets a workflow, so // the listing has to serve the pinned copy too rather than the author's live metadata. - val record = translatedRecord( - grantedAccess = java.lang.Boolean.FALSE, - publishedName = "as-published", - publishedDescription = "described-as-published" - ) + val record = pinnedMetadata(java.lang.Boolean.FALSE) val workflow = workflowOf(record, viewerUid).workflow @@ -162,11 +165,7 @@ class WorkflowSearchQueryBuilderSpec extends AnyFlatSpec with Matchers { } it should "leave the author's live name and description for a viewer who was granted access" in { - val record = translatedRecord( - grantedAccess = java.lang.Boolean.TRUE, - publishedName = "as-published", - publishedDescription = "described-as-published" - ) + val record = pinnedMetadata(java.lang.Boolean.TRUE) val workflow = workflowOf(record, ownerUid).workflow diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResourceSpec.scala index 43491e7e38e..ef4a8c9beb8 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResourceSpec.scala @@ -20,30 +20,16 @@ package org.apache.texera.web.resource.dashboard.admin.execution import org.apache.texera.auth.SessionUser -import org.apache.texera.dao.MockTexeraDB -import org.apache.texera.dao.jooq.generated.Tables.WORKFLOW_OF_USER +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum -import org.apache.texera.dao.jooq.generated.tables.daos.WorkflowUserAccessDao -import org.apache.texera.dao.jooq.generated.tables.pojos.{ - User, - WorkflowExecutions, - WorkflowUserAccess, - WorkflowVersion -} +import org.apache.texera.dao.jooq.generated.tables.pojos.{User, WorkflowExecutions, WorkflowVersion} import org.apache.texera.web.ExecutionDatabaseTestSupport -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers import java.util.UUID import java.util.concurrent.TimeUnit class AdminExecutionResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB + extends DatabaseFlatSpec(cleanupAfterEach = true) with ExecutionDatabaseTestSupport { // MockTexeraDB's embedded Postgres is a JVM singleton shared by all suites, which @@ -55,22 +41,10 @@ class AdminExecutionResourceSpec private var testUser: User = _ private var testVersion: WorkflowVersion = _ - private var workflowUserAccessDao: WorkflowUserAccessDao = _ private val resource = new AdminExecutionResource() - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - } - - override protected def afterAll(): Unit = { - shutdownDB() - } - - override protected def beforeEach(): Unit = { - workflowUserAccessDao = new WorkflowUserAccessDao(getDSLContext.configuration()) - cleanupTestData() - + override protected def onBeforeEach(): Unit = { testUser = insertUser(testUid, "test_user", "admin_exec_test@example.com") insertWorkflow( testWid, @@ -80,11 +54,7 @@ class AdminExecutionResourceSpec testVersion = insertWorkflowVersion(testWid) } - override protected def afterEach(): Unit = { - cleanupTestData() - } - - private def cleanupTestData(): Unit = + override protected def cleanup(): Unit = cleanupWorkflowRecords( Seq(testWid, secondWid), uids = Seq(testUid), @@ -110,14 +80,6 @@ class AdminExecutionResourceSpec durationMillis = Some(durationMillis) ) - private def grantAccess(uid: Int, privilege: PrivilegeEnum): Unit = { - val access = new WorkflowUserAccess - access.setUid(uid) - access.setWid(testWid) - access.setPrivilege(privilege) - workflowUserAccessDao.insert(access) - } - // Seeds a full second workflow (workflow + version + one execution) owned by // testUser, whose latest execution ends `endOffsetMillis` before "now". Used to // give the ordering test two workflows with distinct end times. @@ -190,7 +152,7 @@ class AdminExecutionResourceSpec "listWorkflows" should "return the seeded execution with the mapped status and access flag" in { seedExecution(status = 3.toByte, name = "completed-run") - grantAccess(testUser.getUid, PrivilegeEnum.READ) + insertWorkflowUserAccess(testUser.getUid, testWid, PrivilegeEnum.READ) val rows = list() @@ -214,11 +176,7 @@ class AdminExecutionResourceSpec it should "report access = true for the owner without an access row" in { seedExecution() - getDSLContext - .insertInto(WORKFLOW_OF_USER) - .set(WORKFLOW_OF_USER.UID, Integer.valueOf(testUid)) - .set(WORKFLOW_OF_USER.WID, Integer.valueOf(testWid)) - .execute() + insertWorkflowOfUser(testUid, testWid) list().head.access shouldBe true } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala index c4ddd923eda..efbc49113e4 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/admin/user/AdminUserResourceSpec.scala @@ -19,83 +19,38 @@ package org.apache.texera.web.resource.dashboard.admin.user -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.enums.{PrivilegeEnum, ProviderTypeEnum, UserRoleEnum} -import org.apache.texera.dao.jooq.generated.tables.daos.{ - DatasetDao, - UserDao, - WorkflowDao, - WorkflowExecutionsDao, - WorkflowOfUserDao, - WorkflowUserAccessDao, - WorkflowVersionDao -} import org.apache.texera.dao.jooq.generated.tables.pojos.{ Dataset, User, Workflow, - WorkflowExecutions, - WorkflowOfUser, - WorkflowUserAccess, - WorkflowVersion + WorkflowExecutions } -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.apache.texera.web.resource.dashboard.UserDashboardFixtureSupport -import java.sql.Timestamp import java.util.UUID import javax.ws.rs.{BadRequestException, WebApplicationException} import scala.jdk.CollectionConverters._ class AdminUserResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { + extends DatabaseFlatSpec(cleanupBeforeEach = false, cleanupAfterEach = true) + with UserDashboardFixtureSupport { private val primaryUid = 90000 + scala.util.Random.nextInt(5000) private val secondaryUid = primaryUid + 1 private val testWid = 90000 + scala.util.Random.nextInt(5000) - private var userDao: UserDao = _ - private var datasetDao: DatasetDao = _ - private var workflowDao: WorkflowDao = _ - private var workflowVersionDao: WorkflowVersionDao = _ - private var workflowExecutionsDao: WorkflowExecutionsDao = _ - private var workflowOfUserDao: WorkflowOfUserDao = _ - private var workflowUserAccessDao: WorkflowUserAccessDao = _ - private val resource = new AdminUserResource - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - userDao = new UserDao(getDSLContext.configuration()) - datasetDao = new DatasetDao(getDSLContext.configuration()) - workflowDao = new WorkflowDao(getDSLContext.configuration()) - workflowVersionDao = new WorkflowVersionDao(getDSLContext.configuration()) - workflowExecutionsDao = new WorkflowExecutionsDao(getDSLContext.configuration()) - workflowOfUserDao = new WorkflowOfUserDao(getDSLContext.configuration()) - workflowUserAccessDao = new WorkflowUserAccessDao(getDSLContext.configuration()) - } - - override protected def afterAll(): Unit = closeConnectionPool() - // Wipe everything this spec seeds, children before parents, after each test. - private def cleanup(): Unit = { + override protected def cleanup(): Unit = { getDSLContext .deleteFrom(WORKFLOW_EXECUTIONS) .where(WORKFLOW_EXECUTIONS.UID.in(primaryUid, secondaryUid)) .execute() - getDSLContext.deleteFrom(WORKFLOW_VERSION).where(WORKFLOW_VERSION.WID.eq(testWid)).execute() - getDSLContext - .deleteFrom(WORKFLOW_USER_ACCESS) - .where(WORKFLOW_USER_ACCESS.WID.eq(testWid)) - .execute() - getDSLContext.deleteFrom(WORKFLOW_OF_USER).where(WORKFLOW_OF_USER.WID.eq(testWid)).execute() - getDSLContext.deleteFrom(WORKFLOW).where(WORKFLOW.WID.eq(testWid)).execute() + cleanupWorkflowRecords(Seq(testWid), includeUserAccess = true) getDSLContext .deleteFrom(DATASET) .where(DATASET.OWNER_UID.in(primaryUid, secondaryUid)) @@ -112,7 +67,7 @@ class AdminUserResourceSpec user.setUid(uid) user.setName(name) user.setEmail( - s"admin_user_spec_${uid}_${UUID.randomUUID().toString.substring(0, 8)}@example.com" + s"admin_user_spec_${uid}_${uniqueSuffix}@example.com" ) user.setRole(role) user @@ -137,55 +92,22 @@ class AdminUserResourceSpec .set(AUTH_PROVIDER.PASSWORD, password) .execute() - private def seedWorkflow(): Workflow = { - val workflow = new Workflow - workflow.setWid(testWid) - workflow.setName("admin_user_spec_wf_" + UUID.randomUUID().toString.substring(0, 8)) - workflow.setContent("{}") - workflow.setDescription("desc") - workflow.setCreationTime(new Timestamp(System.currentTimeMillis())) - workflow.setLastModifiedTime(new Timestamp(System.currentTimeMillis())) - workflowDao.insert(workflow) - workflow - } + private def seedWorkflow(): Workflow = + insertWorkflow(testWid, "admin_user_spec_wf_" + uniqueSuffix, description = "desc") - private def seedDataset(uid: Int): Dataset = { - val dataset = new Dataset - dataset.setOwnerUid(uid) - dataset.setName("admin_user_spec_ds_" + UUID.randomUUID().toString.substring(0, 8)) - dataset.setRepositoryName("repo-" + UUID.randomUUID().toString.substring(0, 8)) - dataset.setIsPublic(false) - dataset.setIsDownloadable(true) - dataset.setDescription("") - dataset.setCreationTime(new Timestamp(System.currentTimeMillis())) - datasetDao.insert(dataset) - dataset - } + private def seedDataset(uid: Int): Dataset = seedDataset(uid, "admin_user_spec_ds_") private def seedExecution(uid: Int): WorkflowExecutions = { seedWorkflow() - val version = new WorkflowVersion - version.setWid(testWid) - version.setContent("{}") - version.setCreationTime(new Timestamp(System.currentTimeMillis())) - workflowVersionDao.insert(version) - - val execution = new WorkflowExecutions - execution.setVid(version.getVid) - execution.setUid(uid) - execution.setStatus(0.toByte) - execution.setResult("") - execution.setLogLocation("") - execution.setStartingTime(new Timestamp(System.currentTimeMillis())) - execution.setBookmarked(false) - execution.setName("admin_user_spec_exec") - execution.setEnvironmentVersion("test-env-1.0") - workflowExecutionsDao.insert(execution) - execution + insertWorkflowExecution( + insertWorkflowVersion(testWid).getVid, + uid, + name = "admin_user_spec_exec", + envVersion = "test-env-1.0", + logLocation = Some("") + ) } - override protected def afterEach(): Unit = cleanup() - // ─── list ─────────────────────────────────────────────────────────────── "list" should "return the seeded users with their name, email, and role" in { @@ -410,10 +332,7 @@ class AdminUserResourceSpec it should "return the workflows the user created" in { userDao.insert(makeUser(primaryUid, "creator")) val workflow = seedWorkflow() - val ownership = new WorkflowOfUser - ownership.setUid(primaryUid) - ownership.setWid(testWid) - workflowOfUserDao.insert(ownership) + insertWorkflowOfUser(primaryUid, testWid) val created = resource.getCreatedWorkflow(primaryUid) created.map(_.workflowId) shouldBe List(Integer.valueOf(testWid)) @@ -430,11 +349,7 @@ class AdminUserResourceSpec it should "return the workflow ids the user can access" in { userDao.insert(makeUser(primaryUid, "viewer")) seedWorkflow() - val access = new WorkflowUserAccess - access.setUid(primaryUid) - access.setWid(testWid) - access.setPrivilege(PrivilegeEnum.READ) - workflowUserAccessDao.insert(access) + insertWorkflowUserAccess(primaryUid, testWid, PrivilegeEnum.READ) resource.getAccessedWorkflow(primaryUid).asScala should contain(Integer.valueOf(testWid)) } @@ -442,11 +357,7 @@ class AdminUserResourceSpec it should "include a workflow the user owns without an access row" in { userDao.insert(makeUser(primaryUid, "owner")) seedWorkflow() - getDSLContext - .insertInto(WORKFLOW_OF_USER) - .set(WORKFLOW_OF_USER.UID, Integer.valueOf(primaryUid)) - .set(WORKFLOW_OF_USER.WID, Integer.valueOf(testWid)) - .execute() + insertWorkflowOfUser(primaryUid, testWid) resource.getAccessedWorkflow(primaryUid).asScala.toList shouldBe List(Integer.valueOf(testWid)) } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/file/DatasetResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/file/DatasetResourceSpec.scala index 5bcbbe2b27b..edc28a64bc0 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/file/DatasetResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/file/DatasetResourceSpec.scala @@ -19,50 +19,37 @@ package org.apache.texera.web.resource.dashboard.file -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum import org.apache.texera.dao.jooq.generated.tables.pojos.User import org.apache.texera.web.resource.dashboard.DashboardResource.SearchQueryParams import org.apache.texera.web.resource.dashboard.DatasetSearchQueryBuilder -import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.dao.jooq.generated.tables.daos.{UserDao, DatasetDao, DatasetUserAccessDao} import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum import org.apache.texera.dao.jooq.generated.tables.pojos.{Dataset, DatasetUserAccess} -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import java.time.OffsetDateTime import org.apache.texera.web.resource.dashboard.SearchQueryBuilder.DATASET_RESOURCE_TYPE class DatasetResourceSpec - extends AnyFlatSpec - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { + extends DatabaseFlatSpec(cleanupBeforeEach = false, cleanupAfterEach = true) { // An example creation time to test Account Creation Time attribute private val exampleCreationTime: OffsetDateTime = OffsetDateTime.parse("2025-01-01T00:00:00Z") - private val ownerUser: User = { + private def seededUser(uid: Int, name: String, role: UserRoleEnum, comment: String): User = { val user = new User - user.setUid(Integer.valueOf(1)) - user.setName("owner_user") - user.setRole(UserRoleEnum.ADMIN) - user.setEmail("owner_user@mail.com") - user.setComment("test_comment") + user.setUid(uid) + user.setName(name) + user.setRole(role) + user.setEmail(s"$name@mail.com") + user.setComment(comment) user.setAccountCreationTime(exampleCreationTime) user } - private val testUser: User = { - val user = new User - user.setUid(Integer.valueOf(2)) - user.setName("test_user") - user.setEmail("test_user@mail.com") - user.setRole(UserRoleEnum.REGULAR) - user.setComment("test_comment2") - user.setAccountCreationTime(exampleCreationTime) - user - } + private val ownerUser = seededUser(1, "owner_user", UserRoleEnum.ADMIN, "test_comment") + private val testUser = seededUser(2, "test_user", UserRoleEnum.REGULAR, "test_comment2") private val testDatasetRecord: Dataset = { val dataset = new Dataset() @@ -73,36 +60,16 @@ class DatasetResourceSpec dataset } - // get context lazily - private lazy val datasetDao: DatasetDao = { - new DatasetDao(getDSLContext.configuration()) - } - - private lazy val datasetUserAccessDao: DatasetUserAccessDao = { - new DatasetUserAccessDao(getDSLContext.configuration()) - } + private lazy val userDao = new UserDao(getDSLContext.configuration()) + private lazy val datasetDao = new DatasetDao(getDSLContext.configuration()) + private lazy val datasetUserAccessDao = new DatasetUserAccessDao(getDSLContext.configuration()) - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - // `FulltextSearchQueryUtils.usePgroonga` is deliberately left at its production default here: - // no test in this suite reaches the read, because both `constructQuery` calls below pass no - // keywords and `getFullTextSearchFilter` returns before that read on an empty keyword list. - // A keyword test added here would need the `to_tsvector` arm instead — `MockTexeraDB` strips - // the full-text index block out of the DDL, so the embedded Postgres has no pgroonga extension - // — and would have to set the flag and put it back: amber has no `Test / fork`, so a value - // left behind here follows every suite scheduled after this one in the same JVM. - - // add test user directly - val userDao = new UserDao(getDSLContext.configuration()) + override protected def onBeforeAll(): Unit = { userDao.insert(ownerUser) userDao.insert(testUser) } - override protected def beforeEach(): Unit = { - // Clean up environment before each test case - } - - override protected def afterEach(): Unit = { + override protected def cleanup(): Unit = { // 1. Delete access rows before the dataset getDSLContext .deleteFrom(org.apache.texera.dao.jooq.generated.tables.DatasetUserAccess.DATASET_USER_ACCESS) @@ -114,12 +81,7 @@ class DatasetResourceSpec } } - override protected def afterAll(): Unit = { - shutdownDB() - } - "User.accountCreationTime" should "be persisted and retrievable via UserDao" in { - val userDao = new UserDao(getDSLContext.configuration()) val u1 = userDao.fetchOneByUid(Integer.valueOf(1)) val u2 = userDao.fetchOneByUid(Integer.valueOf(2)) @@ -131,7 +93,6 @@ class DatasetResourceSpec } it should "remain unchanged when updating unrelated fields" in { - val userDao = new UserDao(getDSLContext.configuration()) val u1 = userDao.fetchOneByUid(Integer.valueOf(1)) val originalTime = u1.getAccountCreationTime @@ -142,67 +103,34 @@ class DatasetResourceSpec assert(test_u1.getAccountCreationTime.isEqual(originalTime)) } - "DatasetResource /owner view" should "get deduplicated datasets created by owner and shared publicly" in { - // Only metadatas of dataset and the user is maintained - no dataset is actually created in LakeFS - // Create dataset - val datasetDao = new DatasetDao(getDSLContext.configuration()) + private def grant(uid: Integer, privilege: PrivilegeEnum): Unit = + datasetUserAccessDao.insert(new DatasetUserAccess(testDatasetRecord.getDid, uid, privilege)) + + // These cases query metadata directly. A LakeFS repository is needed only for hydration. + private def seedPublicDataset(): Unit = { testDatasetRecord.setOwnerUid(ownerUser.getUid) datasetDao.insert(testDatasetRecord) + grant(ownerUser.getUid, PrivilegeEnum.WRITE) + } - // Give write access to the owner user - datasetUserAccessDao.insert( - new DatasetUserAccess( - testDatasetRecord.getDid, - ownerUser.getUid, - PrivilegeEnum.WRITE - ) + private def assertSingleDataset(uid: Integer): Unit = { + val query = DatasetSearchQueryBuilder.constructQuery( + uid, + SearchQueryParams(resourceType = DATASET_RESOURCE_TYPE), + includePublic = true ) - - // Build the query - bypasses DashboarResource - val query = - DatasetSearchQueryBuilder.constructQuery( - ownerUser.getUid, - SearchQueryParams(resourceType = DATASET_RESOURCE_TYPE), - includePublic = true - ) - // Assert the length of returned dataset val datasetEntryList = getDSLContext.fetch(query) assert(datasetEntryList.size() == 1) } - "/search API" should "deduplicate datasets shared both publicly and explicitly with NON-WRITE permissions" in { - // Only metadatas of dataset and the user is maintained - no dataset is actually created in LakeFS - // Create dataset - val datasetDao = new DatasetDao(getDSLContext.configuration()) - testDatasetRecord.setOwnerUid(ownerUser.getUid) - datasetDao.insert(testDatasetRecord) - - // Give write access to the owner user - datasetUserAccessDao.insert( - new DatasetUserAccess( - ownerUser.getUid, - testDatasetRecord.getDid, - PrivilegeEnum.WRITE - ) - ) - - datasetUserAccessDao.insert( - new DatasetUserAccess( - testDatasetRecord.getDid, - testUser.getUid, - PrivilegeEnum.READ - ) - ) + "DatasetResource /owner view" should "get deduplicated datasets created by owner and shared publicly" in { + seedPublicDataset() + assertSingleDataset(ownerUser.getUid) + } - // Build the query - val query = - DatasetSearchQueryBuilder.constructQuery( - testUser.getUid, - SearchQueryParams(resourceType = DATASET_RESOURCE_TYPE), - includePublic = true - ) - // Assert the length of returned dataset - val datasetEntryList = getDSLContext.fetch(query) - assert(datasetEntryList.size() == 1) + "/search API" should "deduplicate datasets shared both publicly and explicitly with NON-WRITE permissions" in { + seedPublicDataset() + grant(testUser.getUid, PrivilegeEnum.READ) + assertSingleDataset(testUser.getUid) } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTablesSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTablesSpec.scala index 75b913e4a19..d3add02fcd0 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTablesSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTablesSpec.scala @@ -19,6 +19,7 @@ package org.apache.texera.web.resource.dashboard.hub +import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.web.resource.dashboard.VersionedResourceTables import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -30,14 +31,20 @@ class EntityTablesSpec extends AnyFlatSpec with Matchers { // -- BaseEntityTable -------------------------------------------------------- "EntityTables.BaseEntityTable.apply" should "dispatch Workflow → WorkflowTable" in { - EntityTables.BaseEntityTable(EntityType.Workflow) shouldBe - EntityTables.BaseEntityTable.WorkflowTable + val descriptor = EntityTables.BaseEntityTable(EntityType.Workflow) + descriptor shouldBe EntityTables.BaseEntityTable.WorkflowTable + descriptor.table shouldBe WORKFLOW + descriptor.isPublicColumn shouldBe WORKFLOW.IS_PUBLIC + descriptor.idColumn shouldBe WORKFLOW.WID } it should "dispatch Dataset → the dataset's search descriptor" in { // Datasets have no BaseEntityTable object: VersionedResourceTables implements it. - EntityTables.BaseEntityTable(EntityType.Dataset) shouldBe - VersionedResourceTables.DatasetTables + val descriptor = EntityTables.BaseEntityTable(EntityType.Dataset) + descriptor shouldBe VersionedResourceTables.DatasetTables + descriptor.table shouldBe DATASET + descriptor.isPublicColumn shouldBe DATASET.IS_PUBLIC + descriptor.idColumn shouldBe DATASET.DID } it should "dispatch Model → the model's search descriptor" in { @@ -66,13 +73,19 @@ class EntityTablesSpec extends AnyFlatSpec with Matchers { // -- LikeTable -------------------------------------------------------------- "EntityTables.LikeTable.apply" should "dispatch Workflow → WorkflowLikeTable" in { - EntityTables.LikeTable(EntityType.Workflow) shouldBe - EntityTables.LikeTable.WorkflowLikeTable + val descriptor = EntityTables.LikeTable(EntityType.Workflow) + descriptor shouldBe EntityTables.LikeTable.WorkflowLikeTable + descriptor.table shouldBe WORKFLOW_USER_LIKES + descriptor.uidColumn shouldBe WORKFLOW_USER_LIKES.UID + descriptor.idColumn shouldBe WORKFLOW_USER_LIKES.WID } it should "dispatch Dataset → DatasetLikeTable" in { - EntityTables.LikeTable(EntityType.Dataset) shouldBe - EntityTables.LikeTable.DatasetLikeTable + val descriptor = EntityTables.LikeTable(EntityType.Dataset) + descriptor shouldBe EntityTables.LikeTable.DatasetLikeTable + descriptor.table shouldBe DATASET_USER_LIKES + descriptor.uidColumn shouldBe DATASET_USER_LIKES.UID + descriptor.idColumn shouldBe DATASET_USER_LIKES.DID } it should "dispatch Model → ModelLikeTable" in { @@ -81,42 +94,36 @@ class EntityTablesSpec extends AnyFlatSpec with Matchers { } "LikeTable variants" should "expose uid and the per-entity id column" in { - val w = EntityTables.LikeTable.WorkflowLikeTable - w.uidColumn.getName shouldBe "uid" - w.idColumn.getName shouldBe "wid" - - val d = EntityTables.LikeTable.DatasetLikeTable - d.uidColumn.getName shouldBe "uid" - d.idColumn.getName shouldBe "did" - - val m = EntityTables.LikeTable.ModelLikeTable - m.uidColumn.getName shouldBe "uid" - m.idColumn.getName shouldBe "mid" + import EntityTables.LikeTable._ + Seq(WorkflowLikeTable -> "wid", DatasetLikeTable -> "did", ModelLikeTable -> "mid").foreach { + case (table, id) => + table.uidColumn.getName shouldBe "uid" + table.idColumn.getName shouldBe id + } } // -- CloneTable ------------------------------------------------------------- "EntityTables.CloneTable.apply" should "dispatch Workflow → WorkflowCloneTable" in { - EntityTables.CloneTable(EntityType.Workflow) shouldBe - EntityTables.CloneTable.WorkflowCloneTable + val descriptor = EntityTables.CloneTable(EntityType.Workflow) + descriptor shouldBe EntityTables.CloneTable.WorkflowCloneTable + descriptor.table shouldBe WORKFLOW_USER_CLONES + descriptor.uidColumn shouldBe WORKFLOW_USER_CLONES.UID + descriptor.idColumn shouldBe WORKFLOW_USER_CLONES.WID } - it should "throw IllegalArgumentException for Model, which is cloneless like Dataset" in { - val ex = intercept[IllegalArgumentException] { - EntityTables.CloneTable(EntityType.Model) - } + private def assertCloneless(entityType: EntityType): Unit = { + val ex = intercept[IllegalArgumentException](EntityTables.CloneTable(entityType)) ex.getMessage should include("Unsupported entity type") ex.getMessage should include("clone") } + it should "throw IllegalArgumentException for Model, which is cloneless like Dataset" in { + assertCloneless(EntityType.Model) + } + it should "throw IllegalArgumentException for Dataset because there is no DatasetClone table" in { - // The asymmetry is intentional today: dataset clones aren't a modelled - // entity. CloneTable.apply stays for recordCloneAction. - val ex = intercept[IllegalArgumentException] { - EntityTables.CloneTable(EntityType.Dataset) - } - ex.getMessage should include("Unsupported entity type") - ex.getMessage should include("clone") + assertCloneless(EntityType.Dataset) } // -- the registry ----------------------------------------------------------- @@ -155,32 +162,32 @@ class EntityTablesSpec extends AnyFlatSpec with Matchers { // -- AccessTable ------------------------------------------------------------ "EntityTables.AccessTable" should "expose id, uid and privilege per entity" in { - val w = EntityTables.AccessTable(EntityType.Workflow) - w.idColumn.getName shouldBe "wid" - w.uidColumn.getName shouldBe "uid" - w.privilegeColumn.getName shouldBe "privilege" - - val d = EntityTables.AccessTable(EntityType.Dataset) - d.idColumn.getName shouldBe "did" - d.uidColumn.getName shouldBe "uid" - d.privilegeColumn.getName shouldBe "privilege" - - val m = EntityTables.AccessTable(EntityType.Model) - m.idColumn.getName shouldBe "mid" - m.uidColumn.getName shouldBe "uid" - m.privilegeColumn.getName shouldBe "privilege" + Seq(EntityType.Workflow -> "wid", EntityType.Dataset -> "did", EntityType.Model -> "mid") + .foreach { + case (entityType, id) => + val table = EntityTables.AccessTable(entityType) + table.idColumn.getName shouldBe id + table.uidColumn.getName shouldBe "uid" + table.privilegeColumn.getName shouldBe "privilege" + } } // -- ViewCountTable --------------------------------------------------------- "EntityTables.ViewCountTable.apply" should "dispatch Workflow → WorkflowViewCountTable" in { - EntityTables.ViewCountTable(EntityType.Workflow) shouldBe - EntityTables.ViewCountTable.WorkflowViewCountTable + val descriptor = EntityTables.ViewCountTable(EntityType.Workflow) + descriptor shouldBe EntityTables.ViewCountTable.WorkflowViewCountTable + descriptor.table shouldBe WORKFLOW_VIEW_COUNT + descriptor.idColumn shouldBe WORKFLOW_VIEW_COUNT.WID + descriptor.viewCountColumn shouldBe WORKFLOW_VIEW_COUNT.VIEW_COUNT } it should "dispatch Dataset → DatasetViewCountTable" in { - EntityTables.ViewCountTable(EntityType.Dataset) shouldBe - EntityTables.ViewCountTable.DatasetViewCountTable + val descriptor = EntityTables.ViewCountTable(EntityType.Dataset) + descriptor shouldBe EntityTables.ViewCountTable.DatasetViewCountTable + descriptor.table shouldBe DATASET_VIEW_COUNT + descriptor.idColumn shouldBe DATASET_VIEW_COUNT.DID + descriptor.viewCountColumn shouldBe DATASET_VIEW_COUNT.VIEW_COUNT } it should "dispatch Model → ModelViewCountTable" in { @@ -189,16 +196,15 @@ class EntityTablesSpec extends AnyFlatSpec with Matchers { } "ViewCountTable variants" should "expose id and view_count columns" in { - val w = EntityTables.ViewCountTable.WorkflowViewCountTable - w.idColumn.getName shouldBe "wid" - w.viewCountColumn.getName shouldBe "view_count" - - val d = EntityTables.ViewCountTable.DatasetViewCountTable - d.idColumn.getName shouldBe "did" - d.viewCountColumn.getName shouldBe "view_count" - - val m = EntityTables.ViewCountTable.ModelViewCountTable - m.idColumn.getName shouldBe "mid" - m.viewCountColumn.getName shouldBe "view_count" + import EntityTables.ViewCountTable._ + Seq( + WorkflowViewCountTable -> "wid", + DatasetViewCountTable -> "did", + ModelViewCountTable -> "mid" + ).foreach { + case (table, id) => + table.idColumn.getName shouldBe id + table.viewCountColumn.getName shouldBe "view_count" + } } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTypeSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTypeSpec.scala index 5c526724fab..08bde0227d7 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTypeSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/EntityTypeSpec.scala @@ -20,6 +20,7 @@ package org.apache.texera.web.resource.dashboard.hub import com.fasterxml.jackson.databind.ObjectMapper +import org.apache.texera.amber.util.JSONUtils.objectMapper import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -47,6 +48,9 @@ class EntityTypeSpec extends AnyFlatSpec with Matchers { EntityType.fromString("Workflow") shouldBe EntityType.Workflow EntityType.fromString("DATASET") shouldBe EntityType.Dataset EntityType.fromString("Model") shouldBe EntityType.Model + EntityType.fromString("WORKFLOW") shouldBe EntityType.Workflow + EntityType.fromString("Dataset") shouldBe EntityType.Dataset + EntityType.fromString("MODEL") shouldBe EntityType.Model } it should "throw IllegalArgumentException for an unknown value" in { @@ -56,6 +60,13 @@ class EntityTypeSpec extends AnyFlatSpec with Matchers { ex.getMessage should include("project") } + it should "throw IllegalArgumentException for an empty string, naming the empty input" in { + val ex = intercept[IllegalArgumentException] { + EntityType.fromString("") + } + ex.getMessage should include("''") + } + // The @JsonValue / @JsonCreator pair drives Jackson serialisation. Cover // the round-trip so a future @JsonValue rename can't silently change the // wire format. @@ -63,5 +74,10 @@ class EntityTypeSpec extends AnyFlatSpec with Matchers { val mapper = new ObjectMapper() mapper.writeValueAsString(EntityType.Workflow: EntityType) shouldBe "\"workflow\"" mapper.readValue("\"dataset\"", classOf[EntityType]) shouldBe EntityType.Dataset + + objectMapper.writeValueAsString(EntityType.Workflow: EntityType) shouldBe "\"workflow\"" + objectMapper.writeValueAsString(EntityType.Dataset: EntityType) shouldBe "\"dataset\"" + objectMapper.readValue("\"workflow\"", classOf[EntityType]) shouldBe EntityType.Workflow + objectMapper.readValue("\"dataset\"", classOf[EntityType]) shouldBe EntityType.Dataset } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubEntityModelSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubEntityModelSpec.scala index e3826c80cb5..ba69eedd6ea 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubEntityModelSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubEntityModelSpec.scala @@ -20,21 +20,23 @@ package org.apache.texera.web.resource.dashboard.hub import org.apache.texera.amber.util.JSONUtils.objectMapper -import org.apache.texera.dao.jooq.generated.Tables._ -import org.apache.texera.web.resource.dashboard.VersionedResourceTables import org.scalatest.flatspec.AnyFlatSpec class HubEntityModelSpec extends AnyFlatSpec { + private val actions: Seq[(ActionType, String, String)] = Seq( + (ActionType.View, "view", "VIEW"), + (ActionType.Like, "like", "Like"), + (ActionType.Clone, "clone", "CLONE"), + (ActionType.Unlike, "unlike", "uNlIkE") + ) + // --------------------------------------------------------------------------- // ActionType // --------------------------------------------------------------------------- "ActionType subtypes" should "expose their lowercase string value" in { - assert(ActionType.View.value == "view") - assert(ActionType.Like.value == "like") - assert(ActionType.Clone.value == "clone") - assert(ActionType.Unlike.value == "unlike") + actions.foreach { case (kind, wire, _) => assert(kind.value == wire) } } it should "have toString equal to value (override pin)" in { @@ -43,26 +45,19 @@ class HubEntityModelSpec extends AnyFlatSpec { // name (e.g. "View" instead of "view") breaks here. Use the class // simpleName in the failure message — not toString, which is what // we are pinning — so a regression produces a readable diagnostic. - val all: List[ActionType] = - List(ActionType.View, ActionType.Like, ActionType.Clone, ActionType.Unlike) - all.foreach { a => - val name = a.getClass.getSimpleName - assert(a.toString == a.value, s"$name.toString = '${a.toString}' but value = '${a.value}'") + actions.foreach { + case (a, _, _) => + val name = a.getClass.getSimpleName + assert(a.toString == a.value, s"$name.toString = '${a.toString}' but value = '${a.value}'") } } "ActionType.fromString" should "match each subtype exactly" in { - assert(ActionType.fromString("view") == ActionType.View) - assert(ActionType.fromString("like") == ActionType.Like) - assert(ActionType.fromString("clone") == ActionType.Clone) - assert(ActionType.fromString("unlike") == ActionType.Unlike) + actions.foreach { case (kind, wire, _) => assert(ActionType.fromString(wire) == kind) } } it should "match case-insensitively" in { - assert(ActionType.fromString("VIEW") == ActionType.View) - assert(ActionType.fromString("Like") == ActionType.Like) - assert(ActionType.fromString("CLONE") == ActionType.Clone) - assert(ActionType.fromString("uNlIkE") == ActionType.Unlike) + actions.foreach { case (kind, _, mixed) => assert(ActionType.fromString(mixed) == kind) } } it should "throw IllegalArgumentException for an unknown action, naming the input" in { @@ -84,157 +79,23 @@ class HubEntityModelSpec extends AnyFlatSpec { "ActionType Jackson round-trip" should "serialize each subtype as its lowercase string value" in { // `@JsonValue` on `value` instructs Jackson to emit the field's value // string instead of a wrapping object form. - assert(objectMapper.writeValueAsString(ActionType.View: ActionType) == "\"view\"") - assert(objectMapper.writeValueAsString(ActionType.Like: ActionType) == "\"like\"") - assert(objectMapper.writeValueAsString(ActionType.Clone: ActionType) == "\"clone\"") - assert(objectMapper.writeValueAsString(ActionType.Unlike: ActionType) == "\"unlike\"") + actions.foreach { + case (action, wire, _) => + assert(objectMapper.writeValueAsString(action) == s""""$wire"""") + } } it should "deserialize from the lowercase string back to the canonical subtype" in { // `@JsonCreator` on `fromString` lets Jackson reconstruct the subtype // from a raw string field. - assert(objectMapper.readValue("\"view\"", classOf[ActionType]) == ActionType.View) - assert(objectMapper.readValue("\"like\"", classOf[ActionType]) == ActionType.Like) - assert(objectMapper.readValue("\"clone\"", classOf[ActionType]) == ActionType.Clone) - assert(objectMapper.readValue("\"unlike\"", classOf[ActionType]) == ActionType.Unlike) + actions.foreach { + case (action, wire, _) => + assert(objectMapper.readValue(s""""$wire"""", classOf[ActionType]) == action) + } } it should "honor the case-insensitive deserialization via @JsonCreator" in { assert(objectMapper.readValue("\"VIEW\"", classOf[ActionType]) == ActionType.View) } - // --------------------------------------------------------------------------- - // EntityType - // --------------------------------------------------------------------------- - - "EntityType subtypes" should "expose their lowercase string value" in { - assert(EntityType.Workflow.value == "workflow") - assert(EntityType.Dataset.value == "dataset") - assert(EntityType.Model.value == "model") - } - - it should "have toString equal to value (override pin)" in { - // Same stable-name pattern as ActionType — don't use the SUT - // (toString) in the failure message. - val all: List[EntityType] = List(EntityType.Workflow, EntityType.Dataset, EntityType.Model) - all.foreach { e => - val name = e.getClass.getSimpleName - assert(e.toString == e.value, s"$name.toString = '${e.toString}' but value = '${e.value}'") - } - } - - "EntityType.fromString" should "match each subtype exactly" in { - assert(EntityType.fromString("workflow") == EntityType.Workflow) - assert(EntityType.fromString("dataset") == EntityType.Dataset) - assert(EntityType.fromString("model") == EntityType.Model) - } - - it should "match case-insensitively" in { - assert(EntityType.fromString("WORKFLOW") == EntityType.Workflow) - assert(EntityType.fromString("Dataset") == EntityType.Dataset) - assert(EntityType.fromString("MODEL") == EntityType.Model) - } - - it should "throw IllegalArgumentException for an unknown kind, naming the input" in { - val ex = intercept[IllegalArgumentException] { - EntityType.fromString("project") - } - assert(ex.getMessage.contains("project")) - } - - it should "throw IllegalArgumentException for an empty string, naming the empty input" in { - val ex = intercept[IllegalArgumentException] { - EntityType.fromString("") - } - assert(ex.getMessage.contains("''"), s"unexpected message: ${ex.getMessage}") - } - - "EntityType Jackson round-trip" should "serialize / deserialize each subtype as its lowercase string value" in { - assert(objectMapper.writeValueAsString(EntityType.Workflow: EntityType) == "\"workflow\"") - assert(objectMapper.writeValueAsString(EntityType.Dataset: EntityType) == "\"dataset\"") - assert(objectMapper.readValue("\"workflow\"", classOf[EntityType]) == EntityType.Workflow) - assert(objectMapper.readValue("\"dataset\"", classOf[EntityType]) == EntityType.Dataset) - } - - // --------------------------------------------------------------------------- - // EntityTables.BaseEntityTable - // --------------------------------------------------------------------------- - - "EntityTables.BaseEntityTable.apply" should "dispatch Workflow → WorkflowTable" in { - val t = EntityTables.BaseEntityTable(EntityType.Workflow) - assert(t == EntityTables.BaseEntityTable.WorkflowTable) - assert(t.table == WORKFLOW) - assert(t.isPublicColumn == WORKFLOW.IS_PUBLIC) - assert(t.idColumn == WORKFLOW.WID) - } - - it should "dispatch Dataset → the dataset's search descriptor" in { - // Datasets have no BaseEntityTable object: VersionedResourceTables implements it. - val t = EntityTables.BaseEntityTable(EntityType.Dataset) - assert(t == VersionedResourceTables.DatasetTables) - assert(t.table == DATASET) - assert(t.isPublicColumn == DATASET.IS_PUBLIC) - assert(t.idColumn == DATASET.DID) - } - - // --------------------------------------------------------------------------- - // EntityTables.LikeTable - // --------------------------------------------------------------------------- - - "EntityTables.LikeTable.apply" should "dispatch Workflow → WorkflowLikeTable" in { - val t = EntityTables.LikeTable(EntityType.Workflow) - assert(t == EntityTables.LikeTable.WorkflowLikeTable) - assert(t.table == WORKFLOW_USER_LIKES) - assert(t.uidColumn == WORKFLOW_USER_LIKES.UID) - assert(t.idColumn == WORKFLOW_USER_LIKES.WID) - } - - it should "dispatch Dataset → DatasetLikeTable" in { - val t = EntityTables.LikeTable(EntityType.Dataset) - assert(t == EntityTables.LikeTable.DatasetLikeTable) - assert(t.table == DATASET_USER_LIKES) - assert(t.uidColumn == DATASET_USER_LIKES.UID) - assert(t.idColumn == DATASET_USER_LIKES.DID) - } - - // --------------------------------------------------------------------------- - // EntityTables.CloneTable (workflow-only today) - // --------------------------------------------------------------------------- - - "EntityTables.CloneTable.apply" should "dispatch Workflow → WorkflowCloneTable" in { - val t = EntityTables.CloneTable(EntityType.Workflow) - assert(t == EntityTables.CloneTable.WorkflowCloneTable) - assert(t.table == WORKFLOW_USER_CLONES) - assert(t.uidColumn == WORKFLOW_USER_CLONES.UID) - assert(t.idColumn == WORKFLOW_USER_CLONES.WID) - } - - it should "throw IllegalArgumentException for Dataset (clone is workflow-only)" in { - // Pin: clone is implemented for workflow only today. A future addition - // of DatasetCloneTable should remove this assertion deliberately. - val ex = intercept[IllegalArgumentException] { - EntityTables.CloneTable(EntityType.Dataset) - } - assert(ex.getMessage.contains("clone")) - } - - // --------------------------------------------------------------------------- - // EntityTables.ViewCountTable - // --------------------------------------------------------------------------- - - "EntityTables.ViewCountTable.apply" should "dispatch Workflow → WorkflowViewCountTable" in { - val t = EntityTables.ViewCountTable(EntityType.Workflow) - assert(t == EntityTables.ViewCountTable.WorkflowViewCountTable) - assert(t.table == WORKFLOW_VIEW_COUNT) - assert(t.idColumn == WORKFLOW_VIEW_COUNT.WID) - assert(t.viewCountColumn == WORKFLOW_VIEW_COUNT.VIEW_COUNT) - } - - it should "dispatch Dataset → DatasetViewCountTable" in { - val t = EntityTables.ViewCountTable(EntityType.Dataset) - assert(t == EntityTables.ViewCountTable.DatasetViewCountTable) - assert(t.table == DATASET_VIEW_COUNT) - assert(t.idColumn == DATASET_VIEW_COUNT.DID) - assert(t.viewCountColumn == DATASET_VIEW_COUNT.VIEW_COUNT) - } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala index c0410db4d42..19fa57f8303 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/hub/HubResourceSpec.scala @@ -20,42 +20,27 @@ package org.apache.texera.web.resource.dashboard.hub import org.apache.texera.auth.SessionUser -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum -import org.apache.texera.dao.jooq.generated.tables.daos.{ - UserDao, - WorkflowDao, - WorkflowOfUserDao, - WorkflowUserAccessDao +import org.apache.texera.dao.jooq.generated.tables.daos.UserDao +import org.apache.texera.dao.jooq.generated.tables.pojos.User +import org.apache.texera.web.resource.dashboard.{ + DashboardWorkflowFixtureSupport, + VersionedResourceTables } -import org.apache.texera.dao.jooq.generated.tables.pojos.{ - User, - Workflow, - WorkflowOfUser, - WorkflowUserAccess -} -import org.apache.texera.web.resource.dashboard.VersionedResourceTables import org.apache.texera.web.resource.dashboard.hub.HubResource._ +import org.jooq.{Field, Record, Table} import org.scalamock.scalatest.MockFactory -import org.scalatest.BeforeAndAfterAll -import org.scalatest.BeforeAndAfterEach -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import java.sql.Timestamp -import java.util.UUID import javax.servlet.http.HttpServletRequest import javax.ws.rs.BadRequestException import scala.jdk.CollectionConverters._ class HubResourceSpec - extends AnyFlatSpec - with Matchers + extends DatabaseFlatSpec() with MockFactory - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { + with DashboardWorkflowFixtureSupport { // MockTexeraDB gives this suite its own UUID-named database, so fixed ids are // safe and keep failures reproducible. @@ -64,15 +49,12 @@ class HubResourceSpec private val wid = 7001 private val Wf: EntityType = EntityType.Workflow - private var userDao: UserDao = _ - private var workflowDao: WorkflowDao = _ - private var workflowOfUserDao: WorkflowOfUserDao = _ - private var workflowUserAccessDao: WorkflowUserAccessDao = _ - // A request whose remote address is a valid IPv4 so recordUserAction stores it. - private def req: HttpServletRequest = { + private def req: HttpServletRequest = requestFrom("127.0.0.1") + + private def requestFrom(remoteAddress: String): HttpServletRequest = { val r = stub[HttpServletRequest] - (r.getRemoteAddr _).when().returns("127.0.0.1") + (r.getRemoteAddr _).when().returns(remoteAddress) r } @@ -82,41 +64,37 @@ class HubResourceSpec new SessionUser(u) } - private def makeUser(uid: Int, name: String): User = { - val u = new User - u.setUid(Integer.valueOf(uid)) - u.setName(name) - u.setEmail(s"$name@test.com") - u - } - private def ids(values: Int*): java.util.List[Integer] = values.map(Integer.valueOf).asJava private def types(values: EntityType*): java.util.List[EntityType] = values.toList.asJava private def actions(values: ActionType*): java.util.List[ActionType] = values.toList.asJava + private def recordLike(uid: Int, entity: UserRequest, isLike: Boolean): Boolean = + recordLikeAction(req, Integer.valueOf(uid), entity, isLike) + + private def view(id: Integer, uid: Integer, kind: EntityType = Wf): Int = + hub.postView(req, ViewRequest(id, uid, kind)) + + private def countsFor( + kind: EntityType, + id: Int, + requested: java.util.List[ActionType] = null + ): Map[ActionType, Int] = + hub.getCounts(types(kind), ids(id), requested).asScala.head.counts.asScala.toMap + private def likeRows: Int = - getDSLContext - .selectCount() - .from(WORKFLOW_USER_LIKES) - .where(WORKFLOW_USER_LIKES.WID.eq(wid).and(WORKFLOW_USER_LIKES.UID.eq(likerUid))) - .fetchOne(0, classOf[Integer]) - .intValue() + getDSLContext.fetchCount( + WORKFLOW_USER_LIKES, + WORKFLOW_USER_LIKES.WID.eq(wid).and(WORKFLOW_USER_LIKES.UID.eq(likerUid)) + ) private def cloneRows: Int = - getDSLContext - .selectCount() - .from(WORKFLOW_USER_CLONES) - .where(WORKFLOW_USER_CLONES.WID.eq(wid).and(WORKFLOW_USER_CLONES.UID.eq(likerUid))) - .fetchOne(0, classOf[Integer]) - .intValue() + getDSLContext.fetchCount( + WORKFLOW_USER_CLONES, + WORKFLOW_USER_CLONES.WID.eq(wid).and(WORKFLOW_USER_CLONES.UID.eq(likerUid)) + ) private def userActionRows: Int = - getDSLContext - .selectCount() - .from(USER_ACTION) - .where(USER_ACTION.RESOURCE_ID.eq(wid)) - .fetchOne(0, classOf[Integer]) - .intValue() + getDSLContext.fetchCount(USER_ACTION, USER_ACTION.RESOURCE_ID.eq(wid)) private def isLiked(uid: Int): Boolean = isLikedHelper(Integer.valueOf(uid), ids(wid), types(Wf)).asScala.head.isLiked @@ -140,13 +118,6 @@ class HubResourceSpec private def hub: HubResource = new HubResource() - // A request whose remote address is not IPv4-shaped, to exercise the ip guard. - private def nonIpv4Req: HttpServletRequest = { - val r = stub[HttpServletRequest] - (r.getRemoteAddr _).when().returns("::1") - r - } - /** * Inserts a workflow with an explicit wid (the serial sequence is left alone so * these ids never collide with anything jOOQ generates). `withOwnerRows` also @@ -169,16 +140,16 @@ class HubResourceSpec .set(WORKFLOW.IS_PUBLIC, java.lang.Boolean.valueOf(isPublic)) .execute() if (withOwnerRows) { - getDSLContext - .insertInto(WORKFLOW_OF_USER) - .set(WORKFLOW_OF_USER.UID, Integer.valueOf(owner)) - .set(WORKFLOW_OF_USER.WID, Integer.valueOf(wfId)) - .execute() - grantWorkflowAccess(wfId, owner, PrivilegeEnum.WRITE) + seedWorkflowOwner(wfId, owner) } Integer.valueOf(wfId) } + private def seedWorkflowOwner(wfId: Int, owner: Int): Unit = { + insertWorkflowOfUser(owner, wfId) + insertWorkflowUserAccess(owner, wfId, PrivilegeEnum.WRITE) + } + private def seedDataset( dsId: Int, name: String, @@ -213,145 +184,74 @@ class HubResourceSpec Integer.valueOf(modelId) } - private def grantWorkflowAccess(wfId: Int, uid: Int, privilege: PrivilegeEnum): Unit = - getDSLContext - .insertInto(WORKFLOW_USER_ACCESS) - .set(WORKFLOW_USER_ACCESS.WID, Integer.valueOf(wfId)) - .set(WORKFLOW_USER_ACCESS.UID, Integer.valueOf(uid)) - .set(WORKFLOW_USER_ACCESS.PRIVILEGE, privilege) - .execute() - - private def grantDatasetAccess(dsId: Int, uid: Int, privilege: PrivilegeEnum): Unit = - getDSLContext - .insertInto(DATASET_USER_ACCESS) - .set(DATASET_USER_ACCESS.DID, Integer.valueOf(dsId)) - .set(DATASET_USER_ACCESS.UID, Integer.valueOf(uid)) - .set(DATASET_USER_ACCESS.PRIVILEGE, privilege) - .execute() - - private def grantModelAccess(modelId: Int, uid: Int, privilege: PrivilegeEnum): Unit = - getDSLContext - .insertInto(MODEL_USER_ACCESS) - .set(MODEL_USER_ACCESS.MID, Integer.valueOf(modelId)) - .set(MODEL_USER_ACCESS.UID, Integer.valueOf(uid)) - .set(MODEL_USER_ACCESS.PRIVILEGE, privilege) - .execute() - - private def seedWorkflowLike(wfId: Int, uid: Int): Unit = - getDSLContext - .insertInto(WORKFLOW_USER_LIKES) - .set(WORKFLOW_USER_LIKES.WID, Integer.valueOf(wfId)) - .set(WORKFLOW_USER_LIKES.UID, Integer.valueOf(uid)) - .execute() + private case class GrantRows( + table: Table[_ <: Record], + id: Field[Integer], + user: Field[Integer], + privilege: Field[PrivilegeEnum] + ) { + def insert(entityId: Int, uid: Int, value: PrivilegeEnum): Unit = + getDSLContext + .insertInto(table) + .set(id, Int.box(entityId)) + .set(user, Int.box(uid)) + .set(privilege, value) + .execute() + } - private def seedDatasetLike(dsId: Int, uid: Int): Unit = - getDSLContext - .insertInto(DATASET_USER_LIKES) - .set(DATASET_USER_LIKES.DID, Integer.valueOf(dsId)) - .set(DATASET_USER_LIKES.UID, Integer.valueOf(uid)) - .execute() + private case class InteractionRows( + table: Table[_ <: Record], + id: Field[Integer], + value: Field[Integer] + ) { + def insert(entityId: Int, n: Int): Unit = + getDSLContext.insertInto(table).set(id, Int.box(entityId)).set(value, Int.box(n)).execute() - private def seedModelLike(modelId: Int, uid: Int): Unit = - getDSLContext - .insertInto(MODEL_USER_LIKES) - .set(MODEL_USER_LIKES.MID, Integer.valueOf(modelId)) - .set(MODEL_USER_LIKES.UID, Integer.valueOf(uid)) - .execute() + def insertAll(entityId: Int, values: Int*): Unit = values.foreach(insert(entityId, _)) - private def seedWorkflowClone(wfId: Int, uid: Int): Unit = - getDSLContext - .insertInto(WORKFLOW_USER_CLONES) - .set(WORKFLOW_USER_CLONES.WID, Integer.valueOf(wfId)) - .set(WORKFLOW_USER_CLONES.UID, Integer.valueOf(uid)) - .execute() + def delete(entityId: Int): Unit = + getDSLContext.deleteFrom(table).where(id.eq(Int.box(entityId))).execute() - private def seedWorkflowViewCount(wfId: Int, count: Int): Unit = - getDSLContext - .insertInto(WORKFLOW_VIEW_COUNT) - .set(WORKFLOW_VIEW_COUNT.WID, Integer.valueOf(wfId)) - .set(WORKFLOW_VIEW_COUNT.VIEW_COUNT, Integer.valueOf(count)) - .execute() + private def select(entityId: Int) = + getDSLContext.select(value).from(table).where(id.eq(Int.box(entityId))) - private def seedDatasetViewCount(dsId: Int, count: Int): Unit = - getDSLContext - .insertInto(DATASET_VIEW_COUNT) - .set(DATASET_VIEW_COUNT.DID, Integer.valueOf(dsId)) - .set(DATASET_VIEW_COUNT.VIEW_COUNT, Integer.valueOf(count)) - .execute() + def all(entityId: Int): Seq[Int] = + select(entityId).fetchInto(classOf[Integer]).asScala.map(_.intValue()).toSeq - private def seedModelViewCount(modelId: Int, count: Int): Unit = - getDSLContext - .insertInto(MODEL_VIEW_COUNT) - .set(MODEL_VIEW_COUNT.MID, Integer.valueOf(modelId)) - .set(MODEL_VIEW_COUNT.VIEW_COUNT, Integer.valueOf(count)) - .execute() - - private def workflowLikeUids(wfId: Int): Set[Int] = - getDSLContext - .select(WORKFLOW_USER_LIKES.UID) - .from(WORKFLOW_USER_LIKES) - .where(WORKFLOW_USER_LIKES.WID.eq(Integer.valueOf(wfId))) - .fetchInto(classOf[Integer]) - .asScala - .map(_.intValue()) - .toSet - - private def datasetLikeUids(dsId: Int): Set[Int] = - getDSLContext - .select(DATASET_USER_LIKES.UID) - .from(DATASET_USER_LIKES) - .where(DATASET_USER_LIKES.DID.eq(Integer.valueOf(dsId))) - .fetchInto(classOf[Integer]) - .asScala - .map(_.intValue()) - .toSet - - private def modelLikeUids(modelId: Int): Set[Int] = - getDSLContext - .select(MODEL_USER_LIKES.UID) - .from(MODEL_USER_LIKES) - .where(MODEL_USER_LIKES.MID.eq(Integer.valueOf(modelId))) - .fetchInto(classOf[Integer]) - .asScala - .map(_.intValue()) - .toSet + def count(entityId: Int): Option[Int] = + Option(select(entityId).fetchOne(value)).map(_.intValue()) + } - private def workflowCloneUids(wfId: Int): Seq[Int] = - getDSLContext - .select(WORKFLOW_USER_CLONES.UID) - .from(WORKFLOW_USER_CLONES) - .where(WORKFLOW_USER_CLONES.WID.eq(Integer.valueOf(wfId))) - .fetchInto(classOf[Integer]) - .asScala - .map(_.intValue()) - .toSeq + // Fixture routing stays independent of the production EntityTables registries. + private val datasetGrants = + GrantRows( + DATASET_USER_ACCESS, + DATASET_USER_ACCESS.DID, + DATASET_USER_ACCESS.UID, + DATASET_USER_ACCESS.PRIVILEGE + ) + private val modelGrants = + GrantRows( + MODEL_USER_ACCESS, + MODEL_USER_ACCESS.MID, + MODEL_USER_ACCESS.UID, + MODEL_USER_ACCESS.PRIVILEGE + ) - private def workflowViewCount(wfId: Int): Option[Int] = - Option( - getDSLContext - .select(WORKFLOW_VIEW_COUNT.VIEW_COUNT) - .from(WORKFLOW_VIEW_COUNT) - .where(WORKFLOW_VIEW_COUNT.WID.eq(Integer.valueOf(wfId))) - .fetchOne(WORKFLOW_VIEW_COUNT.VIEW_COUNT) - ).map(_.intValue()) - - private def datasetViewCount(dsId: Int): Option[Int] = - Option( - getDSLContext - .select(DATASET_VIEW_COUNT.VIEW_COUNT) - .from(DATASET_VIEW_COUNT) - .where(DATASET_VIEW_COUNT.DID.eq(Integer.valueOf(dsId))) - .fetchOne(DATASET_VIEW_COUNT.VIEW_COUNT) - ).map(_.intValue()) - - private def modelViewCount(modelId: Int): Option[Int] = - Option( - getDSLContext - .select(MODEL_VIEW_COUNT.VIEW_COUNT) - .from(MODEL_VIEW_COUNT) - .where(MODEL_VIEW_COUNT.MID.eq(Integer.valueOf(modelId))) - .fetchOne(MODEL_VIEW_COUNT.VIEW_COUNT) - ).map(_.intValue()) + private val workflowLikes = + InteractionRows(WORKFLOW_USER_LIKES, WORKFLOW_USER_LIKES.WID, WORKFLOW_USER_LIKES.UID) + private val datasetLikes = + InteractionRows(DATASET_USER_LIKES, DATASET_USER_LIKES.DID, DATASET_USER_LIKES.UID) + private val modelLikes = + InteractionRows(MODEL_USER_LIKES, MODEL_USER_LIKES.MID, MODEL_USER_LIKES.UID) + private val workflowClones = + InteractionRows(WORKFLOW_USER_CLONES, WORKFLOW_USER_CLONES.WID, WORKFLOW_USER_CLONES.UID) + private val workflowViews = + InteractionRows(WORKFLOW_VIEW_COUNT, WORKFLOW_VIEW_COUNT.WID, WORKFLOW_VIEW_COUNT.VIEW_COUNT) + private val datasetViews = + InteractionRows(DATASET_VIEW_COUNT, DATASET_VIEW_COUNT.DID, DATASET_VIEW_COUNT.VIEW_COUNT) + private val modelViews = + InteractionRows(MODEL_VIEW_COUNT, MODEL_VIEW_COUNT.MID, MODEL_VIEW_COUNT.VIEW_COUNT) /** (uid, resourceType, resourceId, action literal, ip) for every audit row. */ private def auditRows(): Seq[(Integer, String, Int, String, String)] = @@ -371,52 +271,29 @@ class HubResourceSpec ) .toSeq - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - userDao = new UserDao(getDSLContext.configuration()) - workflowDao = new WorkflowDao(getDSLContext.configuration()) - workflowOfUserDao = new WorkflowOfUserDao(getDSLContext.configuration()) - workflowUserAccessDao = new WorkflowUserAccessDao(getDSLContext.configuration()) + override protected def onBeforeAll(): Unit = { + val userDao = new UserDao(getDSLContext.configuration()) - userDao.insert(makeUser(ownerUid, "hub_owner")) - userDao.insert(makeUser(likerUid, "hub_liker")) + userDao.insert(fixtureUser(ownerUid, "hub_owner")) + userDao.insert(fixtureUser(likerUid, "hub_liker")) // A third liker, needed by the ranking cases below to make "most liked" a // strict order (3 > 2 > 1) rather than a tie between two users' likes. - userDao.insert(makeUser(thirdUid, "hub_third")) - userDao.insert(makeUser(cachedUid, "hub_cached_uid")) - userDao.insert(makeUser(lastCachedUid, "hub_uid_127")) - userDao.insert(makeUser(firstUncachedUid, "hub_uid_128")) - - val wf = new Workflow - wf.setWid(Integer.valueOf(wid)) - wf.setName("hub_wf_" + UUID.randomUUID().toString.substring(0, 8)) - wf.setContent("{}") - wf.setDescription("hub test") - wf.setIsPublic(true) - wf.setCreationTime(new Timestamp(System.currentTimeMillis())) - wf.setLastModifiedTime(new Timestamp(System.currentTimeMillis())) - workflowDao.insert(wf) - - val ownership = new WorkflowOfUser - ownership.setUid(Integer.valueOf(ownerUid)) - ownership.setWid(Integer.valueOf(wid)) - workflowOfUserDao.insert(ownership) - - val access = new WorkflowUserAccess - access.setUid(Integer.valueOf(ownerUid)) - access.setWid(Integer.valueOf(wid)) - access.setPrivilege(PrivilegeEnum.WRITE) - workflowUserAccessDao.insert(access) - } - - override protected def afterAll(): Unit = closeConnectionPool() + userDao.insert(fixtureUser(thirdUid, "hub_third")) + userDao.insert(fixtureUser(cachedUid, "hub_cached_uid")) + userDao.insert(fixtureUser(lastCachedUid, "hub_uid_127")) + userDao.insert(fixtureUser(firstUncachedUid, "hub_uid_128")) + + workflowDao.insert(fixtureWorkflow(wid, "hub_wf_" + uniqueSuffix, "hub test", isPublic = true)) + + seedWorkflowOwner(wid, ownerUid) + } // Reset the per-entity hub rows so every test starts from a clean slate. - override protected def beforeEach(): Unit = { + override protected def cleanup(): Unit = { val ctx = getDSLContext - ctx.deleteFrom(WORKFLOW_USER_LIKES).where(WORKFLOW_USER_LIKES.WID.eq(wid)).execute() - ctx.deleteFrom(WORKFLOW_USER_CLONES).where(WORKFLOW_USER_CLONES.WID.eq(wid)).execute() - ctx.deleteFrom(WORKFLOW_VIEW_COUNT).where(WORKFLOW_VIEW_COUNT.WID.eq(wid)).execute() + workflowLikes.delete(wid) + workflowClones.delete(wid) + workflowViews.delete(wid) ctx.deleteFrom(USER_ACTION).where(USER_ACTION.RESOURCE_ID.eq(wid)).execute() // The cases added below seed workflows, datasets and models of their own (ids in the // 81xxxx / 82xxxx / 83xxxx / 84xxxx ranges) plus audit rows pointing at them. MockTexeraDB @@ -453,7 +330,7 @@ class HubResourceSpec it should "leave the ip column null when the remote address is not IPv4-shaped" in { val id = seedWorkflow(810102, "wf_audit_v6") - recordUserAction(nonIpv4Req, Some(Integer.valueOf(ownerUid)), id, Wf, ActionType.Clone) + recordUserAction(requestFrom("::1"), Some(Integer.valueOf(ownerUid)), id, Wf, ActionType.Clone) // Everything but the address is still recorded; only the ip column is skipped. auditRows() shouldBe Seq((Integer.valueOf(ownerUid), "workflow", 810102, "clone", null)) @@ -480,38 +357,18 @@ class HubResourceSpec } "recordLikeAction" should "insert a like the first time and remove it on unlike" in { - recordLikeAction( - req, - Integer.valueOf(likerUid), - UserRequest(wid, Wf), - isLike = true - ) shouldBe true + recordLike(likerUid, UserRequest(wid, Wf), isLike = true) shouldBe true likeRows shouldBe 1 isLiked(likerUid) shouldBe true - recordLikeAction( - req, - Integer.valueOf(likerUid), - UserRequest(wid, Wf), - isLike = false - ) shouldBe true + recordLike(likerUid, UserRequest(wid, Wf), isLike = false) shouldBe true likeRows shouldBe 0 isLiked(likerUid) shouldBe false } it should "return false when liking something already liked" in { - recordLikeAction( - req, - Integer.valueOf(likerUid), - UserRequest(wid, Wf), - isLike = true - ) shouldBe true - recordLikeAction( - req, - Integer.valueOf(likerUid), - UserRequest(wid, Wf), - isLike = true - ) shouldBe false + recordLike(likerUid, UserRequest(wid, Wf), isLike = true) shouldBe true + recordLike(likerUid, UserRequest(wid, Wf), isLike = true) shouldBe false likeRows shouldBe 1 } @@ -519,60 +376,45 @@ class HubResourceSpec val id = seedWorkflow(810201, "wf_like_audit") val request = UserRequest(id, Wf) - recordLikeAction(req, Integer.valueOf(ownerUid), request, isLike = true) shouldBe true - recordLikeAction(req, Integer.valueOf(ownerUid), request, isLike = true) shouldBe false - recordLikeAction(req, Integer.valueOf(ownerUid), request, isLike = false) shouldBe true + recordLike(ownerUid, request, isLike = true) shouldBe true + recordLike(ownerUid, request, isLike = true) shouldBe false + recordLike(ownerUid, request, isLike = false) shouldBe true // The rejected duplicate like contributes nothing: two accepted calls, two rows. auditRows() shouldBe Seq( (Integer.valueOf(ownerUid), "workflow", 810201, "like", "127.0.0.1"), (Integer.valueOf(ownerUid), "workflow", 810201, "unlike", "127.0.0.1") ) - workflowLikeUids(810201) shouldBe empty + workflowLikes.all(810201).toSet shouldBe empty } it should "return false and audit nothing when unliking an entity that was never liked" in { val id = seedWorkflow(810204, "wf_unlike_cold") - recordLikeAction( - req, - Integer.valueOf(ownerUid), - UserRequest(id, Wf), - isLike = false - ) shouldBe false + recordLike(ownerUid, UserRequest(id, Wf), isLike = false) shouldBe false auditRows() shouldBe empty - workflowLikeUids(810204) shouldBe empty + workflowLikes.all(810204).toSet shouldBe empty } it should "only remove the calling user's like, leaving other users' likes intact" in { val id = seedWorkflow(810205, "wf_like_two_users") - seedWorkflowLike(810205, ownerUid) - seedWorkflowLike(810205, likerUid) + workflowLikes.insert(810205, ownerUid) + workflowLikes.insert(810205, likerUid) - recordLikeAction( - req, - Integer.valueOf(ownerUid), - UserRequest(id, Wf), - isLike = false - ) shouldBe true + recordLike(ownerUid, UserRequest(id, Wf), isLike = false) shouldBe true - workflowLikeUids(810205) shouldBe Set(likerUid) + workflowLikes.all(810205).toSet shouldBe Set(likerUid) } it should "route the like to the table for its entity type when a workflow and a dataset share an id" in { seedWorkflow(830001, "wf_like_shared_id") seedDataset(830001, "ds_like_shared_id") - recordLikeAction( - req, - Integer.valueOf(ownerUid), - UserRequest(Integer.valueOf(830001), Ds), - isLike = true - ) shouldBe true + recordLike(ownerUid, UserRequest(Integer.valueOf(830001), Ds), isLike = true) shouldBe true - datasetLikeUids(830001) shouldBe Set(ownerUid) - workflowLikeUids(830001) shouldBe empty + datasetLikes.all(830001).toSet shouldBe Set(ownerUid) + workflowLikes.all(830001).toSet shouldBe empty } it should "route the like to the model table when a model shares the id" in { @@ -580,31 +422,21 @@ class HubResourceSpec seedDataset(830002, "ds_like_shared_with_model") seedModel(830002, "md_like_shared_id") - recordLikeAction( - req, - Integer.valueOf(ownerUid), - UserRequest(Integer.valueOf(830002), Md), - isLike = true - ) shouldBe true + recordLike(ownerUid, UserRequest(Integer.valueOf(830002), Md), isLike = true) shouldBe true - modelLikeUids(830002) shouldBe Set(ownerUid) - datasetLikeUids(830002) shouldBe empty - workflowLikeUids(830002) shouldBe empty + modelLikes.all(830002).toSet shouldBe Set(ownerUid) + datasetLikes.all(830002).toSet shouldBe empty + workflowLikes.all(830002).toSet shouldBe empty } it should "unlike a model, leaving other likers alone" in { seedModel(840101, "md_unlike") - seedModelLike(840101, likerUid) - seedModelLike(840101, ownerUid) + modelLikes.insert(840101, likerUid) + modelLikes.insert(840101, ownerUid) - recordLikeAction( - req, - Integer.valueOf(ownerUid), - UserRequest(Integer.valueOf(840101), Md), - isLike = false - ) shouldBe true + recordLike(ownerUid, UserRequest(Integer.valueOf(840101), Md), isLike = false) shouldBe true - modelLikeUids(840101) shouldBe Set(likerUid) + modelLikes.all(840101).toSet shouldBe Set(likerUid) } "recordCloneAction" should "record a clone row and a user_action row" in { @@ -620,7 +452,7 @@ class HubResourceSpec // The asymmetry is deliberate: the audit trail records both attempts while the // existence check keeps workflow_user_clones at one row for the (uid, wid) pair. - workflowCloneUids(810402) shouldBe Seq(ownerUid) + workflowClones.all(810402) shouldBe Seq(ownerUid) auditRows() shouldBe Seq( (Integer.valueOf(ownerUid), "workflow", 810402, "clone", "127.0.0.1"), (Integer.valueOf(ownerUid), "workflow", 810402, "clone", "127.0.0.1") @@ -641,8 +473,8 @@ class HubResourceSpec seedWorkflow(810302, "wf_not_liked") seedDataset(820301, "ds_liked") seedDataset(820302, "ds_not_liked") - seedWorkflowLike(810301, ownerUid) - seedDatasetLike(820301, ownerUid) + workflowLikes.insert(810301, ownerUid) + datasetLikes.insert(820301, ownerUid) val responses = isLikedHelper( Integer.valueOf(ownerUid), @@ -662,7 +494,7 @@ class HubResourceSpec it should "keep model likes apart from the other entity types" in { seedModel(840501, "md_is_liked") - seedModelLike(840501, ownerUid) + modelLikes.insert(840501, ownerUid) seedDataset(820920, "ds_is_liked") val responses = isLikedHelper( @@ -676,7 +508,7 @@ class HubResourceSpec it should "not report another user's like as the caller's" in { seedWorkflow(810303, "wf_liked_by_other") - seedWorkflowLike(810303, likerUid) + workflowLikes.insert(810303, likerUid) isLikedHelper(Integer.valueOf(ownerUid), ids(810303), types(Wf)).asScala .map(_.isLiked) shouldBe Seq(false) @@ -691,7 +523,7 @@ class HubResourceSpec "isLiked" should "resolve the liked flag against the session user, not another user" in { seedWorkflow(810304, "wf_session_like") - seedWorkflowLike(810304, ownerUid) + workflowLikes.insert(810304, ownerUid) hub.isLiked(session(ownerUid), ids(810304), types(Wf)).asScala.map(_.isLiked) shouldBe Seq(true) hub.isLiked(session(likerUid), ids(810304), types(Wf)).asScala.map(_.isLiked) shouldBe Seq( @@ -754,7 +586,7 @@ class HubResourceSpec it should "ignore a grant, which is what the per-kind owners endpoints answer instead" in { // The bug itself: a grant without anything published must not make you an owner here. - grantWorkflowAccess(wid, likerUid, PrivilegeEnum.READ) + insertWorkflowUserAccess(likerUid, wid, PrivilegeEnum.READ) hub.getPublicOwners(Wf).asScala should not contain "hub_liker@test.com" } @@ -785,15 +617,8 @@ class HubResourceSpec } "postView" should "increment the view count and record a view action" in { - val resource = new HubResource() - resource.postView( - req, - ViewRequest(Integer.valueOf(wid), Integer.valueOf(likerUid), Wf) - ) shouldBe 1 - resource.postView( - req, - ViewRequest(Integer.valueOf(wid), Integer.valueOf(likerUid), Wf) - ) shouldBe 2 + view(Integer.valueOf(wid), Integer.valueOf(likerUid)) shouldBe 1 + view(Integer.valueOf(wid), Integer.valueOf(likerUid)) shouldBe 2 userActionRows shouldBe 2 } @@ -801,7 +626,7 @@ class HubResourceSpec val id = seedWorkflow(810602, "wf_view_audit") // The viewer (likerUid) is deliberately not the owner (ownerUid), so an // implementation that audited the owner instead would fail here. - hub.postView(req, ViewRequest(id, Integer.valueOf(likerUid), Wf)) + view(id, Integer.valueOf(likerUid)) auditRows() shouldBe Seq( (Integer.valueOf(likerUid), "workflow", 810602, "view", "127.0.0.1") @@ -810,8 +635,8 @@ class HubResourceSpec it should "record an anonymous view (uid 0 or none) with a NULL uid" in { val id = seedWorkflow(810603, "wf_view_anonymous") - hub.postView(req, ViewRequest(id, Integer.valueOf(0), Wf)) shouldBe 1 - hub.postView(req, ViewRequest(id, null, Wf)) shouldBe 2 + view(id, Integer.valueOf(0)) shouldBe 1 + view(id, null) shouldBe 2 auditRows() shouldBe Seq( (null, "workflow", 810603, "view", "127.0.0.1"), @@ -821,12 +646,12 @@ class HubResourceSpec it should "leave the count unchanged when the view cannot be recorded" in { val id = seedWorkflow(810605, "wf_view_missing_user") - hub.postView(req, ViewRequest(id, Integer.valueOf(likerUid), Wf)) shouldBe 1 + view(id, Integer.valueOf(likerUid)) shouldBe 1 // A uid with no user row, e.g. an account deleted while another tab was still open. - an[Exception] should be thrownBy hub.postView(req, ViewRequest(id, Integer.valueOf(999999), Wf)) + an[Exception] should be thrownBy view(id, Integer.valueOf(999999)) - workflowViewCount(810605) shouldBe Some(1) + workflowViews.count(810605) shouldBe Some(1) } it should "keep workflow and dataset view counts apart when the ids collide" in { @@ -834,12 +659,12 @@ class HubResourceSpec seedDataset(830001, "ds_view_shared_id") val shared = Integer.valueOf(830001) - hub.postView(req, ViewRequest(shared, Integer.valueOf(ownerUid), Wf)) - hub.postView(req, ViewRequest(shared, Integer.valueOf(ownerUid), Wf)) - hub.postView(req, ViewRequest(shared, Integer.valueOf(ownerUid), Ds)) + view(shared, Integer.valueOf(ownerUid)) + view(shared, Integer.valueOf(ownerUid)) + view(shared, Integer.valueOf(ownerUid), Ds) - workflowViewCount(830001) shouldBe Some(2) - datasetViewCount(830001) shouldBe Some(1) + workflowViews.count(830001) shouldBe Some(2) + datasetViews.count(830001) shouldBe Some(1) } it should "keep model view counts apart from the dataset and workflow rows" in { @@ -848,17 +673,25 @@ class HubResourceSpec seedModel(830003, "md_view_shared_id") val shared = Integer.valueOf(830003) - hub.postView(req, ViewRequest(shared, Integer.valueOf(ownerUid), Md)) - hub.postView(req, ViewRequest(shared, Integer.valueOf(ownerUid), Md)) - hub.postView(req, ViewRequest(shared, Integer.valueOf(ownerUid), Ds)) + view(shared, Integer.valueOf(ownerUid), Md) + view(shared, Integer.valueOf(ownerUid), Md) + view(shared, Integer.valueOf(ownerUid), Ds) + + modelViews.count(830003) shouldBe Some(2) + datasetViews.count(830003) shouldBe Some(1) + workflowViews.count(830003) shouldBe None + } - modelViewCount(830003) shouldBe Some(2) - datasetViewCount(830003) shouldBe Some(1) - workflowViewCount(830003) shouldBe None + private def seedWorkflowWithCounts(wid: Int, name: String): Integer = { + val id = seedWorkflow(wid, name) + workflowViews.insert(wid, 5) + workflowLikes.insertAll(wid, ownerUid, likerUid) + workflowClones.insert(wid, ownerUid) + id } "getCounts" should "report the like count for the entity" in { - recordLikeAction(req, Integer.valueOf(likerUid), UserRequest(wid, Wf), isLike = true) + recordLike(likerUid, UserRequest(wid, Wf), isLike = true) val response = new HubResource().getCounts(types(Wf), ids(wid), actions(ActionType.Like)).asScala.head @@ -874,10 +707,7 @@ class HubResourceSpec } it should "return view, like and clone counts by default" in { - val id = seedWorkflow(810801, "wf_counts") - seedWorkflowViewCount(810801, 5) - Seq(ownerUid, likerUid).foreach(seedWorkflowLike(810801, _)) - seedWorkflowClone(810801, ownerUid) + val id = seedWorkflowWithCounts(810801, "wf_counts") val responses = hub.getCounts(types(Wf), ids(810801), null).asScala @@ -885,45 +715,30 @@ class HubResourceSpec responses.head.entityId shouldBe id // Distinct 5 / 2 / 1 so swapping two of the three maps cannot pass. responses.head.counts.asScala.toMap shouldBe Map( - (ActionType.View: ActionType) -> 5, - (ActionType.Like: ActionType) -> 2, - (ActionType.Clone: ActionType) -> 1 + ActionType.View -> 5, + ActionType.Like -> 2, + ActionType.Clone -> 1 ) } it should "return only the requested action types" in { - seedWorkflow(810802, "wf_counts_filtered") - seedWorkflowViewCount(810802, 5) - Seq(ownerUid, likerUid).foreach(seedWorkflowLike(810802, _)) - seedWorkflowClone(810802, ownerUid) + seedWorkflowWithCounts(810802, "wf_counts_filtered") - val counts = hub - .getCounts(types(Wf), ids(810802), actions(ActionType.Like)) - .asScala - .head - .counts - .asScala - .toMap + val counts = countsFor(Wf, 810802, actions(ActionType.Like)) // View and clone data exists for this workflow; the filter must drop both keys. - counts shouldBe Map((ActionType.Like: ActionType) -> 2) + counts shouldBe Map(ActionType.Like -> 2) } it should "backfill a zero view-count row for an entity that has never been viewed" in { seedWorkflow(810803, "wf_counts_backfill") - workflowViewCount(810803) shouldBe None + workflowViews.count(810803) shouldBe None - val counts = hub - .getCounts(types(Wf), ids(810803), actions(ActionType.View)) - .asScala - .head - .counts - .asScala - .toMap + val counts = countsFor(Wf, 810803, actions(ActionType.View)) - counts shouldBe Map((ActionType.View: ActionType) -> 0) + counts shouldBe Map(ActionType.View -> 0) // The backfill is a real side effect: the row is written by getCounts itself. - workflowViewCount(810803) shouldBe Some(0) + workflowViews.count(810803) shouldBe Some(0) } it should "not touch the view-count table when view is not among the requested actions" in { @@ -931,42 +746,38 @@ class HubResourceSpec hub.getCounts(types(Wf), ids(810804), actions(ActionType.Like)) - workflowViewCount(810804) shouldBe None + workflowViews.count(810804) shouldBe None } it should "report zero clones for a dataset rather than failing on the absent clone table" in { seedDataset(820801, "ds_counts") - seedDatasetViewCount(820801, 7) - Seq(ownerUid, likerUid, thirdUid).foreach(seedDatasetLike(820801, _)) + datasetViews.insert(820801, 7) + datasetLikes.insertAll(820801, ownerUid, likerUid, thirdUid) - val counts = hub.getCounts(types(Ds), ids(820801), null).asScala.head.counts - - counts.asScala.toMap shouldBe Map( - (ActionType.View: ActionType) -> 7, - (ActionType.Like: ActionType) -> 3, - (ActionType.Clone: ActionType) -> 0 + countsFor(Ds, 820801) shouldBe Map( + ActionType.View -> 7, + ActionType.Like -> 3, + ActionType.Clone -> 0 ) } it should "report view and like counts for a model, and zero clones" in { seedModel(840301, "md_counts") - seedModelViewCount(840301, 5) - Seq(ownerUid, likerUid).foreach(seedModelLike(840301, _)) - - val counts = hub.getCounts(types(Md), ids(840301), null).asScala.head.counts + modelViews.insert(840301, 5) + modelLikes.insertAll(840301, ownerUid, likerUid) - counts.asScala.toMap shouldBe Map( - (ActionType.View: ActionType) -> 5, - (ActionType.Like: ActionType) -> 2, - (ActionType.Clone: ActionType) -> 0 + countsFor(Md, 840301) shouldBe Map( + ActionType.View -> 5, + ActionType.Like -> 2, + ActionType.Clone -> 0 ) } it should "answer a mixed batch with one response per requested pair" in { seedWorkflow(810805, "wf_mixed") seedDataset(820802, "ds_mixed") - seedWorkflowLike(810805, ownerUid) - Seq(ownerUid, likerUid).foreach(seedDatasetLike(820802, _)) + workflowLikes.insert(810805, ownerUid) + datasetLikes.insertAll(820802, ownerUid, likerUid) val responses = hub.getCounts(types(Wf, Ds), ids(810805, 820802), actions(ActionType.Like)).asScala @@ -986,12 +797,7 @@ class HubResourceSpec "versionedResourcesByIdsQuery" should "carry only the viewer's own grant, never another user's" in { val did = seedDataset(820860, "ds_two_grants") for ((uid, privilege) <- Seq(ownerUid -> PrivilegeEnum.WRITE, likerUid -> PrivilegeEnum.READ)) { - getDSLContext - .insertInto(DATASET_USER_ACCESS) - .set(DATASET_USER_ACCESS.DID, did) - .set(DATASET_USER_ACCESS.UID, Integer.valueOf(uid)) - .set(DATASET_USER_ACCESS.PRIVILEGE, privilege) - .execute() + datasetGrants.insert(did, uid, privilege) } val tables = VersionedResourceTables.DatasetTables def grantsSeenBy(uid: Integer): Seq[PrivilegeEnum] = @@ -1009,7 +815,7 @@ class HubResourceSpec } "getTops" should "list the liked public entity under the 'like' key" in { - recordLikeAction(req, Integer.valueOf(likerUid), UserRequest(wid, Wf), isLike = true) + recordLike(likerUid, UserRequest(wid, Wf), isLike = true) val tops = new HubResource().getTops(Wf, actions(ActionType.Like), null, null) tops.keySet.asScala should contain("like") @@ -1042,7 +848,7 @@ class HubResourceSpec it should "return an empty clone bucket when clone is asked for explicitly" in { seedDataset(820850, "ds_no_clones") - seedDatasetLike(820850, likerUid) + datasetLikes.insert(820850, likerUid) hub.getTops(Ds, actions(ActionType.Clone), null, null).get("clone").asScala shouldBe empty } @@ -1051,9 +857,9 @@ class HubResourceSpec val hot = seedWorkflow(810701, "wf_hot") val warm = seedWorkflow(810702, "wf_warm") seedWorkflow(810703, "wf_cold") - Seq(ownerUid, likerUid, thirdUid).foreach(seedWorkflowLike(810701, _)) - Seq(ownerUid, likerUid).foreach(seedWorkflowLike(810702, _)) - seedWorkflowLike(810703, ownerUid) + workflowLikes.insertAll(810701, ownerUid, likerUid, thirdUid) + workflowLikes.insertAll(810702, ownerUid, likerUid) + workflowLikes.insert(810703, ownerUid) val liked = hub .getTops(Wf, actions(ActionType.Like), null, Integer.valueOf(2)) @@ -1069,8 +875,8 @@ class HubResourceSpec it should "exclude non-public workflows even when they are the most liked" in { val visible = seedWorkflow(810704, "wf_public_liked", isPublic = true) seedWorkflow(810705, "wf_private_liked", isPublic = false) - seedWorkflowLike(810704, ownerUid) - Seq(ownerUid, likerUid, thirdUid).foreach(seedWorkflowLike(810705, _)) + workflowLikes.insert(810704, ownerUid) + workflowLikes.insertAll(810705, ownerUid, likerUid, thirdUid) val liked = hub.getTops(Wf, actions(ActionType.Like), null, null).get("like").asScala @@ -1080,7 +886,7 @@ class HubResourceSpec it should "fall back to a limit of 8 when the limit is missing or non-positive" in { (1 to 9).foreach { i => seedWorkflow(810710 + i, s"wf_top_$i") - seedWorkflowLike(810710 + i, ownerUid) + workflowLikes.insert(810710 + i, ownerUid) } def topCount(limit: Integer): Int = @@ -1102,8 +908,8 @@ class HubResourceSpec it should "rank the clone bucket independently of the like bucket" in { val mostLiked = seedWorkflow(810707, "wf_most_liked") val mostCloned = seedWorkflow(810708, "wf_most_cloned") - Seq(ownerUid, likerUid).foreach(seedWorkflowLike(810707, _)) - Seq(ownerUid, likerUid).foreach(seedWorkflowClone(810708, _)) + workflowLikes.insertAll(810707, ownerUid, likerUid) + workflowClones.insertAll(810708, ownerUid, likerUid) val tops = hub.getTops(Wf, null, null, Integer.valueOf(1)).asScala @@ -1111,6 +917,16 @@ class HubResourceSpec tops("clone").asScala.map(_.workflow.get.workflow.getWid) shouldBe Seq(mostCloned) } + private def accessByEntity( + kinds: java.util.List[EntityType], + entityIds: java.util.List[Integer] + ): Map[(EntityType, Int), Set[Int]] = + hub + .userAccess(kinds, entityIds) + .asScala + .map(r => (r.entityType, r.entityId.intValue()) -> r.userIds.asScala.map(_.intValue()).toSet) + .toMap + "userAccess" should "return the user ids granted access to the entity" in { val response = new HubResource().userAccess(types(Wf), ids(wid)).asScala.head response.entityId shouldBe Integer.valueOf(wid) @@ -1121,17 +937,11 @@ class HubResourceSpec seedWorkflow(810901, "wf_access", withOwnerRows = false) seedDataset(820901, "ds_access") // Disjoint grantee sets so reading the wrong access table cannot pass. - grantWorkflowAccess(810901, ownerUid, PrivilegeEnum.WRITE) - grantWorkflowAccess(810901, likerUid, PrivilegeEnum.READ) - grantDatasetAccess(820901, thirdUid, PrivilegeEnum.READ) - - val byEntity = hub - .userAccess(types(Wf, Ds), ids(810901, 820901)) - .asScala - .map(r => (r.entityType, r.entityId.intValue()) -> r.userIds.asScala.map(_.intValue()).toSet) - .toMap + insertWorkflowUserAccess(ownerUid, 810901, PrivilegeEnum.WRITE) + insertWorkflowUserAccess(likerUid, 810901, PrivilegeEnum.READ) + datasetGrants.insert(820901, thirdUid, PrivilegeEnum.READ) - byEntity shouldBe Map( + accessByEntity(types(Wf, Ds), ids(810901, 820901)) shouldBe Map( (Wf, 810901) -> Set(ownerUid, likerUid), (Ds, 820901) -> Set(thirdUid) ) @@ -1141,16 +951,10 @@ class HubResourceSpec seedModel(840401, "md_access") seedDataset(820910, "ds_access_noise") // Disjoint grantee sets so reading the wrong access table cannot pass. - grantModelAccess(840401, likerUid, PrivilegeEnum.WRITE) - grantDatasetAccess(820910, thirdUid, PrivilegeEnum.READ) + modelGrants.insert(840401, likerUid, PrivilegeEnum.WRITE) + datasetGrants.insert(820910, thirdUid, PrivilegeEnum.READ) - val byEntity = hub - .userAccess(types(Md, Ds), ids(840401, 820910)) - .asScala - .map(r => (r.entityType, r.entityId.intValue()) -> r.userIds.asScala.map(_.intValue()).toSet) - .toMap - - byEntity shouldBe Map( + accessByEntity(types(Md, Ds), ids(840401, 820910)) shouldBe Map( (Md, 840401) -> Set(likerUid), (Ds, 820910) -> Set(thirdUid) ) @@ -1168,7 +972,7 @@ class HubResourceSpec it should "emit a single response when the same entity id is requested twice" in { seedWorkflow(810903, "wf_dup_request", withOwnerRows = false) - grantWorkflowAccess(810903, ownerUid, PrivilegeEnum.READ) + insertWorkflowUserAccess(ownerUid, 810903, PrivilegeEnum.READ) val responses = hub.userAccess(types(Wf, Wf), ids(810903, 810903)).asScala @@ -1205,37 +1009,38 @@ class HubResourceSpec entry.coverImage shouldBe empty } - // mapWorkflowEntries compares two boxed Integers, so the owner's own request must be - // recognised on both sides of the default Integer cache (-128..127). - it should "set isOwner for the owner's own request when the uid is outside the Integer cache" in { - val id = seedWorkflow(811003, "wf_mine_uncached", owner = ownerUid) - - fetchDashboardWorkflowsByWids(Seq(id), Integer.valueOf(ownerUid)).head.isOwner shouldBe true - } - - it should "set isOwner for the owner's own request when the uid is inside the Integer cache" in { - val id = seedWorkflow(811004, "wf_mine_cached", owner = cachedUid) - - fetchDashboardWorkflowsByWids(Seq(id), Integer.valueOf(cachedUid)).head.isOwner shouldBe true - } - - // The boundary itself: 127 is the last cached value and 128 the first uncached one. - it should "set isOwner for the highest uid inside the Integer cache (127)" in { - val id = seedWorkflow(811006, "wf_mine_uid_127", owner = lastCachedUid) - - fetchDashboardWorkflowsByWids( - Seq(id), - Integer.valueOf(lastCachedUid) - ).head.isOwner shouldBe true - } - - it should "set isOwner for the lowest uid outside the Integer cache (128)" in { - val id = seedWorkflow(811007, "wf_mine_uid_128", owner = firstUncachedUid) - - fetchDashboardWorkflowsByWids( - Seq(id), - Integer.valueOf(firstUncachedUid) - ).head.isOwner shouldBe true + // Cover boxed owner identities on both sides of the Integer cache boundary. + Seq( + ( + "set isOwner for the owner's own request when the uid is outside the Integer cache", + 811003, + "wf_mine_uncached", + ownerUid + ), + ( + "set isOwner for the owner's own request when the uid is inside the Integer cache", + 811004, + "wf_mine_cached", + cachedUid + ), + ( + "set isOwner for the highest uid inside the Integer cache (127)", + 811006, + "wf_mine_uid_127", + lastCachedUid + ), + ( + "set isOwner for the lowest uid outside the Integer cache (128)", + 811007, + "wf_mine_uid_128", + firstUncachedUid + ) + ).foreach { + case (description, workflowId, name, uid) => + it should description in { + val id = seedWorkflow(workflowId, name, owner = uid) + fetchDashboardWorkflowsByWids(Seq(id), Integer.valueOf(uid)).head.isOwner shouldBe true + } } it should "clear isOwner for a different uid and for an anonymous (null) uid" in { @@ -1251,7 +1056,7 @@ class HubResourceSpec // mapWorkflowEntries is what keeps that one false. it should "clear isOwner for a workflow with no ownership row, for an authenticated and an anonymous caller" in { val id = seedWorkflow(811005, "wf_unowned", withOwnerRows = false) - grantWorkflowAccess(id, ownerUid, PrivilegeEnum.READ) + insertWorkflowUserAccess(ownerUid, id, PrivilegeEnum.READ) val entry = fetchDashboardWorkflowsByWids(Seq(id), Integer.valueOf(ownerUid)).head entry.ownerId shouldBe null @@ -1261,8 +1066,8 @@ class HubResourceSpec it should "return one entry per workflow, carrying only the viewer's access level" in { val id = seedWorkflow(811008, "wf_shared_twice") - grantWorkflowAccess(id, likerUid, PrivilegeEnum.READ) - grantWorkflowAccess(id, thirdUid, PrivilegeEnum.WRITE) + insertWorkflowUserAccess(likerUid, id, PrivilegeEnum.READ) + insertWorkflowUserAccess(thirdUid, id, PrivilegeEnum.WRITE) def levelsSeenBy(uid: Integer) = fetchDashboardWorkflowsByWids(Seq(id), uid).map(_.accessLevel) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/UserResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/UserResourceSpec.scala index 90258cc499f..139a6ee7c93 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/UserResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/UserResourceSpec.scala @@ -19,14 +19,11 @@ package org.apache.texera.web.resource.dashboard.user -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.USER import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum import org.apache.texera.dao.jooq.generated.tables.daos.UserDao import org.apache.texera.dao.jooq.generated.tables.pojos.User -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import javax.ws.rs.WebApplicationException import javax.ws.rs.core.Response @@ -35,12 +32,7 @@ import javax.ws.rs.core.Response * Covers the joining-reason endpoints against embedded Postgres: whether a user still has to be * prompted, and that submitting a reason persists and flips that answer. */ -class UserResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class UserResourceSpec extends DatabaseFlatSpec(cleanupAfterEach = true, cleanupAfterAll = true) { private val testUid = 8000 + scala.util.Random.nextInt(1000) private val unknownUid = testUid + 1 @@ -48,23 +40,13 @@ class UserResourceSpec private var userDao: UserDao = _ private var resource: UserResource = _ - override protected def beforeAll(): Unit = initializeDBAndReplaceDSLContext() - - override protected def afterAll(): Unit = { - cleanup() - shutdownDB() - } - - override protected def beforeEach(): Unit = { + override protected def onBeforeEach(): Unit = { userDao = new UserDao(getDSLContext.configuration()) resource = new UserResource() - cleanup() userDao.insert(seedUser()) } - override protected def afterEach(): Unit = cleanup() - - private def cleanup(): Unit = + override protected def cleanup(): Unit = getDSLContext.deleteFrom(USER).where(USER.UID.in(testUid, unknownUid)).execute() /** A freshly registered user: joining reason not yet supplied. */ diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/dataset/utils/DatasetStatisticsUtilsSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/dataset/utils/DatasetStatisticsUtilsSpec.scala index 7dc0878c3d1..c7504c68f78 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/dataset/utils/DatasetStatisticsUtilsSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/dataset/utils/DatasetStatisticsUtilsSpec.scala @@ -19,12 +19,10 @@ package org.apache.texera.web.resource.dashboard.user.dataset.utils -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.{DATASET, USER} import org.apache.texera.dao.jooq.generated.tables.daos.{DatasetDao, UserDao} import org.apache.texera.dao.jooq.generated.tables.pojos.{Dataset, User} -import org.scalatest.BeforeAndAfterAll -import org.scalatest.flatspec.AnyFlatSpec import java.sql.Timestamp import java.util.UUID @@ -43,7 +41,7 @@ import java.util.UUID * rows are uniformly private (or uniformly downloadable) cannot tell the owner * filter apart from an owner filter plus a spurious visibility predicate. */ -class DatasetStatisticsUtilsSpec extends AnyFlatSpec with BeforeAndAfterAll with MockTexeraDB { +class DatasetStatisticsUtilsSpec extends DatabaseFlatSpec(cleanupBeforeEach = false) { private val ownerUid = 7000 + scala.util.Random.nextInt(1000) private val otherUid = ownerUid + 1 @@ -52,14 +50,11 @@ class DatasetStatisticsUtilsSpec extends AnyFlatSpec with BeforeAndAfterAll with private var userDao: UserDao = _ private var datasetDao: DatasetDao = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() + override protected def onBeforeAll(): Unit = { userDao = new UserDao(getDSLContext.configuration()) datasetDao = new DatasetDao(getDSLContext.configuration()) } - override protected def afterAll(): Unit = shutdownDB() - private def resetFixtures(): Unit = { Seq(ownerUid, otherUid, strangerUid).foreach { uid => getDSLContext.deleteFrom(DATASET).where(DATASET.OWNER_UID.eq(uid)).execute() diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResourceSpec.scala index 23787febe53..8c58db4af11 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResourceSpec.scala @@ -20,67 +20,33 @@ package org.apache.texera.web.resource.dashboard.user.quota import org.apache.texera.auth.SessionUser -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum -import org.apache.texera.dao.jooq.generated.tables.daos.{ - DatasetDao, - UserDao, - WorkflowDao, - WorkflowExecutionsDao, - WorkflowOfUserDao, - WorkflowUserAccessDao, - WorkflowVersionDao -} import org.apache.texera.dao.jooq.generated.tables.pojos.{ Dataset, User, Workflow, WorkflowExecutions, - WorkflowOfUser, - WorkflowUserAccess, WorkflowVersion } -import org.scalatest.BeforeAndAfterAll -import org.scalatest.flatspec.AnyFlatSpec +import org.apache.texera.web.resource.dashboard.UserDashboardFixtureSupport -import java.sql.Timestamp -import java.util.UUID import scala.jdk.CollectionConverters._ import javax.ws.rs.WebApplicationException -class UserQuotaResourceSpec extends AnyFlatSpec with BeforeAndAfterAll with MockTexeraDB { +class UserQuotaResourceSpec + extends DatabaseFlatSpec(cleanupBeforeEach = false) + with UserDashboardFixtureSupport { private val testUid = 4000 + scala.util.Random.nextInt(1000) private val testWid = 5000 + scala.util.Random.nextInt(1000) - private var userDao: UserDao = _ - private var workflowDao: WorkflowDao = _ - private var workflowVersionDao: WorkflowVersionDao = _ - private var workflowOfUserDao: WorkflowOfUserDao = _ - private var workflowUserAccessDao: WorkflowUserAccessDao = _ - private var workflowExecutionsDao: WorkflowExecutionsDao = _ - private var datasetDao: DatasetDao = _ - private var testUser: User = _ private var testWorkflow: Workflow = _ private var testVersion: WorkflowVersion = _ private val resource = new UserQuotaResource - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - - userDao = new UserDao(getDSLContext.configuration()) - workflowDao = new WorkflowDao(getDSLContext.configuration()) - workflowVersionDao = new WorkflowVersionDao(getDSLContext.configuration()) - workflowOfUserDao = new WorkflowOfUserDao(getDSLContext.configuration()) - workflowUserAccessDao = new WorkflowUserAccessDao(getDSLContext.configuration()) - workflowExecutionsDao = new WorkflowExecutionsDao(getDSLContext.configuration()) - datasetDao = new DatasetDao(getDSLContext.configuration()) - } - - override protected def afterAll(): Unit = shutdownDB() - // Each test starts from a clean slate for the ids under test, then seeds // only what it needs, so tests are order-independent. private def resetFixtures(): Unit = { @@ -92,28 +58,11 @@ class UserQuotaResourceSpec extends AnyFlatSpec with BeforeAndAfterAll with Mock testUser.setEmail("quota@example.com") userDao.insert(testUser) - testWorkflow = new Workflow - testWorkflow.setWid(testWid) - testWorkflow.setName("quota_workflow_" + UUID.randomUUID().toString.substring(0, 8)) - testWorkflow.setContent("{}") - testWorkflow.setDescription("desc") - testWorkflow.setCreationTime(new Timestamp(System.currentTimeMillis())) - testWorkflow.setLastModifiedTime(new Timestamp(System.currentTimeMillis())) - workflowDao.insert(testWorkflow) - - testVersion = new WorkflowVersion - testVersion.setWid(testWid) - testVersion.setContent("{}") - testVersion.setCreationTime(new Timestamp(System.currentTimeMillis())) - workflowVersionDao.insert(testVersion) + testWorkflow = insertWorkflow(testWid, "quota_workflow_" + uniqueSuffix, description = "desc") + testVersion = insertWorkflowVersion(testWid) } private def cleanupTestData(): Unit = { - val vidSubquery = getDSLContext - .select(WORKFLOW_VERSION.VID) - .from(WORKFLOW_VERSION) - .where(WORKFLOW_VERSION.WID.eq(testWid)) - getDSLContext .deleteFrom(OPERATOR_PORT_EXECUTIONS) .where( @@ -136,73 +85,30 @@ class UserQuotaResourceSpec extends AnyFlatSpec with BeforeAndAfterAll with Mock ) ) .execute() - getDSLContext - .deleteFrom(WORKFLOW_EXECUTIONS) - .where(WORKFLOW_EXECUTIONS.VID.in(vidSubquery)) - .execute() - getDSLContext.deleteFrom(WORKFLOW_VERSION).where(WORKFLOW_VERSION.WID.eq(testWid)).execute() - getDSLContext - .deleteFrom(WORKFLOW_USER_ACCESS) - .where(WORKFLOW_USER_ACCESS.UID.eq(testUid)) - .execute() - getDSLContext.deleteFrom(WORKFLOW_OF_USER).where(WORKFLOW_OF_USER.UID.eq(testUid)).execute() - getDSLContext.deleteFrom(WORKFLOW).where(WORKFLOW.WID.eq(testWid)).execute() + cleanupWorkflowRecords(Seq(testWid), includeUserAccess = true) getDSLContext.deleteFrom(DATASET).where(DATASET.OWNER_UID.eq(testUid)).execute() getDSLContext.deleteFrom(USER).where(USER.UID.eq(testUid)).execute() } // ─── helpers ────────────────────────────────────────────────────────────── - private def insertOwnership(): Unit = { - val ownership = new WorkflowOfUser - ownership.setUid(testUid) - ownership.setWid(testWid) - workflowOfUserDao.insert(ownership) - } + private def insertOwnership(): Unit = insertWorkflowOfUser(testUid, testWid) - private def insertAccess(): Unit = { - val access = new WorkflowUserAccess - access.setUid(testUid) - access.setWid(testWid) - access.setPrivilege(PrivilegeEnum.READ) - workflowUserAccessDao.insert(access) - } + private def insertAccess(): Unit = insertWorkflowUserAccess(testUid, testWid, PrivilegeEnum.READ) - private def insertWriteAccess(): Unit = { - val access = new WorkflowUserAccess - access.setUid(testUid) - access.setWid(testWid) - access.setPrivilege(PrivilegeEnum.WRITE) - workflowUserAccessDao.insert(access) - } + private def insertWriteAccess(): Unit = + insertWorkflowUserAccess(testUid, testWid, PrivilegeEnum.WRITE) - private def insertExecution(): WorkflowExecutions = { - val execution = new WorkflowExecutions - execution.setVid(testVersion.getVid) - execution.setUid(testUid) - execution.setStatus(0.toByte) - execution.setResult("") - execution.setLogLocation("") - execution.setStartingTime(new Timestamp(System.currentTimeMillis())) - execution.setBookmarked(false) - execution.setName("exec-" + UUID.randomUUID().toString.substring(0, 8)) - execution.setEnvironmentVersion("test-env-1.0") - workflowExecutionsDao.insert(execution) - execution - } + private def insertExecution(): WorkflowExecutions = + insertWorkflowExecution( + testVersion.getVid, + testUid, + name = "exec-" + uniqueSuffix, + envVersion = "test-env-1.0", + logLocation = Some("") + ) - private def insertDataset(): Dataset = { - val dataset = new Dataset - dataset.setOwnerUid(testUid) - dataset.setName("quota_ds_" + UUID.randomUUID().toString.substring(0, 8)) - dataset.setRepositoryName("repo-" + UUID.randomUUID().toString.substring(0, 8)) - dataset.setIsPublic(false) - dataset.setIsDownloadable(true) - dataset.setDescription("") - dataset.setCreationTime(new Timestamp(System.currentTimeMillis())) - datasetDao.insert(dataset) - dataset - } + private def insertDataset(): Dataset = seedDataset(testUid, "quota_ds_") // ─── getUserCreatedWorkflow ──────────────────────────────────────────────── @@ -376,7 +282,7 @@ class UserQuotaResourceSpec extends AnyFlatSpec with BeforeAndAfterAll with Mock val otherUser = new User otherUser.setUid(testUid + 100000) otherUser.setName("otherUser") - otherUser.setEmail("otherUser-" + UUID.randomUUID().toString.substring(0, 8) + "@example.com") + otherUser.setEmail("otherUser-" + uniqueSuffix + "@example.com") val refused = intercept[WebApplicationException] { resource.deleteCollection(execution.getEid, new SessionUser(otherUser)) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/warehouse/WarehouseResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/warehouse/WarehouseResourceSpec.scala index e71ad3c3e00..accc87e888a 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/warehouse/WarehouseResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/warehouse/WarehouseResourceSpec.scala @@ -21,10 +21,9 @@ package org.apache.texera.web.resource.dashboard.user.warehouse import org.apache.texera.auth.SessionUser import org.apache.texera.common.config.StorageConfig -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.{USER, USER_WAREHOUSE} -import org.apache.texera.dao.jooq.generated.tables.daos.UserDao -import org.apache.texera.dao.jooq.generated.tables.pojos.User +import org.apache.texera.web.resource.dashboard.WarehouseAccountFixture import org.apache.texera.web.resource.dashboard.user.warehouse.WarehouseResource.{ lakekeeperWarehouseName, CreateWarehouseRequest @@ -32,9 +31,6 @@ import org.apache.texera.web.resource.dashboard.user.warehouse.WarehouseResource import org.apache.texera.web.service.LakekeeperClient import org.jooq.{ExecuteContext, ExecuteListener} import org.jooq.impl.{DefaultConfiguration, DefaultExecuteListenerProvider} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import java.util.UUID import javax.ws.rs.{ @@ -52,12 +48,7 @@ import scala.collection.mutable * The feature flag is a constructor dependency, so the two gate states are two resource * instances — no global state is touched, and suites cannot interfere with each other. */ -class WarehouseResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class WarehouseResourceSpec extends DatabaseFlatSpec() { private val createdNames = mutable.Buffer[String]() private val deletedIds = mutable.Buffer[UUID]() @@ -83,27 +74,16 @@ class WarehouseResourceSpec private var sessionUser: SessionUser = _ private var otherUser: SessionUser = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - - val userDao = new UserDao(getDSLContext.configuration()) - val user = new User - user.setName("warehouse_spec_user") - user.setEmail(s"user_${UUID.randomUUID()}@example.com") - userDao.insert(user) - sessionUser = new SessionUser(user) - - val other = new User - other.setName("warehouse_spec_other") - other.setEmail(s"user_${UUID.randomUUID()}@example.com") - other.setAvatar("other-avatar.png") - userDao.insert(other) - otherUser = new SessionUser(other) + override protected def onBeforeAll(): Unit = { + sessionUser = new SessionUser( + WarehouseAccountFixture.seed(getDSLContext, "warehouse_spec_user") + ) + otherUser = new SessionUser( + WarehouseAccountFixture.seed(getDSLContext, "warehouse_spec_other", Some("other-avatar.png")) + ) } - override protected def afterAll(): Unit = closeConnectionPool() - - override protected def beforeEach(): Unit = { + override protected def cleanup(): Unit = { createFailure = None deleteFailure = None createdNames.clear() diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/PublishedCopySchemaSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/PublishedCopySchemaSpec.scala index aebbd2aaf9f..304d34371bb 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/PublishedCopySchemaSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/PublishedCopySchemaSpec.scala @@ -20,14 +20,11 @@ package org.apache.texera.web.resource.dashboard.user.workflow import org.apache.texera.auth.SessionUser -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.enums.{DefaultViewEnum, UserRoleEnum} import org.apache.texera.dao.jooq.generated.tables.daos.{UserDao, WorkflowDao} import org.apache.texera.dao.jooq.generated.tables.pojos.{User, Workflow} import org.jooq.exception.DataAccessException -import org.scalatest.BeforeAndAfterAll -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers import java.time.OffsetDateTime @@ -38,11 +35,7 @@ import java.time.OffsetDateTime * today keeps behaving as it does, a private one can never carry part of a frozen copy, and the two * endpoints that take a whole Workflow from the request body cannot seed one. */ -class PublishedCopySchemaSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with MockTexeraDB { +class PublishedCopySchemaSpec extends DatabaseFlatSpec(cleanupBeforeEach = false) { private var workflowDao: WorkflowDao = _ private var userDao: UserDao = _ @@ -59,15 +52,12 @@ class PublishedCopySchemaSpec user } - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() + override protected def onBeforeAll(): Unit = { workflowDao = new WorkflowDao(getDSLContext.configuration()) userDao = new UserDao(getDSLContext.configuration()) userDao.insert(owner) } - override protected def afterAll(): Unit = shutdownDB() - /** A workflow POJO the resource layer can take, with nothing frozen on it. */ private def newWorkflow(name: String, isPublic: Boolean): Workflow = { val workflow = new Workflow() @@ -85,6 +75,22 @@ class PublishedCopySchemaSpec workflowDao.fetchOneByWid(workflow.getWid) } + private def assertUnpinned(stored: Workflow): Unit = { + stored.getPublishedContent shouldBe null + stored.getPublishedName shouldBe null + stored.getPublishedDescription shouldBe null + stored.getPublishedVersionId shouldBe null + stored.getPublishedDefaultView shouldBe null + } + + private def supplyPublishedCopy(workflow: Workflow): Unit = { + workflow.setPublishedContent("""{"operators":[],"note":"injected"}""") + workflow.setPublishedName("injected_name") + workflow.setPublishedDescription("injected_description") + workflow.setPublishedVersionId(1) + workflow.setPublishedDefaultView(DefaultViewEnum.FORM) + } + behavior of "the published-copy columns" it should "leave every workflow following the author's latest" in { @@ -93,11 +99,7 @@ class PublishedCopySchemaSpec // "following". val stored = insertWorkflow("migration_changes_nothing", isPublic = true) - stored.getPublishedContent shouldBe null - stored.getPublishedName shouldBe null - stored.getPublishedDescription shouldBe null - stored.getPublishedVersionId shouldBe null - stored.getPublishedDefaultView shouldBe null + assertUnpinned(stored) } it should "let a public workflow carry a frozen copy" in { @@ -116,11 +118,7 @@ class PublishedCopySchemaSpec // The columns are part of the generated POJO, and `POST /workflow/create` takes one whole. A // client must not be able to seed a published copy of its own choosing before anything can pin. val workflow = newWorkflow("create_cannot_inject", isPublic = false) - workflow.setPublishedContent("""{"operators":[],"note":"injected"}""") - workflow.setPublishedName("injected_name") - workflow.setPublishedDescription("injected_description") - workflow.setPublishedVersionId(1) - workflow.setPublishedDefaultView(DefaultViewEnum.FORM) + supplyPublishedCopy(workflow) val wid = new WorkflowResource() .createWorkflow(workflow, new SessionUser(owner)) @@ -128,11 +126,7 @@ class PublishedCopySchemaSpec .getWid val stored = workflowDao.fetchOneByWid(wid) - stored.getPublishedContent shouldBe null - stored.getPublishedName shouldBe null - stored.getPublishedDescription shouldBe null - stored.getPublishedVersionId shouldBe null - stored.getPublishedDefaultView shouldBe null + assertUnpinned(stored) } it should "refuse a pinned copy with no default view" in { @@ -184,19 +178,11 @@ class PublishedCopySchemaSpec .getWid val tampered = workflowDao.fetchOneByWid(wid) - tampered.setPublishedContent("""{"operators":[],"note":"injected"}""") - tampered.setPublishedName("injected_name") - tampered.setPublishedDescription("injected_description") - tampered.setPublishedVersionId(1) - tampered.setPublishedDefaultView(DefaultViewEnum.FORM) + supplyPublishedCopy(tampered) new WorkflowResource().persistWorkflow(tampered, new SessionUser(owner)) val stored = workflowDao.fetchOneByWid(wid) - stored.getPublishedContent shouldBe null - stored.getPublishedName shouldBe null - stored.getPublishedDescription shouldBe null - stored.getPublishedVersionId shouldBe null - stored.getPublishedDefaultView shouldBe null + assertUnpinned(stored) } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala index f7e40d9ee1a..4d4470a6a01 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowAccessResourceSpec.scala @@ -49,15 +49,13 @@ class WorkflowAccessResourceSpec extends WorkflowAccessDatabaseSpec(withTargetUs super.beforeEach() workflowAccessResource = new WorkflowAccessResource() - owner = newUser(ownerUid, "owner", "owner@test.com") - userWithWrite = newUser(userWithWriteUid, "user_with_write", "write@test.com") - userWithRead = newUser(userWithReadUid, "user_with_read", "read@test.com") + val (seededOwner, writer, reader) = newAccessUsers() + owner = seededOwner + userWithWrite = writer + userWithRead = reader targetUser = newUser(targetUserUid, "target_user", "target@test.com") val testWorkflow = newWorkflow() - // Clean up before each test - cleanupTestData() - // Insert test data userDao.insert(owner) userDao.insert(userWithWrite) @@ -80,36 +78,29 @@ class WorkflowAccessResourceSpec extends WorkflowAccessDatabaseSpec(withTargetUs .where(WORKFLOW_USER_ACCESS.WID.eq(testWorkflowWid).and(WORKFLOW_USER_ACCESS.UID.eq(uid))) .fetchOne() - "WorkflowAccessResource.revokeAccess" should "successfully revoke access when user has WRITE permission" in { - val sessionUser = new SessionUser(userWithWrite) - - // Verify target user has access before revocation - val accessBefore = accessRow(targetUserUid) - assert(accessBefore != null, "Target user should have access before revocation") - - // Revoke access - workflowAccessResource.revokeAccess(testWorkflowWid, "target@test.com", sessionUser) + private def assertAccessRevoked(caller: User, targetUid: Int, targetEmail: String): Unit = { + assert(accessRow(targetUid) != null, s"$targetEmail should have access before revocation") + workflowAccessResource.revokeAccess(testWorkflowWid, targetEmail, new SessionUser(caller)) + assert(accessRow(targetUid) == null, s"$targetEmail should no longer have access") + } - // Verify access has been revoked - val accessAfter = accessRow(targetUserUid) + private def assertOwnerRevocationRejected(caller: User): Unit = { + val exception = intercept[ForbiddenException] { + workflowAccessResource.revokeAccess( + testWorkflowWid, + "owner@test.com", + new SessionUser(caller) + ) + } + assert(exception.getMessage.contains("owner cannot revoke their own access")) + } - assert(accessAfter == null, "Target user's access should be revoked") + "WorkflowAccessResource.revokeAccess" should "successfully revoke access when user has WRITE permission" in { + assertAccessRevoked(userWithWrite, targetUserUid, "target@test.com") } it should "successfully allow user to revoke their own access" in { - val sessionUser = new SessionUser(userWithRead) - - // Verify user has access before revocation - val accessBefore = accessRow(userWithReadUid) - assert(accessBefore != null, "User should have access before revocation") - - // User revokes their own access - workflowAccessResource.revokeAccess(testWorkflowWid, "read@test.com", sessionUser) - - // Verify access has been revoked - val accessAfter = accessRow(userWithReadUid) - - assert(accessAfter == null, "User's own access should be revoked") + assertAccessRevoked(userWithRead, userWithReadUid, "read@test.com") } it should "throw ForbiddenException when user without WRITE permission tries to revoke others' access" in { @@ -126,29 +117,11 @@ class WorkflowAccessResourceSpec extends WorkflowAccessDatabaseSpec(withTargetUs } it should "throw ForbiddenException when trying to revoke owner's access" in { - val sessionUser = new SessionUser(userWithWrite) - - val exception = intercept[ForbiddenException] { - workflowAccessResource.revokeAccess(testWorkflowWid, "owner@test.com", sessionUser) - } - - assert( - exception.getMessage.contains("owner cannot revoke their own access"), - "Exception message should indicate owner cannot revoke their own access" - ) + assertOwnerRevocationRejected(userWithWrite) } it should "throw ForbiddenException when owner tries to revoke their own access" in { - val sessionUser = new SessionUser(owner) - - val exception = intercept[ForbiddenException] { - workflowAccessResource.revokeAccess(testWorkflowWid, "owner@test.com", sessionUser) - } - - assert( - exception.getMessage.contains("owner cannot revoke their own access"), - "Exception message should indicate owner cannot revoke their own access" - ) + assertOwnerRevocationRejected(owner) } it should "throw BadRequestException when email does not exist" in { @@ -203,7 +176,7 @@ class WorkflowAccessResourceSpec extends WorkflowAccessDatabaseSpec(withTargetUs assert(accessAfterSecond == null, "Target user's access should still be revoked") } - // Always inserts at newGranteeUid (the only extra uid cleanupTestData removes), + // Always inserts at newGranteeUid (the only extra uid the fixture cleanup removes), // so callers can't leak a user row across tests. private def seedUserWithoutAccess(name: String, email: String): User = { val user = newUser(newGranteeUid, name, email) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResourceCoverSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResourceCoverSpec.scala index 1eeb718408e..f1fd5768bf2 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResourceCoverSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResourceCoverSpec.scala @@ -20,35 +20,19 @@ package org.apache.texera.web.resource.dashboard.user.workflow import org.apache.texera.auth.SessionUser -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum -import org.apache.texera.dao.jooq.generated.tables.daos.{ - UserDao, - WorkflowDao, - WorkflowOfUserDao, - WorkflowUserAccessDao -} -import org.apache.texera.dao.jooq.generated.tables.pojos.{ - User, - Workflow, - WorkflowOfUser, - WorkflowUserAccess -} +import org.apache.texera.dao.jooq.generated.tables.daos.UserDao +import org.apache.texera.dao.jooq.generated.tables.pojos.User import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowResource.CoverImageRequest -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} +import org.apache.texera.web.resource.dashboard.DashboardWorkflowFixtureSupport -import java.sql.Timestamp import javax.ws.rs.{BadRequestException, ForbiddenException, NotFoundException} class WorkflowResourceCoverSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { + extends DatabaseFlatSpec(cleanupAfterEach = true) + with DashboardWorkflowFixtureSupport { private val ownerUid = 1000 + scala.util.Random.nextInt(1000) private val readerUid = 2000 + scala.util.Random.nextInt(1000) @@ -62,74 +46,31 @@ class WorkflowResourceCoverSpec private var stranger: User = _ private var userDao: UserDao = _ - private var workflowDao: WorkflowDao = _ - private var workflowOfUserDao: WorkflowOfUserDao = _ - private var workflowUserAccessDao: WorkflowUserAccessDao = _ private var resource: WorkflowResource = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - } - - override protected def afterAll(): Unit = shutdownDB() - - override protected def beforeEach(): Unit = { + override protected def onBeforeEach(): Unit = { userDao = new UserDao(getDSLContext.configuration()) - workflowDao = new WorkflowDao(getDSLContext.configuration()) - workflowOfUserDao = new WorkflowOfUserDao(getDSLContext.configuration()) - workflowUserAccessDao = new WorkflowUserAccessDao(getDSLContext.configuration()) resource = new WorkflowResource() - owner = makeUser(ownerUid, "cover_owner") - reader = makeUser(readerUid, "cover_reader") - stranger = makeUser(strangerUid, "cover_stranger") - - val workflow = new Workflow - workflow.setWid(testWid) - workflow.setName("cover_test_workflow") - workflow.setContent("{}") - workflow.setDescription("desc") - workflow.setIsPublic(false) - workflow.setCreationTime(new Timestamp(System.currentTimeMillis())) - workflow.setLastModifiedTime(new Timestamp(System.currentTimeMillis())) + owner = fixtureUser(ownerUid, "cover_owner") + reader = fixtureUser(readerUid, "cover_reader") + stranger = fixtureUser(strangerUid, "cover_stranger") - cleanupTestData() + val workflow = fixtureWorkflow(testWid, "cover_test_workflow", "desc", isPublic = false) userDao.insert(owner) userDao.insert(reader) userDao.insert(stranger) workflowDao.insert(workflow) - val ownership = new WorkflowOfUser - ownership.setUid(ownerUid) - ownership.setWid(testWid) - workflowOfUserDao.insert(ownership) - - grantAccess(ownerUid, PrivilegeEnum.WRITE) - grantAccess(readerUid, PrivilegeEnum.READ) - } - - override protected def afterEach(): Unit = cleanupTestData() - - private def makeUser(uid: Int, name: String): User = { - val user = new User - user.setUid(uid) - user.setName(name) - user.setEmail(s"$name@test.com") - user - } - - private def grantAccess(uid: Int, privilege: PrivilegeEnum): Unit = { - val access = new WorkflowUserAccess - access.setUid(uid) - access.setWid(testWid) - access.setPrivilege(privilege) - workflowUserAccessDao.insert(access) + insertWorkflowOfUser(ownerUid, testWid) + insertWorkflowUserAccess(ownerUid, testWid, PrivilegeEnum.WRITE) + insertWorkflowUserAccess(readerUid, testWid, PrivilegeEnum.READ) } private def session(user: User): SessionUser = new SessionUser(user) - private def cleanupTestData(): Unit = { + override protected def cleanup(): Unit = { getDSLContext .deleteFrom(WORKFLOW_COVER_IMAGE) .where(WORKFLOW_COVER_IMAGE.WID.eq(testWid)) diff --git a/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala index 311b00b8a60..a76263cd5bb 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/ResultExportServiceSpec.scala @@ -40,7 +40,7 @@ import org.apache.texera.amber.core.virtualidentity.{ import org.apache.texera.amber.core.workflow.{GlobalPortIdentity, PortIdentity} import org.apache.texera.amber.util.ArrowUtils import org.apache.texera.auth.JwtAuth -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.OPERATOR_PORT_EXECUTIONS import org.apache.texera.dao.jooq.generated.tables.pojos.{ User, @@ -51,9 +51,7 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ import org.apache.texera.web.ExecutionDatabaseTestSupport import org.apache.texera.web.model.http.request.result.{OperatorExportInfo, ResultExportRequest} import org.apache.texera.web.model.http.response.result.ResultExportResponse -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, PrivateMethodTester} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.scalatest.PrivateMethodTester import java.io.{ ByteArrayInputStream, @@ -99,12 +97,8 @@ import scala.collection.mutable.ArrayBuffer * bearer token that authenticates the exporting user to the file service. */ class ResultExportServiceSpec - extends AnyFlatSpec - with Matchers + extends DatabaseFlatSpec(cleanupBeforeEach = false, cleanupAfterEach = true) with PrivateMethodTester - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB with ExecutionDatabaseTestSupport { private val service = new ResultExportService(WorkflowIdentity(1L), computingUnitId = 0) @@ -395,8 +389,7 @@ class ResultExportServiceSpec private var testVersion: WorkflowVersion = _ private var testComputingUnit: WorkflowComputingUnit = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() + override protected def onBeforeAll(): Unit = { testUser = insertUser(testUserId, "export_user", "export@example.com") insertWorkflow(testWorkflowWid, "wf-" + UUID.randomUUID().toString.substring(0, 8)) @@ -406,11 +399,9 @@ class ResultExportServiceSpec // Executions are per-test state: several cases below distinguish "no // execution at all" from "an execution with no stored result URI". - override protected def afterEach(): Unit = + override protected def cleanup(): Unit = cleanupExecutionsForVersion(testVersion.getVid, includePortExecutions = true) - override protected def afterAll(): Unit = closeConnectionPool() - // The service under test, bound to the seeded workflow and computing unit so // that getLatestExecutionId resolves against the rows this spec inserts. private def exportService: ResultExportService = diff --git a/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceWarehouseSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceWarehouseSpec.scala index 788190e9f34..49ef40f61ba 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceWarehouseSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceWarehouseSpec.scala @@ -19,14 +19,11 @@ package org.apache.texera.web.service -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.USER_WAREHOUSE import org.apache.texera.dao.jooq.generated.enums.UserWarehouseFlavorEnum -import org.apache.texera.dao.jooq.generated.tables.daos.UserDao -import org.apache.texera.dao.jooq.generated.tables.pojos.User -import org.scalatest.BeforeAndAfterAll -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers + +import org.apache.texera.web.resource.dashboard.WarehouseAccountFixture import java.util.UUID @@ -34,31 +31,15 @@ import java.util.UUID * Spec for [[WorkflowService.resolveLakekeeperWarehouseName]] (#6932): the ownership check and the * never-silently-fall-back rule for an execution's chosen warehouse. */ -class WorkflowServiceWarehouseSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with MockTexeraDB { +class WorkflowServiceWarehouseSpec extends DatabaseFlatSpec(cleanupBeforeEach = false) { private var ownerUid: Integer = _ private var intruderUid: Integer = _ private var whid: Integer = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - - val userDao = new UserDao(getDSLContext.configuration()) - val owner = new User - owner.setName("resolve_spec_owner") - owner.setEmail(s"user_${UUID.randomUUID()}@example.com") - userDao.insert(owner) - ownerUid = owner.getUid - - val intruder = new User - intruder.setName("resolve_spec_intruder") - intruder.setEmail(s"user_${UUID.randomUUID()}@example.com") - userDao.insert(intruder) - intruderUid = intruder.getUid + override protected def onBeforeAll(): Unit = { + ownerUid = WarehouseAccountFixture.seed(getDSLContext, "resolve_spec_owner").getUid + intruderUid = WarehouseAccountFixture.seed(getDSLContext, "resolve_spec_intruder").getUid val row = getDSLContext.newRecord(USER_WAREHOUSE) row.setUid(ownerUid) @@ -70,8 +51,6 @@ class WorkflowServiceWarehouseSpec whid = row.getWhid } - override protected def afterAll(): Unit = closeConnectionPool() - "resolveLakekeeperWarehouseName" should "require a pick while warehouses are enabled" in { // A run must name the warehouse it writes into, the same way it names a computing // unit; falling back to the shared default would route a caller that forgot to pick diff --git a/common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala b/common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala index 3b950fc7b6a..712c6c47d96 100644 --- a/common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala +++ b/common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala @@ -34,16 +34,9 @@ class WorkflowAccessSpec extends WorkflowAccessDatabaseSpec(withTargetUser = fal val workflowDao = new WorkflowDao(getDSLContext.configuration()) super.beforeEach() - cleanupTestData() - // The workflow's owner, a WRITE grantee and a READ grantee. - Seq( - (ownerUid, "owner", "owner@test.com"), - (userWithWriteUid, "user_with_write", "write@test.com"), - (userWithReadUid, "user_with_read", "read@test.com") - ).foreach { - case (uid, name, email) => userDao.insert(newUser(uid, name, email)) - } + val (owner, writer, reader) = newAccessUsers() + List(owner, writer, reader).foreach(userDao.insert(_)) workflowDao.insert(newWorkflow()) seedOwnerAndGrantees() diff --git a/common/dao/src/test/scala/org/apache/texera/dao/DatabaseFlatSpec.scala b/common/dao/src/test/scala/org/apache/texera/dao/DatabaseFlatSpec.scala new file mode 100644 index 00000000000..17a28fec71d --- /dev/null +++ b/common/dao/src/test/scala/org/apache/texera/dao/DatabaseFlatSpec.scala @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.texera.dao + +import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +/** Shared ScalaTest FlatSpec base managing [[MockTexeraDB]] suite initialization and cleanup hooks. */ +abstract class DatabaseFlatSpec( + private val cleanupBeforeEach: Boolean = true, + private val cleanupAfterEach: Boolean = false, + private val cleanupAfterAll: Boolean = false +) extends AnyFlatSpec + with Matchers + with BeforeAndAfterAll + with BeforeAndAfterEach + with MockTexeraDB { + + protected def onBeforeAll(): Unit = () + protected def onBeforeEach(): Unit = () + protected def onAfterAll(): Unit = () + protected def cleanup(): Unit = () + + override protected def beforeAll(): Unit = { + super.beforeAll() + initializeDBAndReplaceDSLContext() + onBeforeAll() + } + + override protected def afterAll(): Unit = { + try { + if (cleanupAfterAll) cleanup() + onAfterAll() + } finally { + try closeConnectionPool() + finally super.afterAll() + } + } + + override protected def beforeEach(): Unit = { + super.beforeEach() + if (cleanupBeforeEach) cleanup() + onBeforeEach() + } + + override protected def afterEach(): Unit = { + try { + if (cleanupAfterEach) cleanup() + } finally super.afterEach() + } +} diff --git a/common/dao/src/test/scala/org/apache/texera/dao/WorkflowAccessDatabaseSpec.scala b/common/dao/src/test/scala/org/apache/texera/dao/WorkflowAccessDatabaseSpec.scala index 7e8d0f650f8..36c6f52b55f 100644 --- a/common/dao/src/test/scala/org/apache/texera/dao/WorkflowAccessDatabaseSpec.scala +++ b/common/dao/src/test/scala/org/apache/texera/dao/WorkflowAccessDatabaseSpec.scala @@ -28,16 +28,11 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ WorkflowOfUser, WorkflowUserAccess } -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import java.sql.Timestamp abstract class WorkflowAccessDatabaseSpec(withTargetUser: Boolean) - extends AnyFlatSpec - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { + extends DatabaseFlatSpec(cleanupAfterEach = true) { protected val ownerUid = 1000 + scala.util.Random.nextInt(1000) protected val userWithWriteUid = 2000 + scala.util.Random.nextInt(1000) @@ -49,11 +44,7 @@ abstract class WorkflowAccessDatabaseSpec(withTargetUser: Boolean) protected var workflowOfUserDao: WorkflowOfUserDao = _ protected var workflowUserAccessDao: WorkflowUserAccessDao = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - } - - override protected def beforeEach(): Unit = { + override protected def onBeforeEach(): Unit = { workflowOfUserDao = new WorkflowOfUserDao(getDSLContext.configuration()) workflowUserAccessDao = new WorkflowUserAccessDao(getDSLContext.configuration()) } @@ -66,6 +57,13 @@ abstract class WorkflowAccessDatabaseSpec(withTargetUser: Boolean) user } + protected def newAccessUsers(): (User, User, User) = + ( + newUser(ownerUid, "owner", "owner@test.com"), + newUser(userWithWriteUid, "user_with_write", "write@test.com"), + newUser(userWithReadUid, "user_with_read", "read@test.com") + ) + protected def newWorkflow(): Workflow = { val workflow = new Workflow workflow.setWid(testWorkflowWid) @@ -87,11 +85,7 @@ abstract class WorkflowAccessDatabaseSpec(withTargetUser: Boolean) ) } - override protected def afterEach(): Unit = { - cleanupTestData() - } - - protected def cleanupTestData(): Unit = { + override protected def cleanup(): Unit = { getDSLContext .deleteFrom(WORKFLOW_USER_ACCESS) .where(WORKFLOW_USER_ACCESS.WID.eq(testWorkflowWid)) @@ -114,8 +108,4 @@ abstract class WorkflowAccessDatabaseSpec(withTargetUser: Boolean) .where(USER.UID.in(userIds.map(Int.box): _*)) .execute() } - - override protected def afterAll(): Unit = { - closeConnectionPool() - } } diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala index ac54678391f..fffea257496 100644 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala @@ -27,7 +27,7 @@ import org.apache.texera.amber.core.virtualidentity.{ } import org.apache.texera.amber.core.workflow.{GlobalPortIdentity, PortIdentity} import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde.SerdeOps -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables._ import org.apache.texera.dao.jooq.generated.tables.daos.{ UserDao, @@ -41,30 +41,19 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ WorkflowExecutions, WorkflowVersion } -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import java.net.URI import java.sql.Timestamp import java.util.UUID -class ExecutionResultUrisSpec - extends AnyFlatSpec - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class ExecutionResultUrisSpec extends DatabaseFlatSpec(cleanupAfterEach = true) { private val testWorkflowWid = 3000 + scala.util.Random.nextInt(1000) private val testUserId = 1000 + scala.util.Random.nextInt(1000) private var testVersion: WorkflowVersion = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - } - - override protected def beforeEach(): Unit = { - cleanupTestData() + override protected def onBeforeEach(): Unit = { val testUser = new User testUser.setUid(testUserId) @@ -87,16 +76,8 @@ class ExecutionResultUrisSpec new WorkflowVersionDao(getDSLContext.configuration()).insert(testVersion) } - override protected def afterEach(): Unit = { - cleanupTestData() - } - - override protected def afterAll(): Unit = { - closeConnectionPool() - } - // Child rows before parents: port results, executions, versions, the workflow, the user. - private def cleanupTestData(): Unit = { + override protected def cleanup(): Unit = { val vids = getDSLContext .select(WORKFLOW_VERSION.VID) .from(WORKFLOW_VERSION) diff --git a/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala b/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala index 9810f4d92f8..cc3e5b3851b 100644 --- a/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala +++ b/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala @@ -45,7 +45,7 @@ import org.apache.texera.amber.core.virtualidentity.{ import org.apache.texera.amber.core.workflow.{GlobalPortIdentity, PortIdentity} import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde.SerdeOps import org.apache.texera.auth.{JwtAuth, JwtAuthFilter, SessionUser, UnauthorizedExceptionMapper} -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.{OPERATOR_PORT_EXECUTIONS, WORKFLOW_EXECUTIONS} import org.apache.texera.dao.jooq.generated.enums.{ OutputModeEnum, @@ -76,9 +76,6 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ WorkflowVersion } import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import java.net.URI import java.sql.Timestamp @@ -88,12 +85,7 @@ import java.util.Locale * Sends requests through the Jersey pipeline production uses, against an embedded database and * real Iceberg tables in a local Hadoop catalog, the way WorkflowCore's storage specs read them. */ -class ResultResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class ResultResourceSpec extends DatabaseFlatSpec() { private val Running: Short = 1 private val Completed: Short = 3 @@ -109,6 +101,7 @@ class ResultResourceSpec Tuple.builder(schema).addSequentially(Array[Any](id, s"first-$id", s"last-$id")).build() private val rows: Seq[Tuple] = (0 until 25).map(tuple) + private val twoPorts = Seq(0 -> rows, 1 -> (100 until 125).map(tuple)) // Mirror production's mapper: ResultService registers DefaultScalaModule on Dropwizard's. private val mapper: ObjectMapper = Jackson.newObjectMapper().registerModule(DefaultScalaModule) @@ -145,8 +138,7 @@ class ResultResourceSpec private var vid: Integer = _ private var unit: Integer = _ - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() + override protected def onBeforeAll(): Unit = { LocalHadoopIcebergCatalog.ensure() resources.before() @@ -195,12 +187,9 @@ class ResultResourceSpec vid = version.getVid } - override protected def afterAll(): Unit = { - resources.after() - shutdownDB() - } + override protected def onAfterAll(): Unit = resources.after() - override protected def beforeEach(): Unit = { + override protected def cleanup(): Unit = { getDSLContext.deleteFrom(OPERATOR_PORT_EXECUTIONS).execute() getDSLContext.deleteFrom(WORKFLOW_EXECUTIONS).execute() } @@ -294,6 +283,16 @@ class ResultResourceSpec uri } + private def executionWithResults( + startedBy: User = owner, + on: Option[Integer] = Some(unit), + ports: Seq[(Int, Seq[Tuple])] = Seq(0 -> rows) + ): Integer = { + val eid = insertExecution(startedBy, on = on) + ports.foreach { case (port, data) => storeResult(eid, port = port, data = data) } + eid + } + private def write(document: VirtualDocument[_], data: Seq[Tuple], writerId: String): Unit = { val writer = document.writer(writerId).asInstanceOf[BufferedItemWriter[Tuple]] writer.open() @@ -323,6 +322,11 @@ class ResultResourceSpec private def readPaths(eid: Integer) = Seq(resultsPath(eid), pagesPath(eid), statisticsPath(eid)) + private def assertReadStatus(eid: Integer, status: Int, callers: User*): Unit = + for (caller <- callers; path <- readPaths(eid)) { + withClue(s"${caller.getName} on $path")(get(caller, path).getStatus shouldBe status) + } + private def columnNames(page: JsonNode): List[String] = (0 until page.get("schema").size).toList .map(page.get("schema").get(_).get("attributeName").asText) @@ -352,20 +356,16 @@ class ResultResourceSpec "Reading an execution" should "be allowed for the user who started it" in { // The public viewer started this one, so its results are theirs despite holding no grant. - val eid = insertExecution(publicViewer) - storeResult(eid) + val eid = executionWithResults(publicViewer) - readPaths(eid).foreach(path => withClue(path)(get(publicViewer, path).getStatus shouldBe 200)) + assertReadStatus(eid, 200, publicViewer) } it should "be allowed for anyone who can use the computing unit it ran on" in { - val eid = insertExecution(publicViewer) - storeResult(eid) + val eid = executionWithResults(publicViewer) // The unit's owner, and a user the unit was shared with who holds nothing on the workflow. - for (caller <- Seq(owner, unitSharer); path <- readPaths(eid)) { - withClue(s"${caller.getName} on $path")(get(caller, path).getStatus shouldBe 200) - } + assertReadStatus(eid, 200, owner, unitSharer) } it should "be refused for a user who only has the workflow, granted or public" in { @@ -373,14 +373,11 @@ class ResultResourceSpec // No table is stored, so a refusal that came after reading it would be a 404. insertResult(eid) - for (caller <- Seq(grantee, publicViewer); path <- readPaths(eid)) { - withClue(s"${caller.getName} on $path")(get(caller, path).getStatus shouldBe 403) - } + assertReadStatus(eid, 403, grantee, publicViewer) } it should "be refused to all but its starter when no computing unit was recorded" in { - val eid = insertExecution(owner, on = None) - storeResult(eid) + val eid = executionWithResults(on = None) readPaths(eid).foreach { path => withClue(path) { @@ -391,9 +388,7 @@ class ResultResourceSpec } it should "give an execution that does not exist the same refusal" in { - readPaths(Integer.MAX_VALUE).foreach { path => - withClue(path)(get(owner, path).getStatus shouldBe 403) - } + assertReadStatus(Integer.MAX_VALUE, 403, owner) } it should "be refused without a token" in { @@ -445,8 +440,7 @@ class ResultResourceSpec } "GET a page" should "return the requested rows with the schema and the full row count" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() val page = getJson(owner, pagesPath(eid), "pageIndex" -> 2, "pageSize" -> 10) @@ -465,9 +459,7 @@ class ResultResourceSpec } it should "default to the first ten rows of port 0" in { - val eid = insertExecution(owner) - storeResult(eid) - storeResult(eid, port = 1, data = (100 until 125).map(tuple)) + val eid = executionWithResults(ports = twoPorts) val page = getJson(owner, pagesPath(eid)) @@ -476,23 +468,19 @@ class ResultResourceSpec } it should "read the port it is asked for" in { - val eid = insertExecution(owner) - storeResult(eid) - storeResult(eid, port = 1, data = (100 until 125).map(tuple)) + val eid = executionWithResults(ports = twoPorts) getJson(owner, pagesPath(eid), "port" -> 1).get("table").get(0).get("id").asInt shouldBe 100 } it should "stop at the end of the result" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() getJson(owner, pagesPath(eid), "pageIndex" -> 3, "pageSize" -> 10).get("table").size shouldBe 5 } it should "keep the schema on a page past the end" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() val page = getJson(owner, pagesPath(eid), "pageIndex" -> 9, "pageSize" -> 10) @@ -502,8 +490,7 @@ class ResultResourceSpec } it should "apply the column offset and limit" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() // With the limit left at its default too: offset plus limit does not fit in an Int. columnNames(getJson(owner, pagesPath(eid), "columnOffset" -> 1)) shouldBe @@ -514,8 +501,7 @@ class ResultResourceSpec } it should "search the columns ignoring case, before the offset and limit" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() columnNames(getJson(owner, pagesPath(eid), "columnSearch" -> "NAME")) shouldBe List("first_name", "Last_Name") @@ -528,8 +514,7 @@ class ResultResourceSpec } it should "search the columns the same way in any locale" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() val default = Locale.getDefault // By Turkish rules "ID" lowercases to "ıd", with a dotless i, which misses "id". Locale.setDefault(Locale.forLanguageTag("tr")) @@ -570,8 +555,7 @@ class ResultResourceSpec } it should "accept the largest page size" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() getJson(owner, pagesPath(eid), "pageSize" -> 1000).get("table").size shouldBe 25 } @@ -617,22 +601,19 @@ class ResultResourceSpec get(owner, pagesPath(eid)).getStatus shouldBe 500 } - it should "answer 500, not 404, when the catalog is unavailable" in { - val eid = insertExecution(owner) - storeResult(eid) - - withFailingCatalog(succeeding = 0) { + private def assertUnavailableResult(succeedingLoads: Int): Unit = { + val eid = executionWithResults() + withFailingCatalog(succeeding = succeedingLoads) { get(owner, pagesPath(eid)).getStatus shouldBe 500 } } - it should "answer 500, not an empty page, when the catalog fails after opening the result" in { - val eid = insertExecution(owner) - storeResult(eid) + it should "answer 500, not 404, when the catalog is unavailable" in { + assertUnavailableResult(succeedingLoads = 0) + } - withFailingCatalog(succeeding = 1) { - get(owner, pagesPath(eid)).getStatus shouldBe 500 - } + it should "answer 500, not an empty page, when the catalog fails after opening the result" in { + assertUnavailableResult(succeedingLoads = 1) } it should "answer 503 for a result in a warehouse it cannot read" in { @@ -647,8 +628,7 @@ class ResultResourceSpec } "GET statistics" should "return the table's per-column statistics" in { - val eid = insertExecution(owner) - storeResult(eid) + val eid = executionWithResults() getJson(owner, statisticsPath(eid)) shouldBe mapper.readTree( """{