|
| 1 | +package org.kohsuke.github; |
| 2 | + |
| 3 | +import org.junit.Assert; |
| 4 | +import org.junit.Test; |
| 5 | + |
| 6 | +import java.text.SimpleDateFormat; |
| 7 | +import java.time.Instant; |
| 8 | +import java.time.temporal.ChronoUnit; |
| 9 | +import java.util.Date; |
| 10 | +import java.util.TimeZone; |
| 11 | + |
| 12 | +import static org.hamcrest.CoreMatchers.equalTo; |
| 13 | +import static org.hamcrest.CoreMatchers.not; |
| 14 | + |
| 15 | +/** |
| 16 | + * Unit test for {@link GitHub} static helpers. |
| 17 | + * |
| 18 | + * @author Liam Newman |
| 19 | + */ |
| 20 | +public class GitHubStaticTest extends Assert { |
| 21 | + |
| 22 | + @Test |
| 23 | + public void timeRoundTrip() throws Exception { |
| 24 | + Instant instantNow = Instant.now(); |
| 25 | + |
| 26 | + Date instantSeconds = Date.from(instantNow.truncatedTo(ChronoUnit.SECONDS)); |
| 27 | + Date instantMillis = Date.from(instantNow.truncatedTo(ChronoUnit.MILLIS)); |
| 28 | + |
| 29 | + // TODO: other formats |
| 30 | + String instantFormatSlash = formatDate(instantMillis, "yyyy/MM/dd HH:mm:ss ZZZZ"); |
| 31 | + String instantFormatDash = formatDate(instantMillis, "yyyy-MM-dd'T'HH:mm:ss'Z'"); |
| 32 | + String instantFormatMillis = formatDate(instantMillis, "yyyy-MM-dd'T'HH:mm:ss.S'Z'"); |
| 33 | + String instantSecondsFormatMillis = formatDate(instantSeconds, "yyyy-MM-dd'T'HH:mm:ss.S'Z'"); |
| 34 | + String instantBadFormat = formatDate(instantMillis, "yy-MM-dd'T'HH:mm'Z'"); |
| 35 | + |
| 36 | + |
| 37 | + assertThat(GitHub.parseDate(GitHub.printDate(instantSeconds)), |
| 38 | + equalTo(GitHub.parseDate(GitHub.printDate(instantMillis)))); |
| 39 | + |
| 40 | + assertThat(instantSeconds, |
| 41 | + equalTo(GitHub.parseDate(GitHub.printDate(instantSeconds)))); |
| 42 | + |
| 43 | + assertThat(instantMillis, |
| 44 | + not(equalTo(GitHub.parseDate(GitHub.printDate(instantMillis))))); |
| 45 | + |
| 46 | + assertThat(instantSeconds, |
| 47 | + equalTo(GitHub.parseDate(instantFormatSlash))); |
| 48 | + |
| 49 | + assertThat(instantSeconds, |
| 50 | + equalTo(GitHub.parseDate(instantFormatDash))); |
| 51 | + |
| 52 | + assertThat(instantMillis, |
| 53 | + equalTo(GitHub.parseDate(instantFormatMillis))); |
| 54 | + |
| 55 | + assertThat(instantSeconds, |
| 56 | + equalTo(GitHub.parseDate(instantSecondsFormatMillis))); |
| 57 | + |
| 58 | + try { |
| 59 | + GitHub.parseDate(instantBadFormat); |
| 60 | + fail("Bad time format should throw."); |
| 61 | + } catch (IllegalStateException e) { |
| 62 | + assertThat(e.getMessage(), equalTo("Unable to parse the timestamp: " + instantBadFormat)); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + static String formatDate(Date dt, String format) { |
| 67 | + SimpleDateFormat df = new SimpleDateFormat(format); |
| 68 | + df.setTimeZone(TimeZone.getTimeZone("GMT")); |
| 69 | + return df.format(dt); |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments