Skip to content

Validation for unit test names #1336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 16, 2024
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
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,7 @@ lazy val spark_scala = (project in file("spark-scala"))

addCommandAlias(
"ci",
";compile;test:compile;it:compile;scalafmtCheckAll;test"
";compile;test:compile;it:compile;scalafmtCheckAll;validateUnitTestNames;test"
)

addCommandAlias(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicBoolean

import scala.concurrent.duration.DurationInt

class CancellationSpec extends AnyWordSpec with Matchers {
class CancellationUnitTest extends AnyWordSpec with Matchers {

"Cancellation" should {
"cancel the fiber directly and execute the action on cancellation" in {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import org.scalatest.wordspec.AnyWordSpec
import scala.util.Try
import scala.util.control.NoStackTrace;

class ErrorHandlingSpec extends AnyWordSpec with Matchers {
class ErrorHandlingUnitTest extends AnyWordSpec with Matchers {

"Calculator" should {
"return left value using attempt in case of division by zero" in {
Expand Down
75 changes: 75 additions & 0 deletions internal-scripts/ClassRenamer.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/** This is an internal scala-cli script written just to reduce manual work of
* renaming files and class names to follow naming standards. This doesn't
* fully correct all the class names, however reduces the manual effort by 90%.
*/
//> using toolkit default
import os._

object RenameClassNames {
def main(args: Array[String]): Unit = {
val directory = os.pwd / os.up

os.walk(directory)
.filter(_.ext == "scala")
.filter(_.toString.contains("src/test/scala"))
.filterNot(_.toString.endsWith("UnitTest.scala"))
.filter(f =>
f.toString.endsWith("Test.scala") || f.toString.endsWith(
"Spec.scala"
) || f.toString.endsWith("Tests.scala") || f.toString
.endsWith("Suite.scala")
)
.foreach { _filePath =>
val _fileName = _filePath.last

val newFileName = _filePath.toString
.replace("Test.scala", "UnitTest.scala")
.replace("Spec.scala", "UnitTest.scala")
.replace("Suite.scala", "UnitTest.scala")
.replace("Tests.scala", "UnitTest.scala")

// rename file
val newFilePath = os.Path(newFileName)
os.move(_filePath, newFilePath)

val content = os.read(newFilePath)
val existingClassName = getClassFromContent(content)

val fileNameWithoutExtension = newFilePath.last.dropRight(6)

def isTestClass(existingClassName: String): Boolean = {
existingClassName
.endsWith("Spec") || existingClassName.endsWith("Test")
}

// Rename the class if it doesn't match the filename
if (
isTestClass(
existingClassName
) && existingClassName.toLowerCase != fileNameWithoutExtension.toLowerCase
) {
// Update the content with the new class name
val updatedContent = content.replaceAll(
s"class\\s+$existingClassName",
s"class $fileNameWithoutExtension"
)

// Now, rename the class
os.write.over(newFilePath, updatedContent)
println(
s"Renamed class in ${newFilePath.last} to $fileNameWithoutExtension"
)
}
}
}

// Extract class name from file content
def getClassFromContent(content: String): String = {
val classNameRegex = """class\s+(\w+)""".r
val matchResult = classNameRegex.findFirstMatchIn(content)
matchResult match {
case Some(m) => m.group(1)
case None => ""
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import play.api.mvc.Headers
import play.api.mvc.Results.NoContent
import play.api.test.{FakeRequest, Helpers}

class SourceActionsTest
class SourceActionsUnitTest
extends AnyWordSpec
with SourceActions
with ScalaFutures {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import play.api.libs.ws.{WSClient, WSResponse}

import scala.concurrent.Future

class ArrivalControllerH2Test
class ArrivalControllerH2UnitTest
extends AnyWordSpec
with WsScalaTestClient
with GuiceOneServerPerTest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import org.scalatestplus.play.MixedPlaySpec
import play.api.Configuration
import play.api.inject.guice.GuiceApplicationBuilder

class ArrivalDecoratorServiceTest extends MixedPlaySpec {
class ArrivalDecoratorServiceUnitTest extends MixedPlaySpec {

"ArrivalDecoratorService#decorate" should {
"mark as short an arrival with plane name length = 5" in new App(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import org.scalatestplus.play.guice.GuiceOneAppPerTest

import scala.language.postfixOps

class ArrivalServiceH2Test
class ArrivalServiceH2UnitTest
extends AnyWordSpec
with GuiceOneAppPerTest
with ScalaFutures
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.{Application, Configuration, inject}

class ArrivalServiceIsolatedTest
class ArrivalServiceIsolatedUnitTest
extends AnyWordSpec
with GuiceOneAppPerTest
with ScalaFutures {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import slick.dbio.{DBIO, SuccessAction}

import scala.concurrent.Future

class ArrivalServiceMocksTest
class ArrivalServiceMocksUnitTest
extends AnyWordSpec
with GuiceOneAppPerTest
with ScalaFutures
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import org.scalatest.wordspec.FixtureAnyWordSpecLike
import org.scalatestplus.play.MixedFixtures
import play.api.inject.guice.GuiceApplicationBuilder

class ServiceWithRemoteCallTest
class ServiceWithRemoteCallUnitTest
extends MixedFixtures
with FixtureAnyWordSpecLike {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package macwire.service
import macwire.components.{ApiComponents, MockApiComponents, ServiceComponents}
import org.scalatest.wordspec.AnyWordSpec

class ServiceWithRemoteCallTest extends AnyWordSpec {
class ServiceWithRemoteCallUnitTest extends AnyWordSpec {

"ServiceWithRemoteCall call" should {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package com.baeldung.reflection

import org.junit.Test

class JavaReflectionTest {
class JavaReflectionUnitTest {
@Test
def invoke_method_dynamically(): Unit = {
val person = Person("John", 20)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import org.junit.Test

import scala.reflect.runtime.{universe => ru}

class ScalaReflectionTest {
class ScalaReflectionUnitTest {
@Test
def instantiate_a_class_at_runtime_v1: Unit = {
val mirror: ru.Mirror = ru.runtimeMirror(getClass.getClassLoader)
Expand Down
17 changes: 9 additions & 8 deletions sbt-standalone/build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ scalacOptions += "-target:17"
// Setting source and target for Java
javacOptions ++= Seq("-source", "17", "-target", "17")


// Enforcing the minimum JVM version
initialize := {
val _ = initialize.value // Ensure previous initializations are run

val required = VersionNumber("17")
val current = VersionNumber(sys.props("java.specification.version"))
println(current)
assert(CompatibleJavaVersion(current, required), s"Java $required or above is required to run this project.")
val _ = initialize.value // Ensure previous initializations are run

val required = VersionNumber("17")
val current = VersionNumber(sys.props("java.specification.version"))
println(current)
assert(
CompatibleJavaVersion(current, required),
s"Java $required or above is required to run this project."
)
}

19 changes: 10 additions & 9 deletions sbt-standalone/project/CompatibleJavaVersion.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import sbt._

// Define a custom object for Java specification version compatibility
object CompatibleJavaVersion extends VersionNumberCompatibility {
def name = "Java specification compatibility"
def name = "Java specification compatibility"

def isCompatible(current: VersionNumber, required: VersionNumber): Boolean =
current.numbers.zip(required.numbers)
.foldRight(required.numbers.size <= current.numbers.size) {
case ((curr, req), acc) => (curr > req) || (curr == req && acc)
}
def isCompatible(current: VersionNumber, required: VersionNumber): Boolean =
current.numbers
.zip(required.numbers)
.foldRight(required.numbers.size <= current.numbers.size) {
case ((curr, req), acc) => (curr > req) || (curr == req && acc)
}

def apply(current: VersionNumber, required: VersionNumber): Boolean =
isCompatible(current, required)
}
def apply(current: VersionNumber, required: VersionNumber): Boolean =
isCompatible(current, required)
}
2 changes: 1 addition & 1 deletion sbt-standalone/src/main/scala/Main.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
object Main extends App {
println("Hello from Scala!")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.baeldung.scala.macros
import org.scalatest.matchers.must.Matchers
import org.scalatest.wordspec.AnyWordSpec

class GenericMacrosTest extends AnyWordSpec with Matchers {
class GenericMacrosUnitTest extends AnyWordSpec with Matchers {
"generic macro" should {
"return String for string argument" in {
GenericMacros.getType("this is a string") mustBe "String"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.baeldung.scala.macros
import org.scalatest.matchers.must.Matchers
import org.scalatest.wordspec.AnyWordSpec

class OddEvenMacrosTest extends AnyWordSpec with Matchers {
class OddEvenMacrosUnitTest extends AnyWordSpec with Matchers {

"def macros" should {
"return literal odd for odd number" in {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,16 @@ object Main extends IOApp {
} yield Created(created)
}

val getTodo: Endpoint[IO, Todo] = get(todosPath :: path[Int]) {
id: Int =>
for {
todos <- sql"select * from todo where id = $id"
.query[Todo]
.to[Set]
.transact(xa)
} yield todos.headOption match {
case None => NotFound(new Exception("Record not found"))
case Some(todo) => Ok(todo)
}
val getTodo: Endpoint[IO, Todo] = get(todosPath :: path[Int]) { id: Int =>
for {
todos <- sql"select * from todo where id = $id"
.query[Todo]
.to[Set]
.transact(xa)
} yield todos.headOption match {
case None => NotFound(new Exception("Record not found"))
case Some(todo) => Ok(todo)
}
}

val updateTodo: Endpoint[IO, Todo] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ object ScalaAsyncTest {
} yield r1 + r2
}

class ScalaAsyncTest extends AsyncWordSpec with Matchers with ScalaFutures {
class ScalaAsyncUnitTest extends AsyncWordSpec with Matchers with ScalaFutures {

import ScalaAsyncTest._

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import pureconfig.generic.ProductHint
import pureconfig.error.ConfigReaderException
import scala.concurrent.duration._

class SampleConfigLoader extends AnyWordSpec with Matchers {
class SampleConfigLoaderUnitTest extends AnyWordSpec with Matchers {

"pureconfig" should {
"load config successfully" in {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import akka.testkit.TestKit
import org.scalatest.BeforeAndAfterAll
import org.scalatest.wordspec.AsyncWordSpecLike

class MessageExchangeServiceTest
class MessageExchangeServiceUnitTest
extends TestKit(ActorSystem("Akka-gRPC"))
with AsyncWordSpecLike
with BeforeAndAfterAll {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import akka.actor.testkit.typed.scaladsl.ScalaTestWithActorTestKit
import akka.pattern.StatusReply
import org.scalatest.wordspec.AnyWordSpecLike

class BankAccountTest extends ScalaTestWithActorTestKit with AnyWordSpecLike {
class BankAccountUnitTest
extends ScalaTestWithActorTestKit
with AnyWordSpecLike {

"A Bank Account" should {
"deposit money to a bank account" in {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class QueryParametersTest
class QueryParametersUnitTest
extends AnyWordSpec
with ScalatestRouteTest
with Matchers {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import com.baeldung.scala.akka.http.routetesting.AkkaRoutes.routes
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class AkkaRoutesTest extends AnyFlatSpec with Matchers with ScalatestRouteTest {
class AkkaRoutesUnitTest
extends AnyFlatSpec
with Matchers
with ScalatestRouteTest {
"/hello" should "return Hello World!" in {
Get("/hello") ~> routes ~> check {
status shouldEqual StatusCodes.OK
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import org.scalatest.concurrent.ScalaFutures.convertScalaFuture
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class StreamTest extends AnyFlatSpec with Matchers {
class StreamUnitTest extends AnyFlatSpec with Matchers {
implicit val system: ActorSystem = ActorSystem("baeldung")

"The parse flow" should "parse pairs of integers" in {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import akka.actor.testkit.typed.scaladsl.ActorTestKit

class TestService extends AnyWordSpec with BeforeAndAfterAll with Matchers {
class TestServiceUnitTest
extends AnyWordSpec
with BeforeAndAfterAll
with Matchers {
val testKit = ActorTestKit()
implicit val system = testKit.system

Expand Down
Loading