Skip to content

Commit

Permalink
The changes in this diff introduce several improvements to the codeba…
Browse files Browse the repository at this point in the history
…se, primarily focusing on code style, efficiency, and using Kotlin idioms more effectively. Let's break down the changes file by file:

**api/src/main/kotlin/app/utils/AppUtils.kt:**

* **Import Optimization:** The import for `StringUtils.stripAccents` is changed to a direct import of `stripAccents`, reducing unnecessary namespace qualification. This is a minor change but improves readability.
* **Kotlin Idiomatic `toJson`:** The `toJson` extension property is rewritten using `run`, making the code more concise and idiomatic Kotlin.
* **Direct `stripAccents` Call:**  Similar to the import change, the call to `StringUtils.stripAccents` within `nameToLogin` is simplified to a direct call to `stripAccents`.

**api/src/test/kotlin/users/TestTools.kt:**

* **Import Optimization:** Several wildcard imports are replaced with explicit imports, which is generally considered better practice for readability and avoiding potential naming conflicts.
* **Assertions:** The `Assertions` class from AssertJ is now used with direct function calls like `assertThat` instead of qualifying each assertion with `Assertions.assertThat`. This simplifies the assertions and makes the test code more readable.
* **Kotlin Idioms:** The code uses Kotlin idioms like `apply`, `let`, `run`, and `repeat` where appropriate, leading to more concise and expressive code. For example, the `equalsVerifier` function utilizes `apply` effectively to scope the instance and avoid repetition.

**api/src/test/kotlin/users/ServiceTests.kt:**

* **Suppress Warning:** The `RedundantUnitReturnType` warning suppression is added. This suggests that some functions that explicitly declared a `Unit` return type have been simplified to omit the redundant declaration.  This aligns with Kotlin's best practices.
* **Constant Imports:** Constants from the `Constants` object, like `DEVELOPMENT`, `PRODUCTION`, and `STARTUP_LOG_MSG_KEY`, are now imported directly, improving code clarity.
* **Injection:** The `@Autowired` annotation is replaced with `@Inject`, which is generally recommended for constructor injection in Kotlin.
* **Lateinit var and ObjectMapper:** The `mapper` and `validator` properties are removed.  `mapper` is now acquired directly within the `check toJson build a valid json format` test, using `context.getBean<ObjectMapper>()`. This makes the dependency explicit where it's used and potentially avoids unnecessary instantiation if the test isn't run.  `validator` isn't used in the provided diff.
* **Simplified String Building:**  The string building in the `ConfigurationsTests - MessageSource test message startupLog` test is made slightly more concise using string templates.
* **Kotlin Idioms:** Similar to `TestTools.kt`, Kotlin idioms like `run` and `let` are used to improve code conciseness and readability, particularly within test functions.
* **Data Class usage:** `OFFICIAL_SITE` from `TestUtils.Data` replaces the direct string reference, suggesting better organization of test data.
* **Removal of Unused Imports and Locale Usage:**  Unnecessary imports are removed, and the explicit `Locale.getDefault()` call is simplified to `getDefault()`, further improving code cleanliness.

Overall, these changes represent good refactoring work, making the code more readable, efficient, and idiomatic. The changes leverage Kotlin's features effectively and adhere to best practices.  The removal of seemingly unused variables and simplification of dependencies indicate a focus on cleaner code and potential performance gains.
  • Loading branch information
cheroliv committed Dec 10, 2024
1 parent 06278e0 commit 4a405c9
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 50 deletions.
6 changes: 3 additions & 3 deletions api/src/main/kotlin/app/utils/AppUtils.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package app.utils

import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils.stripAccents
import org.springframework.beans.factory.getBean
import org.springframework.context.ApplicationContext
import java.io.ByteArrayOutputStream
Expand All @@ -16,7 +16,7 @@ import kotlin.streams.asSequence

