SpannableStringTest.kt revision d8fad98b94940d1a1657bb44366f3305bbcc7203
1/* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package androidx.text 18 19import android.graphics.Typeface.BOLD 20import android.text.SpannableString 21import android.text.style.StyleSpan 22import android.text.style.UnderlineSpan 23import org.junit.Assert.assertEquals 24import org.junit.Assert.assertTrue 25import org.junit.Test 26 27class SpannableStringTest { 28 29 @Test fun toSpannableString() = assertTrue("Hello, World".toSpannable() is SpannableString) 30 31 @Test fun plusAssign() { 32 val s = "Hello, World".toSpannable() 33 assertTrue(s.getSpans<Any>().isEmpty()) 34 s += StyleSpan(BOLD) 35 assertTrue(s.getSpans<Any>().isNotEmpty()) 36 } 37 38 @Test fun minusAssign() { 39 val s = "Hello, World".toSpannable() 40 val bold = StyleSpan(BOLD) 41 s += bold 42 assertTrue(s.getSpans<Any>().isNotEmpty()) 43 s -= bold 44 assertTrue(s.getSpans<Any>().isEmpty()) 45 } 46 47 @Test fun clearSpans() { 48 val s = "Hello, World".toSpannable() 49 s += StyleSpan(BOLD) 50 s += UnderlineSpan() 51 assertTrue(s.getSpans<Any>().isNotEmpty()) 52 s.clearSpans() 53 assertTrue(s.getSpans<Any>().isEmpty()) 54 } 55 56 @Test fun setIndices() { 57 val s = "Hello, World".toSpannable() 58 s[0, 5] = StyleSpan(BOLD) 59 s[7, 12] = UnderlineSpan() 60 61 val spans = s.getSpans<Any>() 62 63 val bold = spans.filterIsInstance<StyleSpan>().single() 64 assertEquals(0, s.getSpanStart(bold)) 65 assertEquals(5, s.getSpanEnd(bold)) 66 67 val underline = spans.filterIsInstance<UnderlineSpan>().single() 68 assertEquals(7, s.getSpanStart(underline)) 69 assertEquals(12, s.getSpanEnd(underline)) 70 } 71 72 @Test fun setRange() { 73 val s = "Hello, World".toSpannable() 74 s[0..5] = StyleSpan(BOLD) 75 s[7..12] = UnderlineSpan() 76 77 val spans = s.getSpans<Any>() 78 79 val bold = spans.filterIsInstance<StyleSpan>().single() 80 assertEquals(0, s.getSpanStart(bold)) 81 assertEquals(5, s.getSpanEnd(bold)) 82 83 val underline = spans.filterIsInstance<UnderlineSpan>().single() 84 assertEquals(7, s.getSpanStart(underline)) 85 assertEquals(12, s.getSpanEnd(underline)) 86 } 87} 88