Fail when parsing invalid local date (#2134)

* Fail when parsing invalid local date

* Improve invalid date tests
This commit is contained in:
Marcono1234 2022-06-16 22:47:57 +02:00 committed by GitHub
parent 96ab171eb4
commit 57225c6741
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 8 deletions

View File

@ -2,7 +2,11 @@ package com.google.gson.internal.bind.util;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* Utilities methods for manipulating dates in iso8601 format. This is much much faster and GC friendly than using SimpleDateFormat so
@ -147,9 +151,10 @@ public class ISO8601Utils
// if the value has no time component (and no time zone), we are done
boolean hasT = checkOffset(date, offset, 'T');
if (!hasT && (date.length() <= offset)) {
Calendar calendar = new GregorianCalendar(year, month - 1, day);
calendar.setLenient(false);
pos.setIndex(offset);
return calendar.getTime();

View File

@ -1,13 +1,18 @@
package com.google.gson.internal.bind.util;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
public class ISO8601UtilsTest {
@ -61,6 +66,26 @@ public class ISO8601UtilsTest {
assertEquals(expectedDate, date);
}
@Test
public void testDateParseInvalidDay() {
String dateStr = "2022-12-33";
try {
ISO8601Utils.parse(dateStr, new ParsePosition(0));
fail("Expected parsing to fail");
} catch (ParseException expected) {
}
}
@Test
public void testDateParseInvalidMonth() {
String dateStr = "2022-14-30";
try {
ISO8601Utils.parse(dateStr, new ParsePosition(0));
fail("Expected parsing to fail");
} catch (ParseException expected) {
}
}
@Test
public void testDateParseWithTimezone() throws ParseException {
String dateStr = "2018-06-25T00:00:00-03:00";