소스 검색

Fixed notes type adapter

sirekanyan 8 년 전
부모
커밋
48cda8e21b

+ 3 - 3
app/src/main/java/me/vadik/knigopis/api/gson/NotesTypeAdapter.kt

@@ -7,20 +7,20 @@ import me.vadik.knigopis.model.Notes
 
 class NotesTypeAdapter : TypeAdapter<Notes>() {
 
-    private val regex = Regex("(.*) // (\\d+)%")
+    private val regex = Regex("(.*)// (\\d+)%")
 
     override fun write(output: JsonWriter, notes: Notes) {
         if (notes.progress == 0) {
             output.value(notes.text)
         } else {
-            output.value("${notes.text} // ${notes.progress}%")
+            output.value("${notes.text} // ${notes.progress}%".trim())
         }
     }
 
     override fun read(input: JsonReader): Notes {
         val fullText = input.nextString()
         return regex.matchEntire(fullText)?.let {
-            Notes(it.groupValues[1], it.groupValues[2].toInt())
+            Notes(it.groupValues[1].trim(), it.groupValues[2].toInt())
         } ?: Notes(fullText, 0)
     }
 }

+ 13 - 0
app/src/test/java/me/vadik/knigopis/api/gson/NotesTypeAdapterTest.kt

@@ -23,6 +23,12 @@ class NotesTypeAdapterTest {
         assertEquals("\"text\"", gson.toJson(notes))
     }
 
+    @Test
+    fun writeEmptyText() {
+        val notes = Notes("", 30)
+        assertEquals("\"// 30%\"", gson.toJson(notes))
+    }
+
     @Test
     fun read() {
         val notes = gson.fromJson("\"text // text // 25%\"", Notes::class.java)
@@ -36,4 +42,11 @@ class NotesTypeAdapterTest {
         assertEquals("text // text", notes.text)
         assertEquals(0, notes.progress)
     }
+
+    @Test
+    fun readEmptyText() {
+        val notes = gson.fromJson("\"// 30%\"", Notes::class.java)
+        assertEquals("", notes.text)
+        assertEquals(30, notes.progress)
+    }
 }