### Question:
OpenTSDBHttpClient { void write(final String metricName, final String[] tags, final long timestamp, final String value) throws IOException { if (currentBatchSize++ > 0) { writer.write(','); } writer.write(METRIC); writeEscapedString(metricName); writer.write(','); writer.write(TIMESTAMP); writer.write(Long.toString((timestampsInMilliseconds ? timestamp : timestamp / 1_000))); writer.write(','); writer.write(TAGS); boolean toggle = true; for (int i = 0; i < tags.length; i++) { writeEscapedString(tags[i]); if (toggle) { writer.write(':'); } else if (i + 1 < tags.length) { writer.write(','); } toggle = !toggle; } writer.write('}'); writer.write(','); writer.write(VALUE); writer.write(value); writer.write('}'); if (currentBatchSize >= batchSize) { flush(); } } OpenTSDBHttpClient(final URI dbUri, int batchSize, boolean timestampsInMilliseconds);   }### Answer:
@Test public void testWriteSuccessfulAutoFlush() throws Exception { new Expectations() {{ httpClient.execute((HttpUriRequest) any); result = closeableHttpResponse; closeableHttpResponse.getStatusLine(); result = statusLine; statusLine.getStatusCode(); result = 204; }}; OpenTSDBHttpClient client = new OpenTSDBHttpClient(DUMMY_DB_URI, 1, true); String[] tags = {"host", "server01", "region", "us-west"}; client.write("cpu_load_short.temp", tags, 1534055562000000003L, "80"); assertEquals(0, client.currentBatchSize); client.write("cpu_load_short.fanSpeed", tags, 1534055562000000004L, "74.3"); assertEquals(0, client.currentBatchSize); }
@Test public void testWriteFailsManualFlush() throws Exception { new Expectations() {{ httpClient.execute((HttpUriRequest) any); result = closeableHttpResponse; closeableHttpResponse.getStatusLine(); result = statusLine; statusLine.getStatusCode(); result = 500; }}; OpenTSDBHttpClient client = new OpenTSDBHttpClient(DUMMY_DB_URI, 64, true); String[] tags = {"host", "server01", "region", "us-west"}; client.write("cpu_load_short.temp", tags, 1534055562000000003L, "80"); client.write("cpu_load_short.fanSpeed", tags, 1534055562000000004L, "74.3"); assertEquals(2, client.currentBatchSize); assertThrows(IllegalStateException.class, client::flush); assertEquals(0, client.currentBatchSize); }
@Test public void testEscapeStringControlChars() { OpenTSDBHttpClient c = new OpenTSDBHttpClient(DUMMY_DB_URI, 64, true); assertThrows(IllegalArgumentException.class, () -> c .write("test\nmetric", new String[]{"host", "web\\01", "colo", "phx"}, 1000000, "42.5")); }