|
| 1 | + |
| 2 | +package scala.io |
| 3 | + |
| 4 | +import org.junit.Test |
| 5 | +import org.junit.Assert._ |
| 6 | +import org.junit.runner.RunWith |
| 7 | +import org.junit.runners.JUnit4 |
| 8 | + |
| 9 | +import scala.tools.testing.AssertUtil._ |
| 10 | + |
| 11 | +import java.io.{ Console => _, _ } |
| 12 | + |
| 13 | +@RunWith(classOf[JUnit4]) |
| 14 | +class SourceTest { |
| 15 | + |
| 16 | + private implicit val `our codec` = Codec.UTF8 |
| 17 | + private val charSet = Codec.UTF8.charSet.name |
| 18 | + |
| 19 | + private def sampler = """ |
| 20 | + |Big-endian and little-endian approaches aren't |
| 21 | + |readily interchangeable in general, because the |
| 22 | + |laws of arithmetic send signals leftward from |
| 23 | + |the bits that are "least significant." |
| 24 | + |""".stripMargin.trim |
| 25 | + |
| 26 | + private def in = new ByteArrayInputStream(sampler.getBytes) |
| 27 | + |
| 28 | + @Test def canIterateLines() = { |
| 29 | + assertEquals(sampler.lines.size, (Source fromString sampler).getLines.size) |
| 30 | + } |
| 31 | + @Test def canCustomizeReporting() = { |
| 32 | + class CapitalReporting(is: InputStream) extends BufferedSource(is) { |
| 33 | + override def report(pos: Int, msg: String, out: PrintStream): Unit = { |
| 34 | + out print f"$pos%04x: ${msg.toUpperCase}" |
| 35 | + } |
| 36 | + class OffsetPositioner extends Positioner(null) { |
| 37 | + override def next(): Char = { |
| 38 | + ch = iter.next() |
| 39 | + pos = pos + 1 |
| 40 | + ch |
| 41 | + } |
| 42 | + } |
| 43 | + withPositioning(new OffsetPositioner) |
| 44 | + } |
| 45 | + val s = new CapitalReporting(in) |
| 46 | + // skip to next line and report an error |
| 47 | + do { |
| 48 | + val c = s.next() |
| 49 | + } while (s.ch != '\n') |
| 50 | + s.next() |
| 51 | + val out = new ByteArrayOutputStream |
| 52 | + val ps = new PrintStream(out, true, charSet) |
| 53 | + s.reportError(s.pos, "That doesn't sound right.", ps) |
| 54 | + assertEquals("0030: THAT DOESN'T SOUND RIGHT.", out.toString(charSet)) |
| 55 | + } |
| 56 | +} |
0 commit comments