Initial commit of HermesControl Android app
This commit is contained in:
commit
d6ff3de594
92 files changed
+10004
No files matched your search
@@ -0,0 +1,134 @@
|
||||
package com.m57.hermescontrol.data.local
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.security.crypto.EncryptedSharedPreferences
|
||||
import androidx.security.crypto.MasterKey
|
||||
import io.mockk.*
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class AuthManagerTest {
|
||||
private lateinit var mockPrefs: SharedPreferences
|
||||
private lateinit var mockEditor: SharedPreferences.Editor
|
||||
private lateinit var mockContext: Context
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
mockPrefs = mockk(relaxed = true)
|
||||
mockEditor = mockk(relaxed = true)
|
||||
mockContext = mockk(relaxed = true)
|
||||
|
||||
every { mockPrefs.edit() } returns mockEditor
|
||||
every { mockEditor.putString(any(), any()) } returns mockEditor
|
||||
every { mockEditor.putInt(any(), any()) } returns mockEditor
|
||||
every { mockEditor.putBoolean(any(), any()) } returns mockEditor
|
||||
|
||||
// Mock EncryptedSharedPreferences static methods
|
||||
mockkStatic(EncryptedSharedPreferences::class)
|
||||
every {
|
||||
EncryptedSharedPreferences.create(
|
||||
any<Context>(),
|
||||
any<String>(),
|
||||
any<MasterKey>(),
|
||||
any<EncryptedSharedPreferences.PrefKeyEncryptionScheme>(),
|
||||
any<EncryptedSharedPreferences.PrefValueEncryptionScheme>(),
|
||||
)
|
||||
} returns mockPrefs
|
||||
|
||||
// Mock MasterKey.Builder constructor and its build method
|
||||
mockkConstructor(MasterKey.Builder::class)
|
||||
val mockMasterKey = mockk<MasterKey>(relaxed = true)
|
||||
every { anyConstructed<MasterKey.Builder>().build() } returns mockMasterKey
|
||||
|
||||
// Reset prefs singleton instance using reflection
|
||||
val field = AuthManager::class.java.getDeclaredField("prefs")
|
||||
field.isAccessible = true
|
||||
field.set(AuthManager, null)
|
||||
|
||||
// Initialise AuthManager
|
||||
AuthManager.init(mockContext)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
unmockkAll()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetAndSetToken() {
|
||||
every { mockPrefs.getString("auth_token", null) } returns "my_secret_token"
|
||||
assertEquals("my_secret_token", AuthManager.getToken())
|
||||
|
||||
AuthManager.setToken("new_token")
|
||||
verify { mockEditor.putString("auth_token", "new_token") }
|
||||
verify { mockEditor.apply() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetAndSetToken_null() {
|
||||
every { mockPrefs.getString("auth_token", null) } returns null
|
||||
assertNull(AuthManager.getToken())
|
||||
|
||||
AuthManager.setToken(null)
|
||||
verify { mockEditor.putString("auth_token", null) }
|
||||
verify { mockEditor.apply() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetAndSetHost() {
|
||||
every { mockPrefs.getString("host", "127.0.0.1") } returns "192.168.1.1"
|
||||
assertEquals("192.168.1.1", AuthManager.getHost())
|
||||
|
||||
AuthManager.setHost("10.0.0.1")
|
||||
verify { mockEditor.putString("host", "10.0.0.1") }
|
||||
verify { mockEditor.apply() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetAndSetPort() {
|
||||
every { mockPrefs.getInt("port", 9119) } returns 8080
|
||||
assertEquals(8080, AuthManager.getPort())
|
||||
|
||||
AuthManager.setPort(9090)
|
||||
verify { mockEditor.putInt("port", 9090) }
|
||||
verify { mockEditor.apply() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetAndSetAutoReconnect() {
|
||||
every { mockPrefs.getBoolean("auto_reconnect", true) } returns false
|
||||
assertEquals(false, AuthManager.isAutoReconnect())
|
||||
|
||||
AuthManager.setAutoReconnect(true)
|
||||
verify { mockEditor.putBoolean("auto_reconnect", true) }
|
||||
verify { mockEditor.apply() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testBaseUrl() {
|
||||
every { mockPrefs.getString("host", "127.0.0.1") } returns "hermes.local"
|
||||
every { mockPrefs.getInt("port", 9119) } returns 1234
|
||||
assertEquals("http://hermes.local:1234/", AuthManager.baseUrl())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWsUrl() {
|
||||
every { mockPrefs.getString("host", "127.0.0.1") } returns "hermes.local"
|
||||
every { mockPrefs.getInt("port", 9119) } returns 1234
|
||||
every { mockPrefs.getString("auth_token", null) } returns "token123"
|
||||
assertEquals("ws://hermes.local:1234/api/ws?token=token123", AuthManager.wsUrl())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testWsUrl_nullToken() {
|
||||
every { mockPrefs.getString("host", "127.0.0.1") } returns "hermes.local"
|
||||
every { mockPrefs.getInt("port", 9119) } returns 1234
|
||||
every { mockPrefs.getString("auth_token", null) } returns null
|
||||
assertEquals("ws://hermes.local:1234/api/ws?token=", AuthManager.wsUrl())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package com.m57.hermescontrol.data.model
|
||||
|
||||
import com.google.gson.Gson
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertNotNull
|
||||
import org.junit.jupiter.api.Assertions.assertNull
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ModelSerializationTest {
|
||||
private val gson = Gson()
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_allFields() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": "weather",
|
||||
"description": "Get current weather info",
|
||||
"category": "utility",
|
||||
"enabled": true
|
||||
}
|
||||
""".trimIndent()
|
||||
val skill = gson.fromJson(json, Skill::class.java)
|
||||
assertEquals("weather", skill.name)
|
||||
assertEquals("Get current weather info", skill.description)
|
||||
assertEquals("utility", skill.category)
|
||||
assertEquals(true, skill.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_optionalFieldsNull() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": "light_control",
|
||||
"description": null,
|
||||
"category": null,
|
||||
"enabled": false
|
||||
}
|
||||
""".trimIndent()
|
||||
val skill = gson.fromJson(json, Skill::class.java)
|
||||
assertEquals("light_control", skill.name)
|
||||
assertNull(skill.description)
|
||||
assertNull(skill.category)
|
||||
assertEquals(false, skill.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCronJobDeserialization_allFields() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"id": "job-123",
|
||||
"name": "Daily Backup",
|
||||
"schedule": "0 0 * * *",
|
||||
"state": "active",
|
||||
"last_run_status": "success",
|
||||
"next_run": "2026-06-16T00:00:00Z"
|
||||
}
|
||||
""".trimIndent()
|
||||
val job = gson.fromJson(json, CronJob::class.java)
|
||||
assertEquals("job-123", job.id)
|
||||
assertEquals("Daily Backup", job.name)
|
||||
assertEquals("0 0 * * *", job.schedule)
|
||||
assertEquals("active", job.state)
|
||||
assertEquals("success", job.last_run_status)
|
||||
assertEquals("2026-06-16T00:00:00Z", job.next_run)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCronJobDeserialization_optionalFieldsNull() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"id": "job-456",
|
||||
"name": "One-off Task",
|
||||
"schedule": null,
|
||||
"state": null,
|
||||
"last_run_status": null,
|
||||
"next_run": null
|
||||
}
|
||||
""".trimIndent()
|
||||
val job = gson.fromJson(json, CronJob::class.java)
|
||||
assertEquals("job-456", job.id)
|
||||
assertEquals("One-off Task", job.name)
|
||||
assertNull(job.schedule)
|
||||
assertNull(job.state)
|
||||
assertNull(job.last_run_status)
|
||||
assertNull(job.next_run)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToggleSkillRequestSerialization() {
|
||||
val request = ToggleSkillRequest(name = "weather", enabled = false)
|
||||
val json = gson.toJson(request)
|
||||
// Ensure serialization produces correct JSON structure
|
||||
val parsed = gson.fromJson(json, Map::class.java)
|
||||
assertEquals("weather", parsed["name"])
|
||||
assertEquals(false, parsed["enabled"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_missingRequiredFields() {
|
||||
val json = "{}"
|
||||
val skill = gson.fromJson(json, Skill::class.java)
|
||||
// Verify null-safety issue: Gson allows non-nullable 'name' to be null at runtime
|
||||
assertNull(skill.name)
|
||||
// Primitive boolean defaults to false in Gson/JVM when missing
|
||||
assertEquals(false, skill.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_explicitNullForNonNullable() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": null,
|
||||
"enabled": null
|
||||
}
|
||||
""".trimIndent()
|
||||
val skill = gson.fromJson(json, Skill::class.java)
|
||||
assertNull(skill.name)
|
||||
assertEquals(false, skill.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCronJobDeserialization_missingRequiredFields() {
|
||||
val json = "{}"
|
||||
val job = gson.fromJson(json, CronJob::class.java)
|
||||
assertNull(job.id)
|
||||
assertNull(job.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSessionListResponseDeserialization_missingRequiredFields() {
|
||||
val json = "{}"
|
||||
val response = gson.fromJson(json, SessionListResponse::class.java)
|
||||
assertNull(response.sessions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSessionInfoDeserialization_missingRequiredFields() {
|
||||
val json = "{}"
|
||||
val info = gson.fromJson(json, SessionInfo::class.java)
|
||||
assertNull(info.id)
|
||||
assertNull(info.title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSessionMessagesResponseDeserialization_missingRequiredFields() {
|
||||
val json = "{}"
|
||||
val response = gson.fromJson(json, SessionMessagesResponse::class.java)
|
||||
assertNull(response.messages)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_malformedJson() {
|
||||
val json = "{\"name\": \"weather\","
|
||||
org.junit.jupiter.api.Assertions.assertThrows(com.google.gson.JsonSyntaxException::class.java) {
|
||||
gson.fromJson(json, Skill::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_typeMismatchObject() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": "weather",
|
||||
"enabled": {}
|
||||
}
|
||||
""".trimIndent()
|
||||
org.junit.jupiter.api.Assertions.assertThrows(com.google.gson.JsonSyntaxException::class.java) {
|
||||
gson.fromJson(json, Skill::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_typeMismatchArray() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": "weather",
|
||||
"enabled": []
|
||||
}
|
||||
""".trimIndent()
|
||||
org.junit.jupiter.api.Assertions.assertThrows(com.google.gson.JsonSyntaxException::class.java) {
|
||||
gson.fromJson(json, Skill::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_missingName_causesNullOnNonNullableField() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"description": "Get current weather info",
|
||||
"category": "utility",
|
||||
"enabled": true
|
||||
}
|
||||
""".trimIndent()
|
||||
val skill = gson.fromJson(json, Skill::class.java)
|
||||
// Gson bypasses Kotlin null-safety constraints, resulting in null on non-nullable field
|
||||
val nameNullable: String? = skill.name
|
||||
assertNull(nameNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_nullName_causesNullOnNonNullableField() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": null,
|
||||
"description": "Get current weather info",
|
||||
"category": "utility",
|
||||
"enabled": true
|
||||
}
|
||||
""".trimIndent()
|
||||
val skill = gson.fromJson(json, Skill::class.java)
|
||||
val nameNullable: String? = skill.name
|
||||
assertNull(nameNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSkillDeserialization_missingEnabled_usesJvmDefaultValue() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": "weather",
|
||||
"description": "Get current weather info",
|
||||
"category": "utility"
|
||||
}
|
||||
""".trimIndent()
|
||||
val skill = gson.fromJson(json, Skill::class.java)
|
||||
// Boolean primitive defaults to false
|
||||
assertEquals(false, skill.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCronJobDeserialization_missingId_causesNullOnNonNullableField() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"name": "Daily Backup",
|
||||
"schedule": "0 0 * * *",
|
||||
"state": "active"
|
||||
}
|
||||
""".trimIndent()
|
||||
val job = gson.fromJson(json, CronJob::class.java)
|
||||
val idNullable: String? = job.id
|
||||
assertNull(idNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSessionListResponseDeserialization_missingSessions_causesNullOnNonNullableField() {
|
||||
val json = "{}"
|
||||
val response = gson.fromJson(json, SessionListResponse::class.java)
|
||||
val sessionsNullable: List<SessionInfo>? = response.sessions
|
||||
assertNull(sessionsNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSessionInfoDeserialization_missingId_causesNullOnNonNullableField() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"title": "My Session",
|
||||
"created_at": "2026-06-15T12:00:00Z"
|
||||
}
|
||||
""".trimIndent()
|
||||
val info = gson.fromJson(json, SessionInfo::class.java)
|
||||
val idNullable: String? = info.id
|
||||
assertNull(idNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSessionMessagesResponseDeserialization_missingMessages_causesNullOnNonNullableField() {
|
||||
val json = "{}"
|
||||
val response = gson.fromJson(json, SessionMessagesResponse::class.java)
|
||||
val messagesNullable: List<SessionMessage>? = response.messages
|
||||
assertNull(messagesNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDeserialization_malformedJson_throwsJsonSyntaxException() {
|
||||
val json = """{"name": "weather", "enabled": """
|
||||
org.junit.jupiter.api.Assertions.assertThrows(com.google.gson.JsonSyntaxException::class.java) {
|
||||
gson.fromJson(json, Skill::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testStatusResponseDeserialization_allFields() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"gateway_running": true,
|
||||
"active_sessions": 5,
|
||||
"auth_required": false,
|
||||
"gateway_platforms": {
|
||||
"platform1": {
|
||||
"state": "connected",
|
||||
"error_code": null
|
||||
},
|
||||
"platform2": {
|
||||
"state": "error",
|
||||
"error_code": "ERR_CONN"
|
||||
}
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
val response = gson.fromJson(json, StatusResponse::class.java)
|
||||
assertEquals("1.0.0", response.version)
|
||||
assertEquals(true, response.gateway_running)
|
||||
assertEquals(5, response.active_sessions)
|
||||
assertEquals(false, response.auth_required)
|
||||
assertEquals(2, response.gateway_platforms?.size)
|
||||
assertEquals("connected", response.gateway_platforms?.get("platform1")?.state)
|
||||
assertNull(response.gateway_platforms?.get("platform1")?.error_code)
|
||||
assertEquals("error", response.gateway_platforms?.get("platform2")?.state)
|
||||
assertEquals("ERR_CONN", response.gateway_platforms?.get("platform2")?.error_code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testStatusResponseDeserialization_missingFields() {
|
||||
val json = "{}"
|
||||
val response = gson.fromJson(json, StatusResponse::class.java)
|
||||
assertNull(response.version)
|
||||
assertNull(response.gateway_running)
|
||||
assertNull(response.active_sessions)
|
||||
assertNull(response.auth_required)
|
||||
assertNull(response.gateway_platforms)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testStatusResponseDeserialization_gatewayPlatformsNullValue() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"gateway_platforms": {
|
||||
"android": null,
|
||||
"ios": {
|
||||
"state": null
|
||||
}
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
val response = gson.fromJson(json, StatusResponse::class.java)
|
||||
val platforms = response.gateway_platforms
|
||||
assertNotNull(platforms)
|
||||
assertNull(platforms!!["android"])
|
||||
val iosPlatform = platforms["ios"]
|
||||
assertNotNull(iosPlatform)
|
||||
assertNull(iosPlatform!!.state)
|
||||
assertNull(iosPlatform.error_code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testStatusResponseDeserialization_typeMismatchInGatewayPlatforms() {
|
||||
val json =
|
||||
"""
|
||||
{
|
||||
"gateway_platforms": "not_a_map"
|
||||
}
|
||||
""".trimIndent()
|
||||
org.junit.jupiter.api.Assertions.assertThrows(com.google.gson.JsonSyntaxException::class.java) {
|
||||
gson.fromJson(json, StatusResponse::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSystemStatsResponse_cpuPercentTypeSafety() {
|
||||
val jsonNumber = """{"cpu":{"percent":45.2}}"""
|
||||
val responseNumber = gson.fromJson(jsonNumber, SystemStatsResponse::class.java)
|
||||
assertEquals(45.2, responseNumber.cpuPercent)
|
||||
|
||||
val jsonStringNum = """{"cpu":{"percent":"45.2"}}"""
|
||||
val responseStringNum = gson.fromJson(jsonStringNum, SystemStatsResponse::class.java)
|
||||
assertNull(responseStringNum.cpuPercent)
|
||||
|
||||
val jsonNullPercent = """{"cpu":{"percent":null}}"""
|
||||
val responseNullPercent = gson.fromJson(jsonNullPercent, SystemStatsResponse::class.java)
|
||||
assertNull(responseNullPercent.cpuPercent)
|
||||
|
||||
val jsonMissingPercent = """{"cpu":{}}"""
|
||||
val responseMissingPercent = gson.fromJson(jsonMissingPercent, SystemStatsResponse::class.java)
|
||||
assertNull(responseMissingPercent.cpuPercent)
|
||||
|
||||
val jsonNullCpu = """{"cpu":null}"""
|
||||
val responseNullCpu = gson.fromJson(jsonNullCpu, SystemStatsResponse::class.java)
|
||||
assertNull(responseNullCpu.cpuPercent)
|
||||
|
||||
val jsonMissingCpu = "{}"
|
||||
val responseMissingCpu = gson.fromJson(jsonMissingCpu, SystemStatsResponse::class.java)
|
||||
assertNull(responseMissingCpu.cpuPercent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToggleSkillRequestDeserialization_missingRequiredFields() {
|
||||
val json = """{"enabled":true}"""
|
||||
val request = gson.fromJson(json, ToggleSkillRequest::class.java)
|
||||
val nameNullable: String? = request.name
|
||||
assertNull(nameNullable)
|
||||
assertEquals(true, request.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToggleSkillRequestDeserialization_explicitNull() {
|
||||
val json = """{"name":null,"enabled":null}"""
|
||||
val request = gson.fromJson(json, ToggleSkillRequest::class.java)
|
||||
val nameNullable: String? = request.name
|
||||
assertNull(nameNullable)
|
||||
assertEquals(false, request.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToggleSkillRequestSerialization_withNullName() {
|
||||
val jsonInput = """{"name":null,"enabled":true}"""
|
||||
val request = gson.fromJson(jsonInput, ToggleSkillRequest::class.java)
|
||||
|
||||
val jsonOutput = gson.toJson(request)
|
||||
val parsed = gson.fromJson(jsonOutput, Map::class.java)
|
||||
assertFalse(parsed.containsKey("name"))
|
||||
assertEquals(true, parsed["enabled"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package com.m57.hermescontrol.data.remote
|
||||
|
||||
import com.m57.hermescontrol.data.model.ToggleSkillRequest
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertNotNull
|
||||
import org.junit.jupiter.api.Assertions.assertNull
|
||||
import org.junit.jupiter.api.Assertions.assertThrows
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
|
||||
class HermesApiServiceTest {
|
||||
private lateinit var mockWebServer: MockWebServer
|
||||
private lateinit var apiService: HermesApiService
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
mockWebServer = MockWebServer()
|
||||
mockWebServer.start()
|
||||
|
||||
val retrofit =
|
||||
Retrofit
|
||||
.Builder()
|
||||
.baseUrl(mockWebServer.url("/"))
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build()
|
||||
|
||||
apiService = retrofit.create(HermesApiService::class.java)
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun tearDown() {
|
||||
mockWebServer.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSkills_requestsCorrectUrlAndMethod() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""[{"name":"weather","description":"info","category":"utils","enabled":true}]"""),
|
||||
)
|
||||
|
||||
val response = apiService.getSkills()
|
||||
assertTrue(response.isSuccessful)
|
||||
assertEquals(1, response.body()?.size)
|
||||
assertEquals("weather", response.body()?.get(0)?.name)
|
||||
|
||||
val recordedRequest = mockWebServer.takeRequest()
|
||||
assertEquals("/api/skills", recordedRequest.path)
|
||||
assertEquals("GET", recordedRequest.method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testToggleSkill_postsCorrectBody() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody(""),
|
||||
)
|
||||
|
||||
val response = apiService.toggleSkill(ToggleSkillRequest(name = "weather", enabled = true))
|
||||
assertTrue(response.isSuccessful)
|
||||
|
||||
val recordedRequest = mockWebServer.takeRequest()
|
||||
assertEquals("/api/skills/toggle", recordedRequest.path)
|
||||
assertEquals("PUT", recordedRequest.method)
|
||||
assertEquals("""{"name":"weather","enabled":true}""", recordedRequest.body.readUtf8())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetCronJobs_requestsCorrectUrlAndMethod() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody(
|
||||
"""[{"id":"job_1","name":"backup","schedule":"* * * * *","state":"active","last_run_status":null,"next_run":null}]""",
|
||||
),
|
||||
)
|
||||
|
||||
val response = apiService.getCronJobs()
|
||||
assertTrue(response.isSuccessful)
|
||||
assertEquals(1, response.body()?.size)
|
||||
assertEquals("job_1", response.body()?.get(0)?.id)
|
||||
|
||||
val recordedRequest = mockWebServer.takeRequest()
|
||||
assertEquals("/api/cron/jobs", recordedRequest.path)
|
||||
assertEquals("GET", recordedRequest.method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testPauseCronJob_sendsPostRequest() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody(""))
|
||||
|
||||
val response = apiService.pauseCronJob("job_1")
|
||||
assertTrue(response.isSuccessful)
|
||||
|
||||
val recordedRequest = mockWebServer.takeRequest()
|
||||
assertEquals("/api/cron/jobs/job_1/pause", recordedRequest.path)
|
||||
assertEquals("POST", recordedRequest.method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testResumeCronJob_sendsPostRequest() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody(""))
|
||||
|
||||
val response = apiService.resumeCronJob("job_1")
|
||||
assertTrue(response.isSuccessful)
|
||||
|
||||
val recordedRequest = mockWebServer.takeRequest()
|
||||
assertEquals("/api/cron/jobs/job_1/resume", recordedRequest.path)
|
||||
assertEquals("POST", recordedRequest.method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testTriggerCronJob_sendsPostRequest() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody(""))
|
||||
|
||||
val response = apiService.triggerCronJob("job_1")
|
||||
assertTrue(response.isSuccessful)
|
||||
|
||||
val recordedRequest = mockWebServer.takeRequest()
|
||||
assertEquals("/api/cron/jobs/job_1/trigger", recordedRequest.path)
|
||||
assertEquals("POST", recordedRequest.method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDeleteCronJob_sendsDeleteRequest() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody(""))
|
||||
|
||||
val response = apiService.deleteCronJob("job_1")
|
||||
assertTrue(response.isSuccessful)
|
||||
|
||||
val recordedRequest = mockWebServer.takeRequest()
|
||||
assertEquals("/api/cron/jobs/job_1", recordedRequest.path)
|
||||
assertEquals("DELETE", recordedRequest.method)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSkills_missingFieldsInResponse() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""[{"description":"info"}]"""),
|
||||
)
|
||||
|
||||
val response = apiService.getSkills()
|
||||
assertTrue(response.isSuccessful)
|
||||
val skills = response.body()
|
||||
assertEquals(1, skills?.size)
|
||||
val skill = skills?.get(0)
|
||||
org.junit.jupiter.api.Assertions
|
||||
.assertNull(skill?.name)
|
||||
assertEquals(false, skill?.enabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetCronJobs_missingFieldsInResponse() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""[{"schedule":"* * * * *"}]"""),
|
||||
)
|
||||
|
||||
val response = apiService.getCronJobs()
|
||||
assertTrue(response.isSuccessful)
|
||||
val jobs = response.body()
|
||||
assertEquals(1, jobs?.size)
|
||||
val job = jobs?.get(0)
|
||||
org.junit.jupiter.api.Assertions
|
||||
.assertNull(job?.id)
|
||||
org.junit.jupiter.api.Assertions
|
||||
.assertNull(job?.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSessions_missingSessionsField() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""{}"""),
|
||||
)
|
||||
|
||||
val response = apiService.getSessions()
|
||||
assertTrue(response.isSuccessful)
|
||||
org.junit.jupiter.api.Assertions
|
||||
.assertNull(response.body()?.sessions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSessionMessages_apiReturnsMalformedJson_throwsException() {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""{"messages": ["""),
|
||||
)
|
||||
|
||||
assertThrows(java.io.EOFException::class.java) {
|
||||
runTest {
|
||||
apiService.getSessionMessages("session_1")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSessionMessages_missingMessagesField() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""{}"""),
|
||||
)
|
||||
|
||||
val response = apiService.getSessionMessages("session_1")
|
||||
assertTrue(response.isSuccessful)
|
||||
org.junit.jupiter.api.Assertions
|
||||
.assertNull(response.body()?.messages)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSkills_malformedJsonResponse_throwsException() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""[{"name":"weather""""),
|
||||
)
|
||||
|
||||
org.junit.jupiter.api.Assertions.assertThrows(java.io.EOFException::class.java) {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
apiService.getSkills()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSkills_typeMismatchInResponse_throwsException() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""[{"name":"weather","enabled":{}}]"""),
|
||||
)
|
||||
|
||||
org.junit.jupiter.api.Assertions.assertThrows(com.google.gson.JsonSyntaxException::class.java) {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
apiService.getSkills()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetStatus_missingFieldsInResponse() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("{}"),
|
||||
)
|
||||
|
||||
val response = apiService.getStatus()
|
||||
assertTrue(response.isSuccessful)
|
||||
val status = response.body()
|
||||
assertNotNull(status)
|
||||
assertNull(status?.version)
|
||||
assertNull(status?.gateway_running)
|
||||
assertNull(status?.active_sessions)
|
||||
assertNull(status?.auth_required)
|
||||
assertNull(status?.gateway_platforms)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetStatus_gatewayPlatformsNullValue() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""{"gateway_platforms": {"android": null}}"""),
|
||||
)
|
||||
|
||||
val response = apiService.getStatus()
|
||||
assertTrue(response.isSuccessful)
|
||||
val status = response.body()
|
||||
assertNotNull(status)
|
||||
val platforms = status?.gateway_platforms
|
||||
assertNotNull(platforms)
|
||||
assertNull(platforms!!["android"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSystemStats_missingFields() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("{}"),
|
||||
)
|
||||
|
||||
val response = apiService.getSystemStats()
|
||||
assertTrue(response.isSuccessful)
|
||||
val stats = response.body()
|
||||
assertNotNull(stats)
|
||||
assertNull(stats?.cpuPercent)
|
||||
assertNull(stats?.memoryPercent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSystemStats_nonNumericPercent_returnsNull() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""{"cpu":{"percent":"not_a_number"}}"""),
|
||||
)
|
||||
|
||||
val response = apiService.getSystemStats()
|
||||
assertTrue(response.isSuccessful)
|
||||
val stats = response.body()
|
||||
assertNotNull(stats)
|
||||
assertNull(stats?.cpuPercent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSystemStats_typeMismatchArray_behavior() =
|
||||
runTest {
|
||||
mockWebServer.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(200)
|
||||
.setBody("""{"cpu": []}"""),
|
||||
)
|
||||
|
||||
val response = apiService.getSystemStats()
|
||||
assertTrue(response.isSuccessful)
|
||||
val stats = response.body()
|
||||
assertNotNull(stats)
|
||||
// Gson deserializes an empty array [] into an empty map {} for Map fields
|
||||
assertTrue(stats?.cpu?.isEmpty() == true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.m57.hermescontrol.data.ws
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class EventParserTest {
|
||||
@Test
|
||||
fun testParseRpcResult_returnsRpcResultEvent() {
|
||||
val response =
|
||||
JsonRpcResponse(
|
||||
jsonrpc = "2.0",
|
||||
id = "123",
|
||||
result = mapOf("status" to "success"),
|
||||
error = null,
|
||||
method = null,
|
||||
params = null,
|
||||
)
|
||||
val event = EventParser.parse(response)
|
||||
assertTrue(event is WsEvent.RpcResult)
|
||||
val rpcResult = event as WsEvent.RpcResult
|
||||
assertEquals("123", rpcResult.id)
|
||||
assertEquals(mapOf("status" to "success"), rpcResult.result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseRpcError_returnsRpcErrorEvent() {
|
||||
val error = JsonRpcError(code = -32600, message = "Invalid Request")
|
||||
val response =
|
||||
JsonRpcResponse(
|
||||
jsonrpc = "2.0",
|
||||
id = "456",
|
||||
result = null,
|
||||
error = error,
|
||||
method = null,
|
||||
params = null,
|
||||
)
|
||||
val event = EventParser.parse(response)
|
||||
assertTrue(event is WsEvent.RpcError)
|
||||
val rpcError = event as WsEvent.RpcError
|
||||
assertEquals("456", rpcError.id)
|
||||
assertEquals(-32600, rpcError.error.code)
|
||||
assertEquals("Invalid Request", rpcError.error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseGatewayReady_returnsGatewayReadyEvent() {
|
||||
val response =
|
||||
JsonRpcResponse(
|
||||
jsonrpc = "2.0",
|
||||
id = null,
|
||||
result = null,
|
||||
error = null,
|
||||
method = "event",
|
||||
params =
|
||||
mapOf(
|
||||
"type" to "gateway.ready",
|
||||
"payload" to mapOf("session_id" to "session-1"),
|
||||
),
|
||||
)
|
||||
val event = EventParser.parse(response)
|
||||
assertTrue(event is WsEvent.GatewayReady)
|
||||
val gatewayReady = event as WsEvent.GatewayReady
|
||||
assertEquals(mapOf("session_id" to "session-1"), gatewayReady.data)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseMessageToken_returnsMessageTokenEvent() {
|
||||
val response =
|
||||
JsonRpcResponse(
|
||||
jsonrpc = "2.0",
|
||||
id = null,
|
||||
result = null,
|
||||
error = null,
|
||||
method = "event",
|
||||
params =
|
||||
mapOf(
|
||||
"type" to "message.token",
|
||||
"payload" to mapOf("text" to "hello", "session_id" to "session-1"),
|
||||
),
|
||||
)
|
||||
val event = EventParser.parse(response)
|
||||
assertTrue(event is WsEvent.MessageToken)
|
||||
val tokenEvent = event as WsEvent.MessageToken
|
||||
assertEquals("hello", tokenEvent.token)
|
||||
assertEquals("session-1", tokenEvent.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseThinkingDelta_returnsThinkingDeltaEvent() {
|
||||
val response =
|
||||
JsonRpcResponse(
|
||||
jsonrpc = "2.0",
|
||||
id = null,
|
||||
result = null,
|
||||
error = null,
|
||||
method = "event",
|
||||
params =
|
||||
mapOf(
|
||||
"type" to "thinking.delta",
|
||||
"payload" to mapOf("text" to "thinking token", "session_id" to "session-2"),
|
||||
),
|
||||
)
|
||||
val event = EventParser.parse(response)
|
||||
assertTrue(event is WsEvent.ThinkingDelta)
|
||||
val deltaEvent = event as WsEvent.ThinkingDelta
|
||||
assertEquals("thinking token", deltaEvent.token)
|
||||
assertEquals("session-2", deltaEvent.sessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseClarifyRequest_returnsClarifyRequestEvent() {
|
||||
val response =
|
||||
JsonRpcResponse(
|
||||
jsonrpc = "2.0",
|
||||
id = null,
|
||||
result = null,
|
||||
error = null,
|
||||
method = "event",
|
||||
params =
|
||||
mapOf(
|
||||
"type" to "clarify.request",
|
||||
"payload" to
|
||||
mapOf(
|
||||
"text" to "Select option?",
|
||||
"options" to listOf("Yes", "No"),
|
||||
),
|
||||
),
|
||||
)
|
||||
val event = EventParser.parse(response)
|
||||
assertTrue(event is WsEvent.ClarifyRequest)
|
||||
val clarifyEvent = event as WsEvent.ClarifyRequest
|
||||
assertEquals("Select option?", clarifyEvent.text)
|
||||
assertEquals(listOf("Yes", "No"), clarifyEvent.options)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user