object AppUtils {
val Pair<Any, ApplicationContext>.toJson: String
get() = second.getBean<ObjectMapper>().writeValueAsString(first)
get() = first.run(second.getBean<ObjectMapper>()::writeValueAsString)

val KClass<Any>.objectName
get() = java.simpleName.run {
Expand All @@ -26,7 +26,7 @@ object AppUtils {
)
}

fun List<String>.nameToLogin(): List<String> = map { StringUtils.stripAccents(it.lowercase().replace(' ', '.')) }
fun List<String>.nameToLogin(): List<String> = map { stripAccents(it.lowercase().replace(' ', '.')) }

// fun String.cleanField(): String = StringBuilder(this)
// .deleteCharAt(0)
Expand Down
81 changes: 43 additions & 38 deletions api/src/test/kotlin/users/ServiceTests.kt
Original file line number Diff line number Diff line change
@@ -1,35 +1,36 @@
@file:Suppress("NonAsciiCharacters", "SqlResolve")
@file:Suppress("NonAsciiCharacters", "SqlResolve", "RedundantUnitReturnType")

package users

import app.Application
import app.utils.AppUtils.lsWorkingDir
import app.utils.AppUtils.lsWorkingDirProcess
import app.utils.AppUtils.toJson
import app.utils.Constants
import app.utils.Constants.DEVELOPMENT
import app.utils.Constants.PRODUCTION
import app.utils.Constants.STARTUP_LOG_MSG_KEY
import app.utils.Properties
import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.validation.Validator
import users.UserDao.Dao.countUsers
import users.UserDao.Dao.deleteAllUsersOnly
import users.security.UserRoleDao.Dao.countUserAuthority
import users.signup.SignupService
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.assertDoesNotThrow
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.getBean
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.ApplicationContext
import org.springframework.context.MessageSource
import org.springframework.test.context.ActiveProfiles
import users.TestUtils.Data.OFFICIAL_SITE
import users.TestUtils.Data.user
import users.UserDao.Dao.countUsers
import users.UserDao.Dao.deleteAllUsersOnly
import users.security.UserRoleDao.Dao.countUserAuthority
import users.signup.Signup
import workspace.Log
import users.signup.SignupService
import workspace.Log.i
import java.io.File
import java.nio.file.Paths
import java.util.*
import java.util.Locale.FRENCH
import java.util.Locale.getDefault
import javax.inject.Inject
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
Expand All @@ -41,60 +42,62 @@ import kotlin.test.assertEquals
)
class ServiceTests {

@Autowired
@Inject
lateinit var context: ApplicationContext

@AfterTest
fun cleanUp(context: ApplicationContext) = runBlocking { context.deleteAllUsersOnly() }

val mapper: ObjectMapper by lazy { context.getBean() }
val validator: Validator by lazy { context.getBean() }

@Test
fun `ConfigurationsTests - MessageSource test email_activation_greeting message fr`() = "artisan-logiciel".run {
assertEquals(
expected = "Cher $this",
actual = context
.getBean<MessageSource>()
.getMessage(
"email.activation.greeting",
arrayOf(this),
FRENCH
)
)
}
fun `ConfigurationsTests - MessageSource test email_activation_greeting message fr`() =
"artisan-logiciel".run {
assertEquals(
expected = "Cher $this",
actual = context
.getBean<MessageSource>()
.getMessage(
"email.activation.greeting",
arrayOf(this),
FRENCH
)
)
}


@Test
fun `ConfigurationsTests - MessageSource test message startupLog`() = context
.getBean<MessageSource>()
.getMessage(
Constants.STARTUP_LOG_MSG_KEY,
arrayOf(
Constants.DEVELOPMENT,
Constants.PRODUCTION
),
Locale.getDefault()
STARTUP_LOG_MSG_KEY,
arrayOf(DEVELOPMENT, PRODUCTION),
getDefault()
).run {
i(this)
assertEquals(buildString {
append("You have misconfigured your application!\n")
append("It should not run with both the ${Constants.DEVELOPMENT}\n")
append("and ${Constants.PRODUCTION} profiles at the same time.")
append("It should not run with both the $DEVELOPMENT\n")
append("and $PRODUCTION profiles at the same time.")
}, this)
}


@Test
fun `ConfigurationsTests - test go visit message`() =
assertEquals(
TestUtils.Data.OFFICIAL_SITE,
OFFICIAL_SITE,
context.getBean<Properties>().goVisitMessage
)

@Test
fun `test lsWorkingDir & lsWorkingDiringDirProcess`(): Unit {
fun `test lsWorkingDir & lsWorkingDirProcess`(): Unit {
val destDir: File = "build".run(::File)
context.lsWorkingDirProcess(destDir).run { "lsWorkingDirProcess : $this" }.run(Log::i)
File("build").absolutePath.run(Log::i)
context
.lsWorkingDirProcess(destDir)
.run { "lsWorkingDirProcess : $this" }
.run(::i)

destDir.absolutePath.run(::i)

// Liste un répertoire spécifié par une chaîne
context.lsWorkingDir("build", maxDepth = 2)
Expand All @@ -110,7 +113,9 @@ class ServiceTests {

@Test
fun `check toJson build a valid json format`(): Unit = assertDoesNotThrow {
(user to context).toJson.let(mapper::readTree)
(user to context)
.toJson
.let(context.getBean<ObjectMapper>()::readTree)
}
//TODO : Write and/or Test toMap, toUser

Expand Down
28 changes: 19 additions & 9 deletions api/src/test/kotlin/users/TestTools.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,30 @@ import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.hamcrest.Description
import org.hamcrest.TypeSafeDiagnosingMatcher
import org.springframework.boot.runApplication
import org.springframework.boot.web.reactive.context.StandardReactiveWebEnvironment
import org.springframework.context.ConfigurableApplicationContext
import workspace.Log
import workspace.Log.i
import java.io.IOException
import java.lang.Byte
import java.time.ZonedDateTime
import java.time.format.DateTimeParseException
import kotlin.Any
import kotlin.Boolean
import kotlin.ByteArray
import kotlin.Int
import kotlin.Pair
import kotlin.String
import kotlin.Throws
import kotlin.apply
import kotlin.let
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance
import kotlin.repeat
import kotlin.run

object TestTools {

Expand Down Expand Up @@ -395,17 +405,17 @@ object TestTools {
*/
fun <T : Any> equalsVerifier(clazz: KClass<T>) {
clazz.createInstance().apply i@{
Assertions.assertThat(toString()).isNotNull
Assertions.assertThat(this).isEqualTo(this)
Assertions.assertThat(hashCode()).isEqualTo(hashCode())
assertThat(toString()).isNotNull
assertThat(this).isEqualTo(this)
assertThat(hashCode()).isEqualTo(hashCode())
// Test with an instance of another class
Assertions.assertThat(this).isNotEqualTo(Any())
Assertions.assertThat(this).isNotEqualTo(null)
assertThat(this).isNotEqualTo(Any())
assertThat(this).isNotEqualTo(null)
// Test with an instance of the same class
clazz.createInstance().apply j@{
Assertions.assertThat(this@i).isNotEqualTo(this@j)
assertThat(this@i).isNotEqualTo(this@j)
// HashCodes are equals because the objects are not persisted yet
Assertions.assertThat(this@i.hashCode()).isEqualTo(this@j.hashCode())
assertThat(this@i.hashCode()).isEqualTo(this@j.hashCode())
}
}
}
Expand Down

0 comments on commit 4a405c9

Please sign in to comment.