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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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) -----------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand All @@ -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
Expand All @@ -84,66 +75,58 @@ 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
counts(otherUid) shouldBe 1
}

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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())
}
Expand All @@ -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())
}
Expand Down Expand Up @@ -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())
}
Expand All @@ -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
Expand 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(_) =>
Expand All @@ -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()

/**
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading