diff --git a/amber/src/test/scala/org/apache/texera/web/resource/EmailTemplateSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/EmailTemplateSpec.scala index 1651e3a23d0..1d54e2f52f5 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/EmailTemplateSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/EmailTemplateSpec.scala @@ -31,17 +31,30 @@ class EmailTemplateSpec extends AnyFlatSpec with Matchers { // Cases that require the suffix-present branch would need a JVM-level // env override before EmailTemplate loads — out of scope here. + private def registrationForAdmin( + userEmail: Option[String], + userName: Option[String], + affiliation: Option[String], + reason: Option[String] + ): EmailMessage = + EmailTemplate.userRegistrationNotification( + "admin@example.com", + userEmail, + userName, + affiliation, + reason, + toAdmin = true + ) + // -- userRegistrationNotification (admin branch) ---------------------------- "userRegistrationNotification(toAdmin = true)" should "produce a subject and receiver and include the requesting user's email" in { - val msg = EmailTemplate.userRegistrationNotification( - receiverEmail = "admin@example.com", + val msg = registrationForAdmin( userEmail = Some("alice@example.com"), userName = Some("Alice Example"), affiliation = Some("UC Irvine"), - reason = Some("research"), - toAdmin = true + reason = Some("research") ) msg.receiver shouldBe "admin@example.com" msg.subject should startWith("New Account Request Pending Approval") @@ -53,43 +66,25 @@ class EmailTemplateSpec extends AnyFlatSpec with Matchers { } it should "fall back to 'Unknown' when userEmail is None" in { - val msg = EmailTemplate.userRegistrationNotification( - receiverEmail = "admin@example.com", + val msg = registrationForAdmin( userEmail = None, userName = None, affiliation = Some("UC Irvine"), - reason = Some("research"), - toAdmin = true + reason = Some("research") ) msg.content should include("Email: Unknown") } it should "render 'Not provided' for name, affiliation, and reason when blank" in { - val withNone = EmailTemplate.userRegistrationNotification( - receiverEmail = "admin@example.com", - userEmail = Some("alice@example.com"), - userName = None, - affiliation = None, - reason = None, - toAdmin = true - ) - withNone.content should include("Affiliation: Not provided") - withNone.content should include("Reason: Not provided") - withNone.content should include("Name: Not provided") - - val withBlank = EmailTemplate.userRegistrationNotification( - receiverEmail = "admin@example.com", - userEmail = Some("alice@example.com"), - userName = Some(" "), - affiliation = Some(" "), - reason = Some(""), - toAdmin = true - ) // The `.filter(_.trim.nonEmpty)` guard treats whitespace-only and empty // strings the same as None. - withBlank.content should include("Affiliation: Not provided") - withBlank.content should include("Reason: Not provided") - withBlank.content should include("Name: Not provided") + Seq((None, None, None), (Some(" "), Some(" "), Some(""))).foreach { + case (userName, affiliation, reason) => + val msg = registrationForAdmin(Some("alice@example.com"), userName, affiliation, reason) + msg.content should include("Affiliation: Not provided") + msg.content should include("Reason: Not provided") + msg.content should include("Name: Not provided") + } } // -- userRegistrationNotification (user branch) ----------------------------- diff --git a/amber/src/test/scala/org/apache/texera/web/resource/FeedbackResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/FeedbackResourceSpec.scala index d18387ee8ce..716ae85a71c 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/FeedbackResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/FeedbackResourceSpec.scala @@ -20,24 +20,17 @@ package org.apache.texera.web.resource 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.FEEDBACK 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.apache.texera.web.resource.FeedbackResource.SubmitFeedbackRequest -import org.scalatest.BeforeAndAfterAll -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers import java.util.UUID import javax.ws.rs.BadRequestException -class FeedbackResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with MockTexeraDB { +class FeedbackResourceSpec extends DatabaseFlatSpec() { private val testUid = 9000 + scala.util.Random.nextInt(1000) private val otherUid = testUid + 1 @@ -54,8 +47,7 @@ class FeedbackResourceSpec user } - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() + override protected def onBeforeAll(): Unit = { val userDao = new UserDao(getDSLContext.configuration()) val testUser = makeUser(testUid, "feedback_spec_user") val otherUser = makeUser(otherUid, "feedback_spec_other_user") @@ -65,15 +57,14 @@ class FeedbackResourceSpec otherSessionUser = new SessionUser(otherUser) } - override protected def afterAll(): Unit = closeConnectionPool() - - private def clearFeedback(): Unit = { + override protected def cleanup(): Unit = getDSLContext.deleteFrom(FEEDBACK).execute() - } + + private def submit(message: String, caller: SessionUser = sessionUser): Unit = + resource.submitFeedback(SubmitFeedbackRequest(message), caller) "FeedbackResource" should "persist a submitted feedback and return it for the same user" in { - clearFeedback() - resource.submitFeedback(SubmitFeedbackRequest("the editor is great"), sessionUser) + submit("the editor is great") val feedback = resource.listMyFeedback(sessionUser) feedback should have size 1 @@ -84,51 +75,45 @@ class FeedbackResourceSpec } it should "return feedback newest first" in { - clearFeedback() - resource.submitFeedback(SubmitFeedbackRequest("first message"), sessionUser) + submit("first message") Thread.sleep(1000) // creation_time has 1-second resolution - resource.submitFeedback(SubmitFeedbackRequest("second message"), sessionUser) + submit("second message") val messages = resource.listMyFeedback(sessionUser).map(_.message) messages shouldBe List("second message", "first message") } it should "trim surrounding whitespace from the feedback message" in { - clearFeedback() - resource.submitFeedback(SubmitFeedbackRequest(" padded message "), sessionUser) + submit(" padded message ") resource.listMyFeedback(sessionUser).head.message shouldBe "padded message" } it should "reject an empty or whitespace-only feedback message" in { - clearFeedback() an[BadRequestException] should be thrownBy - resource.submitFeedback(SubmitFeedbackRequest(" "), sessionUser) + submit(" ") an[BadRequestException] should be thrownBy - resource.submitFeedback(SubmitFeedbackRequest(""), sessionUser) + submit("") resource.listMyFeedback(sessionUser) shouldBe empty } it should "reject a null message body" in { - clearFeedback() an[BadRequestException] should be thrownBy - resource.submitFeedback(SubmitFeedbackRequest(null), sessionUser) + submit(null) } it should "isolate feedback between users" in { - clearFeedback() - resource.submitFeedback(SubmitFeedbackRequest("from test user"), sessionUser) - resource.submitFeedback(SubmitFeedbackRequest("from other user a"), otherSessionUser) - resource.submitFeedback(SubmitFeedbackRequest("from other user b"), otherSessionUser) + submit("from test user") + submit("from other user a", otherSessionUser) + submit("from other user b", otherSessionUser) resource.listMyFeedback(sessionUser).map(_.message) shouldBe List("from test user") resource.listMyFeedback(otherSessionUser) should have size 2 } "feedbackCounts" should "report per-user counts only for users with feedback" in { - clearFeedback() - resource.submitFeedback(SubmitFeedbackRequest("a"), sessionUser) - resource.submitFeedback(SubmitFeedbackRequest("b"), sessionUser) - resource.submitFeedback(SubmitFeedbackRequest("c"), otherSessionUser) + submit("a") + submit("b") + submit("c", otherSessionUser) val counts = resource.feedbackCounts().map(c => c.uid.intValue() -> c.count.intValue()).toMap counts(testUid) shouldBe 2 @@ -136,14 +121,12 @@ class FeedbackResourceSpec } it should "return an empty list when nobody has submitted feedback" in { - clearFeedback() resource.feedbackCounts() shouldBe empty } "listUserFeedback" should "return a specific user's feedback for admins" in { - clearFeedback() - resource.submitFeedback(SubmitFeedbackRequest("target user feedback"), otherSessionUser) - resource.submitFeedback(SubmitFeedbackRequest("noise"), sessionUser) + submit("target user feedback", otherSessionUser) + submit("noise") val feedback = resource.listUserFeedback(otherUid) feedback.map(_.message) shouldBe List("target user feedback") diff --git a/amber/src/test/scala/org/apache/texera/web/resource/GmailResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/GmailResourceSpec.scala index 036532df6a4..351765a6287 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/GmailResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/GmailResourceSpec.scala @@ -24,26 +24,21 @@ import ch.qos.logback.classic.{Level, Logger => LogbackLogger} import ch.qos.logback.core.read.ListAppender import org.apache.texera.auth.SessionUser import org.apache.texera.common.config.UserSystemConfig -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 org.slf4j.LoggerFactory import java.util.UUID import javax.ws.rs.{BadRequestException, ForbiddenException, WebApplicationException} import scala.jdk.CollectionConverters._ -class GmailResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class GmailResourceSpec extends DatabaseFlatSpec(cleanupAfterEach = true) { + + private def messageFor(receiver: String): EmailMessage = + EmailMessage(receiver = receiver, subject = "subj", content = "body") private def newSessionUser(): SessionUser = { val user = new User @@ -56,11 +51,7 @@ class GmailResourceSpec it should "throw BadRequestException (HTTP 400) when the receiver fails email-format validation" in { val resource = new GmailResource() - val msg = EmailMessage( - receiver = "not-a-valid-email", - subject = "subj", - content = "body" - ) + val msg = messageFor("not-a-valid-email") val ex = intercept[BadRequestException] { resource.sendEmailRequest(msg, newSessionUser()) } @@ -74,11 +65,7 @@ class GmailResourceSpec // server contact — and `sendEmail` returns `Left("Failed to send email: // ...")`. The resource then maps that `Left` to a 502 BadGateway. val resource = new GmailResource() - val msg = EmailMessage( - receiver = "valid@example.com", - subject = "subj", - content = "body" - ) + val msg = messageFor("valid@example.com") val ex = intercept[WebApplicationException] { resource.sendEmailRequest(msg, newSessionUser()) } @@ -115,11 +102,7 @@ class GmailResourceSpec // keep this green with the fallback deleted — but as production stands it is a genuine // change-detector, and sendEmailRequest returns Unit so there is no seam for a direct assertion. val resource = new GmailResource() - val msg = EmailMessage( - receiver = "", - subject = "subj", - content = "body" - ) + val msg = messageFor("") val ex = intercept[WebApplicationException] { resource.sendEmailRequest(msg, newSessionUser()) } @@ -134,7 +117,7 @@ class GmailResourceSpec "sendEmail" should "reject malformed recipient addresses before attempting delivery" in { requireNoRealGmailSender() - val msg = EmailMessage(receiver = "unused@example.com", subject = "subj", content = "body") + val msg = messageFor("unused@example.com") val malformed = Seq( null, // the `email != null` short-circuit: the regex would NPE on its own "plainaddress", // no '@' at all @@ -155,7 +138,7 @@ class GmailResourceSpec // Distinguishes the two Left kinds: this one comes from the Try around createMimeMessage // (empty sender ⇒ AddressException), i.e. the guard let the address through. Without it the // test above could stay green under a regex that rejects everything. - val msg = EmailMessage(receiver = "unused@example.com", subject = "subj", content = "body") + val msg = messageFor("unused@example.com") GmailResource.sendEmail(msg, "ok@example.com") match { case Left(error) => error should startWith("Failed to send email:") case Right(_) => @@ -170,19 +153,11 @@ class GmailResourceSpec private val runId = UUID.randomUUID().toString.substring(0, 8) private var userDao: UserDao = _ - 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()) - cleanup() - } - - override protected def afterEach(): Unit = cleanup() // startsWith escapes SQL LIKE wildcards, so the literal "gmailspec_" prefix is matched exactly. - private def cleanup(): Unit = + override protected def cleanup(): Unit = getDSLContext.deleteFrom(USER).where(USER.NAME.startsWith("gmailspec_")).execute() /** @@ -291,11 +266,7 @@ class GmailResourceSpec // runs to completion instead of throwing — the admin fan-out finds nothing and the applicant // acknowledgement returns a Left that the method discards — so `intercept` fails. val resource = new GmailResource() - val msg = EmailMessage( - receiver = "not-a-valid-email", - subject = "subj", - content = "body" - ) + val msg = messageFor("not-a-valid-email") val ex = intercept[ForbiddenException] { resource.notifyUnauthorizedUser(msg) } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/UserConfigResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/UserConfigResourceSpec.scala index 1fd49ab3992..aaf0042f6f0 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/UserConfigResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/UserConfigResourceSpec.scala @@ -20,133 +20,121 @@ package org.apache.texera.web.resource 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.{USER, USER_CONFIG} import org.apache.texera.dao.jooq.generated.tables.daos.UserDao import org.apache.texera.dao.jooq.generated.tables.pojos.User -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} -import org.scalatest.flatspec.AnyFlatSpec import javax.ws.rs.BadRequestException -class UserConfigResourceSpec - extends AnyFlatSpec - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class UserConfigResourceSpec extends DatabaseFlatSpec() { private val testUid = 4000 + scala.util.Random.nextInt(1000) private val otherUid = testUid + 1 private var userDao: UserDao = _ - private var testUser: User = _ - private var otherUser: User = _ + private var testUser: SessionUser = _ + private var otherUser: SessionUser = _ private val resource = new UserConfigResource - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() + override protected def onBeforeAll(): Unit = userDao = new UserDao(getDSLContext.configuration()) - } - - override protected def afterAll(): Unit = shutdownDB() // Every test starts from a clean slate for the ids under test, then seeds only // the two users it needs, so tests are order-independent. - override protected def beforeEach(): Unit = resetFixtures() - - private def resetFixtures(): Unit = { + override protected def cleanup(): Unit = { getDSLContext.deleteFrom(USER_CONFIG).where(USER_CONFIG.UID.in(testUid, otherUid)).execute() getDSLContext.deleteFrom(USER).where(USER.UID.in(testUid, otherUid)).execute() + } - testUser = newUser(testUid, "config_user", "config@example.com") - otherUser = newUser(otherUid, "other_user", "other@example.com") + override protected def onBeforeEach(): Unit = { + testUser = seedSession(testUid, "config_user", "config@example.com") + otherUser = seedSession(otherUid, "other_user", "other@example.com") } - private def newUser(uid: Int, name: String, email: String): User = { + private def seedSession(uid: Int, name: String, email: String): SessionUser = { val user = new User user.setUid(uid) user.setName(name) user.setEmail(email) userDao.insert(user) - user + new SessionUser(user) } - private def session(user: User): SessionUser = new SessionUser(user) - // ─── getEntry / setEntry ─────────────────────────────────────────────────── "getEntry" should "return null for a key that was never set" in { - assert(resource.getEntry("missing", session(testUser)) == null) + assert(resource.getEntry("missing", testUser) == null) } "setEntry" should "store a value that getEntry then returns" in { - resource.setEntry("theme", "dark", session(testUser)) - assert(resource.getEntry("theme", session(testUser)) == "dark") + resource.setEntry("theme", "dark", testUser) + assert(resource.getEntry("theme", testUser) == "dark") } it should "overwrite the value when the same key is set again" in { - resource.setEntry("theme", "dark", session(testUser)) - resource.setEntry("theme", "light", session(testUser)) - assert(resource.getEntry("theme", session(testUser)) == "light") + resource.setEntry("theme", "dark", testUser) + resource.setEntry("theme", "light", testUser) + assert(resource.getEntry("theme", testUser) == "light") // still a single entry, not two - assert(resource.getAllDict(session(testUser)).size == 1) + assert(resource.getAllDict(testUser).size == 1) } // ─── getAllDict ──────────────────────────────────────────────────────────── "getAllDict" should "return an empty map when the user has no entries" in { - assert(resource.getAllDict(session(testUser)).isEmpty) + assert(resource.getAllDict(testUser).isEmpty) } it should "return every key/value pair the user has set" in { - resource.setEntry("a", "1", session(testUser)) - resource.setEntry("b", "2", session(testUser)) - resource.setEntry("c", "3", session(testUser)) + resource.setEntry("a", "1", testUser) + resource.setEntry("b", "2", testUser) + resource.setEntry("c", "3", testUser) - val dict = resource.getAllDict(session(testUser)) + val dict = resource.getAllDict(testUser) assert(dict == Map("a" -> "1", "b" -> "2", "c" -> "3")) } it should "be scoped to the requesting user (another user's entries are not returned)" in { - resource.setEntry("shared", "mine", session(testUser)) - resource.setEntry("shared", "theirs", session(otherUser)) - resource.setEntry("other-only", "x", session(otherUser)) + resource.setEntry("shared", "mine", testUser) + resource.setEntry("shared", "theirs", otherUser) + resource.setEntry("other-only", "x", otherUser) - assert(resource.getAllDict(session(testUser)) == Map("shared" -> "mine")) - assert(resource.getEntry("other-only", session(testUser)) == null) + assert(resource.getAllDict(testUser) == Map("shared" -> "mine")) + assert(resource.getEntry("other-only", testUser) == null) assert( - resource.getAllDict(session(otherUser)) == Map("shared" -> "theirs", "other-only" -> "x") + resource.getAllDict(otherUser) == Map("shared" -> "theirs", "other-only" -> "x") ) } // ─── deleteEntry ─────────────────────────────────────────────────────────── "deleteEntry" should "remove the key so getEntry and getAllDict no longer show it" in { - resource.setEntry("k1", "v1", session(testUser)) - resource.setEntry("k2", "v2", session(testUser)) + resource.setEntry("k1", "v1", testUser) + resource.setEntry("k2", "v2", testUser) - resource.deleteEntry("k1", session(testUser)) + resource.deleteEntry("k1", testUser) - assert(resource.getEntry("k1", session(testUser)) == null) - assert(resource.getAllDict(session(testUser)) == Map("k2" -> "v2")) + assert(resource.getEntry("k1", testUser) == null) + assert(resource.getAllDict(testUser) == Map("k2" -> "v2")) } it should "be a no-op (no error) when the key does not exist" in { - resource.deleteEntry("never-set", session(testUser)) - assert(resource.getAllDict(session(testUser)).isEmpty) + resource.deleteEntry("never-set", testUser) + assert(resource.getAllDict(testUser).isEmpty) } // ─── key validation ──────────────────────────────────────────────────────── "getEntry" should "reject a blank key with a BadRequestException" in { - assertThrows[BadRequestException](resource.getEntry(" ", session(testUser))) + assertThrows[BadRequestException](resource.getEntry(" ", testUser)) } "setEntry" should "reject a blank key with a BadRequestException" in { - assertThrows[BadRequestException](resource.setEntry("", "v", session(testUser))) + assertThrows[BadRequestException](resource.setEntry("", "v", testUser)) } "deleteEntry" should "reject a blank key with a BadRequestException" in { - assertThrows[BadRequestException](resource.deleteEntry("", session(testUser))) + assertThrows[BadRequestException](resource.deleteEntry("", testUser)) } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala index 0f9fa7692b1..52c031848e8 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/AppleAuthResourceSpec.scala @@ -19,17 +19,11 @@ package org.apache.texera.web.resource.auth -import org.apache.texera.auth.InviteOnly import org.apache.texera.common.config.UserSystemConfig -import org.apache.texera.dao.{MockTexeraDB, SiteSettings} -import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, SITE_SETTINGS, USER} +import org.apache.texera.dao.jooq.generated.Tables.USER import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, UserRoleEnum} -import org.apache.texera.dao.jooq.generated.tables.daos.UserDao import org.apache.texera.dao.jooq.generated.tables.pojos.User import org.jose4j.jwt.JwtClaims -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import javax.ws.rs.NotAuthorizedException @@ -42,38 +36,16 @@ import javax.ws.rs.NotAuthorizedException * two cases Apple's own documentation warns about: a string-typed `email_verified`, and a token * with no `email` at all. */ -class AppleAuthResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { - - private val emailDomain = "@apple-auth-test.com" - - private var userDao: UserDao = _ - - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - userDao = new UserDao(getDSLContext.configuration()) - } - - override protected def afterAll(): Unit = shutdownDB() - - override protected def beforeEach(): Unit = cleanup() - override protected def afterEach(): Unit = cleanup() +class AppleAuthResourceSpec extends AuthDatabaseSpec("@apple-auth-test.com") { // Identity-only accounts have a NULL email, so they are matched by the name they are given // instead — the Apple `sub`. AUTH_PROVIDER cascades on delete. - private def cleanup(): Unit = { + override protected def cleanup(): Unit = { getDSLContext .deleteFrom(USER) .where(USER.EMAIL.like("%" + emailDomain).or(USER.NAME.like("apple-sub-%"))) .execute() - getDSLContext - .deleteFrom(SITE_SETTINGS) - .where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey)) - .execute() + cleanupInviteOnlySetting() } // ---- helpers ------------------------------------------------------------- @@ -100,19 +72,10 @@ class AppleAuthResourceSpec .login("stubbed-credential") .accessToken should not be empty - private def userByEmail(localPart: String): User = - userDao.fetchOneByEmail(localPart + emailDomain) - private def userByName(name: String): User = userDao.fetchByName(name).stream().findFirst().orElse(null) - private def appleIdOf(uid: Integer): String = - getDSLContext - .select(AUTH_PROVIDER.PROVIDER_ID) - .from(AUTH_PROVIDER) - .where(AUTH_PROVIDER.UID.eq(uid)) - .and(AUTH_PROVIDER.PROVIDER_TYPE.eq(ProviderTypeEnum.APPLE)) - .fetchOne(AUTH_PROVIDER.PROVIDER_ID) + private def appleIdOf(uid: Integer): String = providerIdOf(uid, ProviderTypeEnum.APPLE) // ---- login --------------------------------------------------------------- @@ -121,7 +84,7 @@ class AppleAuthResourceSpec it should "provision an INACTIVE user and an APPLE provider row on a first login" in { // The role follows the admin's invite-only switch (ExternalAuthProvisionerSpec covers both // sides); pinned on here so the assertion does not depend on default.conf. - SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, "true", "apple-spec-admin") + setInviteOnly(on = true, "apple-spec-admin") loginWith(claims("apple-sub-new", "newcomer" + emailDomain)) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/AuthDatabaseSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/AuthDatabaseSpec.scala new file mode 100644 index 00000000000..76343dc4fdd --- /dev/null +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/AuthDatabaseSpec.scala @@ -0,0 +1,85 @@ +/* + * 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.auth + +import org.apache.texera.auth.InviteOnly +import org.apache.texera.dao.{DatabaseFlatSpec, SiteSettings} +import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, SITE_SETTINGS, USER} +import org.apache.texera.dao.jooq.generated.enums.ProviderTypeEnum +import org.apache.texera.dao.jooq.generated.tables.daos.{AuthProviderDao, UserDao} +import org.apache.texera.dao.jooq.generated.tables.pojos.User +import org.jooq.impl.DSL + +/** Shared embedded-Postgres base for authentication and provisioning integration specs. */ +abstract class AuthDatabaseSpec(protected val emailDomain: String = "") + extends DatabaseFlatSpec(cleanupAfterEach = true) { + + protected var userDao: UserDao = _ + protected var authDao: AuthProviderDao = _ + + override protected def onBeforeAll(): Unit = { + userDao = new UserDao(getDSLContext.configuration()) + authDao = new AuthProviderDao(getDSLContext.configuration()) + } + + protected def userByEmail(localPart: String): User = + userDao.fetchOneByEmail(localPart + emailDomain) + + /** Counts case-insensitively, so a duplicate differing only in case is still counted. */ + protected def userCountByEmail(localPart: String): Int = + getDSLContext.fetchCount(USER, DSL.lower(USER.EMAIL).eq(localPart + emailDomain)) + + protected def providerIdOf(uid: Integer, providerType: ProviderTypeEnum): String = + getDSLContext + .select(AUTH_PROVIDER.PROVIDER_ID) + .from(AUTH_PROVIDER) + .where(AUTH_PROVIDER.UID.eq(uid)) + .and(AUTH_PROVIDER.PROVIDER_TYPE.eq(providerType)) + .fetchOne(AUTH_PROVIDER.PROVIDER_ID) + + protected def deleteUsersByEmailDomain(caseInsensitive: Boolean = false): Unit = { + require(emailDomain.nonEmpty, "deleteUsersByEmailDomain needs a non-empty emailDomain") + val cond = + if (caseInsensitive) DSL.lower(USER.EMAIL).like("%" + emailDomain) + else USER.EMAIL.like("%" + emailDomain) + getDSLContext.deleteFrom(USER).where(cond).execute() + } + + protected def deleteUsersByProviderType(providerType: ProviderTypeEnum): Unit = + getDSLContext + .deleteFrom(USER) + .where( + USER.UID.in( + getDSLContext + .select(AUTH_PROVIDER.UID) + .from(AUTH_PROVIDER) + .where(AUTH_PROVIDER.PROVIDER_TYPE.eq(providerType)) + ) + ) + .execute() + + protected def cleanupInviteOnlySetting(): Unit = + getDSLContext + .deleteFrom(SITE_SETTINGS) + .where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey)) + .execute() + + protected def setInviteOnly(on: Boolean, updatedBy: String): Unit = + SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, on.toString, updatedBy) +} diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/EmailCodeVerifierSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/EmailCodeVerifierSpec.scala index d78d0a9de34..804433ffed0 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/EmailCodeVerifierSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/EmailCodeVerifierSpec.scala @@ -72,6 +72,14 @@ class EmailCodeVerifierSpec extends AnyFlatSpec with Matchers with BeforeAndAfte private def advance(seconds: Long): Unit = now = now.plusSeconds(seconds) + private def checkStatus(purpose: String, scope: String, address: String, code: String): Int = + statusOf(intercept[WebApplicationException](verifier.check(purpose, scope, address, code))) + + private def spendAttempts(scope: String, address: String): Unit = + (1 to EmailCodeVerifier.MAX_ATTEMPTS).foreach { _ => + intercept[WebApplicationException](verifier.check(ADD_EMAIL, scope, address, "000000")) + } + "issue" should "mail a six-digit code to the address being verified" in { verifier.issue(ADD_EMAIL, "7", "someone@example.com") @@ -166,33 +174,25 @@ class EmailCodeVerifierSpec extends AnyFlatSpec with Matchers with BeforeAndAfte val code = issueAndRead(ADD_EMAIL, "7", "a@b.com") advance(EmailCodeVerifier.STEP_SECONDS * 2) - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "a@b.com", code)) - ) shouldBe 406 + checkStatus(ADD_EMAIL, "7", "a@b.com", code) shouldBe 406 } it should "reject a code minted for a different address" in { val code = issueAndRead(ADD_EMAIL, "7", "a@b.com") - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "other@b.com", code)) - ) shouldBe 406 + checkStatus(ADD_EMAIL, "7", "other@b.com", code) shouldBe 406 } it should "reject a code minted for a different scope" in { val code = issueAndRead(ADD_EMAIL, "7", "a@b.com") - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "8", "a@b.com", code)) - ) shouldBe 406 + checkStatus(ADD_EMAIL, "8", "a@b.com", code) shouldBe 406 } it should "reject a code minted for a different purpose" in { val code = issueAndRead(REGISTER, "handle", "a@b.com") - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "handle", "a@b.com", code)) - ) shouldBe 406 + checkStatus(ADD_EMAIL, "handle", "a@b.com", code) shouldBe 406 } it should "reject a code minted under a different secret" in { @@ -219,9 +219,7 @@ class EmailCodeVerifierSpec extends AnyFlatSpec with Matchers with BeforeAndAfte issueAndRead(ADD_EMAIL, "7", "a@b.com") Seq(null, "", "12345", "abcdef").foreach { bad => - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "a@b.com", bad)) - ) shouldBe 406 + checkStatus(ADD_EMAIL, "7", "a@b.com", bad) shouldBe 406 } } @@ -230,35 +228,25 @@ class EmailCodeVerifierSpec extends AnyFlatSpec with Matchers with BeforeAndAfte val wrong = if (code == "000000") "111111" else "000000" (1 to EmailCodeVerifier.MAX_ATTEMPTS).foreach { _ => - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "a@b.com", wrong)) - ) shouldBe 406 + checkStatus(ADD_EMAIL, "7", "a@b.com", wrong) shouldBe 406 } // Even the right code is refused now, and with 429 rather than 406 — the caller has been // rate-limited, not told anything about the code. - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "a@b.com", code)) - ) shouldBe 429 + checkStatus(ADD_EMAIL, "7", "a@b.com", code) shouldBe 429 } it should "not let one scope's spent attempts lock out another" in { val code = issueAndRead(ADD_EMAIL, "8", "b@b.com") - (1 to EmailCodeVerifier.MAX_ATTEMPTS).foreach { _ => - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "a@b.com", "000000")) - } + spendAttempts("7", "a@b.com") noException should be thrownBy verifier.check(ADD_EMAIL, "8", "b@b.com", code) } it should "give a fresh attempt budget once the guesses age out" in { val code = issueAndRead(ADD_EMAIL, "7", "a@b.com") - (1 to EmailCodeVerifier.MAX_ATTEMPTS).foreach { _ => - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "a@b.com", "000000")) - } - statusOf( - intercept[WebApplicationException](verifier.check(ADD_EMAIL, "7", "a@b.com", code)) - ) shouldBe 429 + spendAttempts("7", "a@b.com") + checkStatus(ADD_EMAIL, "7", "a@b.com", code) shouldBe 429 // The cap bounds guesses per window, not forever; the code itself has expired by now anyway. advance(EmailCodeVerifier.STEP_SECONDS * 2) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala index 9da0c5411c8..23b4d7e500b 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisionerSpec.scala @@ -19,75 +19,32 @@ package org.apache.texera.web.resource.auth -import org.apache.texera.auth.InviteOnly -import org.apache.texera.dao.{MockTexeraDB, SiteSettings} -import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, SITE_SETTINGS, USER} +import org.apache.texera.dao.jooq.generated.Tables.AUTH_PROVIDER import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, UserRoleEnum} -import org.apache.texera.dao.jooq.generated.tables.daos.{AuthProviderDao, UserDao} import org.apache.texera.dao.jooq.generated.tables.pojos.{AuthProvider, User} -import org.jooq.impl.DSL -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} /** * Integration spec for [[ExternalAuthProvisioner]] against embedded Postgres - * ([[MockTexeraDB]] loads the real `texera_ddl.sql`, so the `auth_provider` table and + * ([[AuthDatabaseSpec]] loads the real `texera_ddl.sql`, so the `auth_provider` table and * its `ck_provider_credential` / `uq_provider_identity` constraints are exercised). * `loginOrProvision` runs the same transaction the Google resources call. */ -class ExternalAuthProvisionerSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { - - // All test users share this email suffix so cleanup can target them precisely; - // the auth_provider FK is ON DELETE CASCADE, so deleting the user clears its rows. - private val emailDomain = "@provisioner-test.com" - - private var userDao: UserDao = _ - private var authDao: AuthProviderDao = _ - - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - userDao = new UserDao(getDSLContext.configuration()) - authDao = new AuthProviderDao(getDSLContext.configuration()) - } - - override protected def afterAll(): Unit = shutdownDB() - - override protected def beforeEach(): Unit = cleanup() - override protected def afterEach(): Unit = cleanup() +class ExternalAuthProvisionerSpec extends AuthDatabaseSpec("@provisioner-test.com") { // Case-insensitive so it also collects rows seeded with a differing casing. The ORCID arm // catches what the email predicate cannot: an identity-only login leaves `email` NULL, so those // accounts are identified by the provider row that cascades from them. - private def cleanup(): Unit = { - getDSLContext.deleteFrom(USER).where(DSL.lower(USER.EMAIL).like("%" + emailDomain)).execute() - getDSLContext - .deleteFrom(USER) - .where( - USER.UID.in( - getDSLContext - .select(AUTH_PROVIDER.UID) - .from(AUTH_PROVIDER) - .where(AUTH_PROVIDER.PROVIDER_TYPE.eq(ProviderTypeEnum.ORCID)) - ) - ) - .execute() - getDSLContext - .deleteFrom(SITE_SETTINGS) - .where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey)) - .execute() + override protected def cleanup(): Unit = { + deleteUsersByEmailDomain(caseInsensitive = true) + deleteUsersByProviderType(ProviderTypeEnum.ORCID) + cleanupInviteOnlySetting() } // ---- helpers ------------------------------------------------------------- /** Flip the invite-only switch the way the admin settings page does; `cleanup` removes it. */ private def setInviteOnly(on: Boolean): Unit = - SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, on.toString, "provisioner-admin") + setInviteOnly(on, "provisioner-admin") /** A contributor placeholder as DatasetResource creates one: INACTIVE, with no credential. */ private def seedPlaceholder(name: String, localPart: String): User = { @@ -139,18 +96,6 @@ class ExternalAuthProvisionerSpec private def providerRowCount(uid: Integer): Int = getDSLContext.fetchCount(AUTH_PROVIDER, AUTH_PROVIDER.UID.eq(uid)) - private def providerIdOf(uid: Integer, pt: ProviderTypeEnum): String = - getDSLContext - .select(AUTH_PROVIDER.PROVIDER_ID) - .from(AUTH_PROVIDER) - .where(AUTH_PROVIDER.UID.eq(uid)) - .and(AUTH_PROVIDER.PROVIDER_TYPE.eq(pt)) - .fetchOne(AUTH_PROVIDER.PROVIDER_ID) - - /** Counts case-insensitively, so a duplicate differing only in case is still counted. */ - private def userCountByEmail(localPart: String): Int = - getDSLContext.fetchCount(USER, DSL.lower(USER.EMAIL).eq(localPart + emailDomain)) - // ---- new-identity provisioning ------------------------------------------- "ExternalAuthProvisioner.loginOrProvision" should "create an INACTIVE user and provider row for a brand-new Google identity while invite-only is on" in { diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala index b5fbbccc921..23c789b2a35 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/GoogleAuthResourceSpec.scala @@ -20,16 +20,9 @@ package org.apache.texera.web.resource.auth import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken -import org.apache.texera.auth.InviteOnly import org.apache.texera.common.config.UserSystemConfig -import org.apache.texera.dao.{MockTexeraDB, SiteSettings} -import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, SITE_SETTINGS, USER} +import org.apache.texera.dao.jooq.generated.Tables.USER import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, 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.NotAuthorizedException @@ -42,34 +35,13 @@ import javax.ws.rs.NotAuthorizedException * Google payload becomes an [[ExternalProfile]] (the name fallback, and the avatar kept as the * complete URL the provider supplied) and that a credential Google does not verify is a 401. */ -class GoogleAuthResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { - - private val emailDomain = "@google-auth-test.com" - private val avatarUrl = "https://lh3.googleusercontent.com/a/AVATAR-ID" - - private var userDao: UserDao = _ - - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - userDao = new UserDao(getDSLContext.configuration()) - } +class GoogleAuthResourceSpec extends AuthDatabaseSpec("@google-auth-test.com") { - override protected def afterAll(): Unit = shutdownDB() - - override protected def beforeEach(): Unit = cleanup() - override protected def afterEach(): Unit = cleanup() + private val avatarUrl = "https://lh3.googleusercontent.com/a/AVATAR-ID" - private def cleanup(): Unit = { - getDSLContext.deleteFrom(USER).where(USER.EMAIL.like("%" + emailDomain)).execute() - getDSLContext - .deleteFrom(SITE_SETTINGS) - .where(SITE_SETTINGS.KEY.eq(InviteOnly.SettingKey)) - .execute() + override protected def cleanup(): Unit = { + deleteUsersByEmailDomain() + cleanupInviteOnlySetting() } // ---- helpers ------------------------------------------------------------- @@ -108,16 +80,7 @@ class GoogleAuthResourceSpec .login("stubbed-credential") .accessToken should not be empty - private def userByEmail(localPart: String): User = - userDao.fetchOneByEmail(localPart + emailDomain) - - private def googleIdOf(uid: Integer): String = - getDSLContext - .select(AUTH_PROVIDER.PROVIDER_ID) - .from(AUTH_PROVIDER) - .where(AUTH_PROVIDER.UID.eq(uid)) - .and(AUTH_PROVIDER.PROVIDER_TYPE.eq(ProviderTypeEnum.GOOGLE)) - .fetchOne(AUTH_PROVIDER.PROVIDER_ID) + private def googleIdOf(uid: Integer): String = providerIdOf(uid, ProviderTypeEnum.GOOGLE) // ---- first login --------------------------------------------------------- @@ -126,7 +89,7 @@ class GoogleAuthResourceSpec it should "provision an INACTIVE user and a GOOGLE provider row on a first login" in { // The role follows the admin's invite-only switch (ExternalAuthProvisionerSpec covers both // sides); pinned on here so the assertion does not depend on default.conf. - SiteSettings.upsert(getDSLContext, InviteOnly.SettingKey, "true", "google-spec-admin") + setInviteOnly(on = true, "google-spec-admin") loginWith(payload("google-sub-new", "newcomer" + emailDomain, name = "New Comer")) diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/LocalAuthProvisionerSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/LocalAuthProvisionerSpec.scala index 9a6b2653605..d04310a103a 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/LocalAuthProvisionerSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/LocalAuthProvisionerSpec.scala @@ -19,15 +19,9 @@ package org.apache.texera.web.resource.auth -import org.apache.texera.dao.MockTexeraDB -import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, USER} +import org.apache.texera.dao.jooq.generated.Tables.AUTH_PROVIDER import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, UserRoleEnum} -import org.apache.texera.dao.jooq.generated.tables.daos.{AuthProviderDao, UserDao} import org.apache.texera.dao.jooq.generated.tables.pojos.{AuthProvider, User} -import org.jooq.impl.DSL -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 @@ -44,33 +38,12 @@ import javax.ws.rs.core.Response * the wrong one tells a user their free handle is taken, and the two write methods reach * different constraint sets, so a fix applied to one does not cover the other. */ -class LocalAuthProvisionerSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class LocalAuthProvisionerSpec extends AuthDatabaseSpec("@local-provisioner-test.com") { // Shared suffix so cleanup can target this suite's rows precisely; the auth_provider FK is // ON DELETE CASCADE, so deleting the user clears its credential rows. - private val emailDomain = "@local-provisioner-test.com" - - private var userDao: UserDao = _ - private var authDao: AuthProviderDao = _ - - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - userDao = new UserDao(getDSLContext.configuration()) - authDao = new AuthProviderDao(getDSLContext.configuration()) - } - - override protected def afterAll(): Unit = shutdownDB() - - override protected def beforeEach(): Unit = cleanup() - override protected def afterEach(): Unit = cleanup() - - private def cleanup(): Unit = - getDSLContext.deleteFrom(USER).where(DSL.lower(USER.EMAIL).like("%" + emailDomain)).execute() + override protected def cleanup(): Unit = + deleteUsersByEmailDomain(caseInsensitive = true) // ---- helpers ------------------------------------------------------------- @@ -104,9 +77,6 @@ class LocalAuthProvisionerSpec user } - private def userCountByEmail(localPart: String): Int = - getDSLContext.fetchCount(USER, DSL.lower(USER.EMAIL).eq(localPart + emailDomain)) - private def conflictFrom(body: => Unit): WebApplicationException = { val thrown = intercept[WebApplicationException](body) thrown.getResponse.getStatus shouldBe Response.Status.CONFLICT.getStatusCode @@ -170,7 +140,7 @@ class LocalAuthProvisionerSpec // The claim and the credential share one transaction, so the rollback must leave the // placeholder flag as it was rather than marking an account claimed with no new credential. userDao.fetchOneByUid(claimed.getUid).getIsPlaceholder shouldBe true - providerIdOf(claimed.getUid) shouldBe "first-claimer" + providerIdOf(claimed.getUid, ProviderTypeEnum.LOCAL) shouldBe "first-claimer" } it should "report a taken handle when uq_provider_identity fires" in { @@ -186,12 +156,4 @@ class LocalAuthProvisionerSpec thrown.getMessage should not include "has already been claimed" userDao.fetchOneByUid(placeholder.getUid).getIsPlaceholder shouldBe true } - - private def providerIdOf(uid: Integer): String = - getDSLContext - .select(AUTH_PROVIDER.PROVIDER_ID) - .from(AUTH_PROVIDER) - .where(AUTH_PROVIDER.UID.eq(uid)) - .and(AUTH_PROVIDER.PROVIDER_TYPE.eq(ProviderTypeEnum.LOCAL)) - .fetchOne(AUTH_PROVIDER.PROVIDER_ID) } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/auth/OrcidAuthResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/auth/OrcidAuthResourceSpec.scala index ed504a8d0d4..24015173293 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/auth/OrcidAuthResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/auth/OrcidAuthResourceSpec.scala @@ -19,14 +19,9 @@ package org.apache.texera.web.resource.auth -import org.apache.texera.dao.MockTexeraDB import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, USER} import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, 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.NotAuthorizedException @@ -38,41 +33,14 @@ import javax.ws.rs.NotAuthorizedException * feeds: that an authenticated iD becomes an emailless INACTIVE account with an ORCID provider row, * and that a response authenticating nobody is a 401 rather than an account. */ -class OrcidAuthResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class OrcidAuthResourceSpec extends AuthDatabaseSpec { private val orcidId = "0000-0002-1825-0097" - private var userDao: UserDao = _ - - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - userDao = new UserDao(getDSLContext.configuration()) - } - - override protected def afterAll(): Unit = shutdownDB() - - override protected def beforeEach(): Unit = cleanup() - override protected def afterEach(): Unit = cleanup() - // Accounts provisioned here have no email, so they are identified by the provider row that // cascades from them rather than by an address pattern. - private def cleanup(): Unit = - getDSLContext - .deleteFrom(USER) - .where( - USER.UID.in( - getDSLContext - .select(AUTH_PROVIDER.UID) - .from(AUTH_PROVIDER) - .where(AUTH_PROVIDER.PROVIDER_TYPE.eq(ProviderTypeEnum.ORCID)) - ) - ) - .execute() + override protected def cleanup(): Unit = + deleteUsersByProviderType(ProviderTypeEnum.ORCID) // ---- helpers ------------------------------------------------------------- diff --git a/amber/src/test/scala/org/apache/texera/web/service/WorkflowEmailNotifierSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/WorkflowEmailNotifierSpec.scala index aecc3dc3fbf..df84ae9bab0 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/WorkflowEmailNotifierSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/WorkflowEmailNotifierSpec.scala @@ -21,13 +21,12 @@ package org.apache.texera.web.service import org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState import org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState._ -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.WORKFLOW import org.apache.texera.dao.jooq.generated.tables.daos.WorkflowDao import org.apache.texera.dao.jooq.generated.tables.pojos.Workflow import org.apache.texera.web.resource.EmailMessage -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.{BeforeAndAfterAll, PrivateMethodTester} +import org.scalatest.PrivateMethodTester import java.net.URI import java.sql.Timestamp @@ -53,9 +52,7 @@ import javax.ws.rs.NotFoundException * invoked, so no test here reaches `GmailResource.sendEmail`. */ class WorkflowEmailNotifierSpec - extends AnyFlatSpec - with BeforeAndAfterAll - with MockTexeraDB + extends DatabaseFlatSpec(cleanupBeforeEach = false, cleanupAfterAll = true) with PrivateMethodTester { private val testWid: Int = 7000 + scala.util.Random.nextInt(1000) @@ -72,9 +69,8 @@ class WorkflowEmailNotifierSpec private val formatTimestamp = PrivateMethod[String](Symbol("formatTimestamp")) private val isValidEmail = PrivateMethod[Boolean](Symbol("isValidEmail")) - override protected def beforeAll(): Unit = { - initializeDBAndReplaceDSLContext() - deleteFixtureRows() + override protected def onBeforeAll(): Unit = { + cleanup() val workflow = new Workflow workflow.setWid(testWid) @@ -86,12 +82,7 @@ class WorkflowEmailNotifierSpec new WorkflowDao(getDSLContext.configuration()).insert(workflow) } - override protected def afterAll(): Unit = { - deleteFixtureRows() - shutdownDB() - } - - private def deleteFixtureRows(): Unit = + override protected def cleanup(): Unit = getDSLContext.deleteFrom(WORKFLOW).where(WORKFLOW.WID.in(testWid, unseededWid)).execute() /** Builds a notifier for the seeded workflow; the constructor hits the database every time. */ diff --git a/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala b/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala index 5a73acf3d3a..d1c69de92d2 100644 --- a/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala +++ b/common/dao/src/test/scala/org/apache/texera/dao/SiteSettingsSpec.scala @@ -19,35 +19,13 @@ package org.apache.texera.dao import org.apache.texera.dao.jooq.generated.Tables.SITE_SETTINGS -import org.scalatest.BeforeAndAfterAll -import org.scalatest.BeforeAndAfterEach -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers import scala.util.Success -class SiteSettingsSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { - - // Point SqlServer (used by SiteSettings.getInt/getLong internally) and the test's - // own getDSLContext at the same embedded Postgres. - override protected def beforeAll(): Unit = { - super.beforeAll() - initializeDBAndReplaceDSLContext() - } - - override protected def afterAll(): Unit = - try closeConnectionPool() - finally super.afterAll() +class SiteSettingsSpec extends DatabaseFlatSpec() { - override protected def beforeEach(): Unit = { - super.beforeEach() + override protected def cleanup(): Unit = getDSLContext.deleteFrom(SITE_SETTINGS).execute() - } private def storedUpdatedBy(key: String): String = getDSLContext diff --git a/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/AdminComputingUnitResourceSpec.scala b/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/AdminComputingUnitResourceSpec.scala index a9b4ef2a0fc..a33df545b40 100644 --- a/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/AdminComputingUnitResourceSpec.scala +++ b/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/AdminComputingUnitResourceSpec.scala @@ -23,7 +23,7 @@ import jakarta.annotation.security.RolesAllowed import jakarta.ws.rs.NotFoundException import org.apache.texera.auth.SessionUser import org.apache.texera.common.config.KubernetesConfig -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.WORKFLOW_COMPUTING_UNIT import org.apache.texera.dao.jooq.generated.enums.{ PrivilegeEnum, @@ -32,36 +32,17 @@ import org.apache.texera.dao.jooq.generated.enums.{ } import org.apache.texera.dao.jooq.generated.tables.daos.{UserDao, WorkflowComputingUnitDao} import org.apache.texera.dao.jooq.generated.tables.pojos.{User, WorkflowComputingUnit} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import java.sql.Timestamp -class AdminComputingUnitResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { - - override protected def beforeAll(): Unit = { - super.beforeAll() - initializeDBAndReplaceDSLContext() - } +class AdminComputingUnitResourceSpec extends DatabaseFlatSpec() { // MockTexeraDB does not truncate between tests, and this endpoint lists every unit in the // database, so each case must start from a known-empty table — otherwise the exact-match // assertions below depend on the order ScalaTest happens to run the cases in. Safe to wipe // unqualified: MockTexeraDB provisions a fresh database per suite, so these are the only rows. - override protected def beforeEach(): Unit = { - super.beforeEach() + override protected def cleanup(): Unit = getDSLContext.deleteFrom(WORKFLOW_COMPUTING_UNIT).execute() - } - - override protected def afterAll(): Unit = - try shutdownDB() - finally super.afterAll() private def makeUser(uid: Int, name: String): User = { val u = new User() diff --git a/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitAccessResourceSpec.scala b/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitAccessResourceSpec.scala index 02bbbb4864d..e0bbec15ba0 100644 --- a/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitAccessResourceSpec.scala +++ b/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitAccessResourceSpec.scala @@ -22,7 +22,7 @@ package org.apache.texera.service.resource import jakarta.ws.rs.{BadRequestException, ForbiddenException, NotFoundException} import org.apache.texera.auth.SessionUser import org.apache.texera.common.config.ComputingUnitConfig -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.dao.jooq.generated.Tables.COMPUTING_UNIT_USER_ACCESS import org.apache.texera.dao.jooq.generated.enums.{ PrivilegeEnum, @@ -39,9 +39,6 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ User, WorkflowComputingUnit } -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} /** * Spec for [[ComputingUnitAccessResource]] with sharing ENABLED, backed by an embedded @@ -55,12 +52,7 @@ import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} * The sharing-DISABLED branch is covered separately by ComputingUnitAccessSharingDisabledSpec, * which forks without that env var (the flag is a load-time val). */ -class ComputingUnitAccessResourceSpec - extends AnyFlatSpec - with Matchers - with MockTexeraDB - with BeforeAndAfterAll - with BeforeAndAfterEach { +class ComputingUnitAccessResourceSpec extends DatabaseFlatSpec() { private val ownerUser: User = { val user = new User @@ -116,10 +108,7 @@ class ComputingUnitAccessResourceSpec new ComputingUnitUserAccessDao(getDSLContext.configuration()).insert(access) } - override protected def beforeAll(): Unit = { - super.beforeAll() - initializeDBAndReplaceDSLContext() - + override protected def onBeforeAll(): Unit = { val userDao = new UserDao(getDSLContext.configuration()) userDao.insert(ownerUser) userDao.insert(granteeUser) @@ -129,16 +118,9 @@ class ComputingUnitAccessResourceSpec new WorkflowComputingUnitDao(getDSLContext.configuration()).insert(ownedUnit) } - override protected def beforeEach(): Unit = { - super.beforeEach() - // every test starts with no explicit grants on the unit + // every test starts with no explicit grants on the unit + override protected def cleanup(): Unit = getDSLContext.deleteFrom(COMPUTING_UNIT_USER_ACCESS).execute() - } - - override protected def afterAll(): Unit = { - try shutdownDB() - finally super.afterAll() - } "the test environment" should "have computing-unit sharing enabled" in { // guards against a silent misconfiguration that would make every case below diff --git a/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitIdleCleanupSpec.scala b/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitIdleCleanupSpec.scala index 3a736550c8c..c74726bedcb 100644 --- a/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitIdleCleanupSpec.scala +++ b/computing-unit-managing-service/src/test/scala/org/apache/texera/service/resource/ComputingUnitIdleCleanupSpec.scala @@ -20,7 +20,7 @@ package org.apache.texera.service.resource 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.{ USER => USER_TABLE, WORKFLOW, @@ -50,20 +50,11 @@ import org.apache.texera.service.resource.ComputingUnitManagingResource.Terminat import org.apache.texera.service.util.KubernetesClient import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito.{doThrow, mock, never, verify, verifyNoInteractions} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} - import java.sql.Timestamp import java.util.UUID import java.util.concurrent.TimeUnit -class ComputingUnitIdleCleanupSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class ComputingUnitIdleCleanupSpec extends DatabaseFlatSpec(cleanupAfterEach = true) { private val testUserId = 810000 + scala.util.Random.nextInt(10000) private val testWorkflowId = 820000 + scala.util.Random.nextInt(10000) @@ -77,18 +68,13 @@ class ComputingUnitIdleCleanupSpec private var workflowExecutionsDao: WorkflowExecutionsDao = _ private var testVersion: WorkflowVersion = _ - override protected def beforeAll(): Unit = - initializeDBAndReplaceDSLContext() - - override protected def beforeEach(): Unit = { + override protected def onBeforeEach(): Unit = { userDao = new UserDao(getDSLContext.configuration()) workflowDao = new WorkflowDao(getDSLContext.configuration()) workflowVersionDao = new WorkflowVersionDao(getDSLContext.configuration()) workflowComputingUnitDao = new WorkflowComputingUnitDao(getDSLContext.configuration()) workflowExecutionsDao = new WorkflowExecutionsDao(getDSLContext.configuration()) - cleanupTestData() - val user = new User user.setUid(testUserId) user.setName("idle-cu-owner") @@ -110,13 +96,7 @@ class ComputingUnitIdleCleanupSpec workflowVersionDao.insert(testVersion) } - override protected def afterEach(): Unit = - cleanupTestData() - - override protected def afterAll(): Unit = - shutdownDB() - - private def cleanupTestData(): Unit = { + override protected def cleanup(): Unit = { getDSLContext .deleteFrom(WORKFLOW_EXECUTIONS) .where(WORKFLOW_EXECUTIONS.UID.eq(testUserId)) diff --git a/notebook-migration-service/src/test/scala/org/apache/texera/service/resource/NotebookMigrationResourceSpec.scala b/notebook-migration-service/src/test/scala/org/apache/texera/service/resource/NotebookMigrationResourceSpec.scala index e1c1f7ab8e4..ef40f7c39d4 100644 --- a/notebook-migration-service/src/test/scala/org/apache/texera/service/resource/NotebookMigrationResourceSpec.scala +++ b/notebook-migration-service/src/test/scala/org/apache/texera/service/resource/NotebookMigrationResourceSpec.scala @@ -22,7 +22,7 @@ package org.apache.texera.service.resource import jakarta.ws.rs.core.Response import org.apache.texera.auth.SessionUser import io.fabric8.kubernetes.client.KubernetesClientException -import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.DatabaseFlatSpec import org.apache.texera.service.util.{ JupyterEndpointResolver, JupyterEndpoints, @@ -53,9 +53,6 @@ import org.apache.texera.dao.jooq.generated.tables.pojos.{ WorkflowVersion } import org.jooq.JSONB -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import com.sun.net.httpserver.HttpServer @@ -65,12 +62,7 @@ import scala.jdk.CollectionConverters._ import java.sql.Timestamp import java.util.UUID -class NotebookMigrationResourceSpec - extends AnyFlatSpec - with Matchers - with BeforeAndAfterAll - with BeforeAndAfterEach - with MockTexeraDB { +class NotebookMigrationResourceSpec extends DatabaseFlatSpec(cleanupAfterEach = true) { // Randomise the seeded wid so a parallel run of unrelated specs that happen // to seed the same id wouldn't collide on the embedded postgres. @@ -95,17 +87,13 @@ class NotebookMigrationResourceSpec private val sampleMapping = """{"operator_to_cell":{},"cell_to_operator":{}}""" - override protected def beforeAll(): Unit = initializeDBAndReplaceDSLContext() - override protected def afterAll(): Unit = closeConnectionPool() - - override protected def beforeEach(): Unit = { + override protected def onBeforeEach(): Unit = { val cfg = getDSLContext.configuration() workflowDao = new WorkflowDao(cfg) workflowVersionDao = new WorkflowVersionDao(cfg) userDao = new UserDao(cfg) workflowUserAccessDao = new WorkflowUserAccessDao(cfg) lastContentsRequest = None - cleanup() val workflow = new Workflow workflow.setWid(testWid) @@ -131,8 +119,6 @@ class NotebookMigrationResourceSpec insertAccess(readerUid, PrivilegeEnum.READ) } - override protected def afterEach(): Unit = cleanup() - private def insertUser(name: String, email: String): Integer = { val user = new User user.setName(name) @@ -150,7 +136,7 @@ class NotebookMigrationResourceSpec workflowUserAccessDao.insert(access) } - private def cleanup(): Unit = { + override protected def cleanup(): Unit = { // Delete children before parents. workflow_user_access and notebook cascade // on workflow delete, but explicit deletes keep state observable across tests // and avoid depending on cascade ordering.