function
stringlengths
61
9.1k
testmethod
stringlengths
42
143
location_fixed
stringlengths
43
98
end_buggy
int64
10
12k
location
stringlengths
43
98
function_name
stringlengths
4
73
source_buggy
stringlengths
655
442k
prompt_complete
stringlengths
433
4.3k
end_fixed
int64
10
12k
comment
stringlengths
0
763
bug_id
stringlengths
1
3
start_fixed
int64
7
12k
location_buggy
stringlengths
43
98
source_dir
stringclasses
5 values
prompt_chat
stringlengths
420
3.86k
start_buggy
int64
7
12k
classes_modified
sequence
task_id
stringlengths
64
64
function_signature
stringlengths
22
150
prompt_complete_without_signature
stringlengths
404
4.23k
project
stringclasses
17 values
indent
stringclasses
4 values
source_fixed
stringlengths
655
442k
public void testFormatWithoutPattern() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss")); String json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01X01:00:00'}"), json); }
com.fasterxml.jackson.databind.ser.DateSerializationTest::testFormatWithoutPattern
src/test/java/com/fasterxml/jackson/databind/ser/DateSerializationTest.java
316
src/test/java/com/fasterxml/jackson/databind/ser/DateSerializationTest.java
testFormatWithoutPattern
package com.fasterxml.jackson.databind.ser; import java.io.*; import java.text.*; import java.util.*; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.*; public class DateSerializationTest extends BaseMapTest { static class TimeZoneBean { private TimeZone tz; public TimeZoneBean(String name) { tz = TimeZone.getTimeZone(name); } public TimeZone getTz() { return tz; } } static class DateAsNumberBean { @JsonFormat(shape=JsonFormat.Shape.NUMBER) public Date date; public DateAsNumberBean(long l) { date = new java.util.Date(l); } } static class SqlDateAsDefaultBean { public java.sql.Date date; public SqlDateAsDefaultBean(long l) { date = new java.sql.Date(l); } } static class SqlDateAsNumberBean { @JsonFormat(shape=JsonFormat.Shape.NUMBER) public java.sql.Date date; public SqlDateAsNumberBean(long l) { date = new java.sql.Date(l); } } static class DateAsStringBean { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") public Date date; public DateAsStringBean(long l) { date = new java.util.Date(l); } } static class DateAsDefaultStringBean { @JsonFormat(shape=JsonFormat.Shape.STRING) public Date date; public DateAsDefaultStringBean(long l) { date = new java.util.Date(l); } } static class DateInCETBean { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET") public Date date; public DateInCETBean(long l) { date = new java.util.Date(l); } } static class CalendarAsStringBean { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") public Calendar value; public CalendarAsStringBean(long l) { value = new GregorianCalendar(); value.setTimeInMillis(l); } } static class DateAsDefaultBean { public Date date; public DateAsDefaultBean(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithEmptyJsonFormat { @JsonFormat public Date date; public DateAsDefaultBeanWithEmptyJsonFormat(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithPattern { @JsonFormat(pattern="yyyy-MM-dd") public Date date; public DateAsDefaultBeanWithPattern(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithLocale { @JsonFormat(locale = "fr") public Date date; public DateAsDefaultBeanWithLocale(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithTimezone { @JsonFormat(timezone="CET") public Date date; public DateAsDefaultBeanWithTimezone(long l) { date = new java.util.Date(l); } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testDateNumeric() throws IOException { // default is to output time stamps... assertTrue(MAPPER.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)); // shouldn't matter which offset we give... String json = MAPPER.writeValueAsString(new Date(199L)); assertEquals("199", json); } public void testDateISO8601() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // let's hit epoch start String json = mapper.writeValueAsString(new Date(0L)); assertEquals("\"1970-01-01T00:00:00.000+0000\"", json); } public void testDateOther() throws IOException { ObjectMapper mapper = new ObjectMapper(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss"); mapper.setDateFormat(df); mapper.setTimeZone(TimeZone.getTimeZone("PST")); // let's hit epoch start, offset by a bit assertEquals(quote("1969-12-31X16:00:00"), mapper.writeValueAsString(new Date(0L))); } @SuppressWarnings("deprecation") public void testSqlDate() throws IOException { // use date 1999-04-01 (note: months are 0-based, use constant) java.sql.Date date = new java.sql.Date(99, Calendar.APRIL, 1); assertEquals(quote("1999-04-01"), MAPPER.writeValueAsString(date)); java.sql.Date date0 = new java.sql.Date(0L); assertEquals(aposToQuotes("{'date':'"+date0.toString()+"'}"), MAPPER.writeValueAsString(new SqlDateAsDefaultBean(0L))); // but may explicitly force timestamp too assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsNumberBean(0L))); } public void testSqlTime() throws IOException { java.sql.Time time = new java.sql.Time(0L); // not 100% sure what we should expect wrt timezone, but what serializes // does use is quite simple: assertEquals(quote(time.toString()), MAPPER.writeValueAsString(time)); } public void testSqlTimestamp() throws IOException { java.sql.Timestamp input = new java.sql.Timestamp(0L); // just should produce same output as standard `java.util.Date`: Date altTnput = new Date(0L); assertEquals(MAPPER.writeValueAsString(altTnput), MAPPER.writeValueAsString(input)); } public void testTimeZone() throws IOException { TimeZone input = TimeZone.getTimeZone("PST"); String json = MAPPER.writeValueAsString(input); assertEquals(quote("PST"), json); } public void testTimeZoneInBean() throws IOException { String json = MAPPER.writeValueAsString(new TimeZoneBean("PST")); assertEquals("{\"tz\":\"PST\"}", json); } public void testDateUsingObjectWriter() throws IOException { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss"); TimeZone tz = TimeZone.getTimeZone("PST"); assertEquals(quote("1969-12-31X16:00:00"), MAPPER.writer(df) .with(tz) .writeValueAsString(new Date(0L))); ObjectWriter w = MAPPER.writer((DateFormat)null); assertEquals("0", w.writeValueAsString(new Date(0L))); w = w.with(df).with(tz); assertEquals(quote("1969-12-31X16:00:00"), w.writeValueAsString(new Date(0L))); w = w.with((DateFormat) null); assertEquals("0", w.writeValueAsString(new Date(0L))); } public void testDatesAsMapKeys() throws IOException { ObjectMapper mapper = new ObjectMapper(); Map<Date,Integer> map = new HashMap<Date,Integer>(); assertFalse(mapper.isEnabled(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS)); map.put(new Date(0L), Integer.valueOf(1)); // by default will serialize as ISO-8601 values... assertEquals("{\"1970-01-01T00:00:00.000+0000\":1}", mapper.writeValueAsString(map)); // but can change to use timestamps too mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, true); assertEquals("{\"0\":1}", mapper.writeValueAsString(map)); } public void testDateWithJsonFormat() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json; // first: test overriding writing as timestamp mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsNumberBean(0L)); assertEquals(aposToQuotes("{'date':0}"), json); // then reverse mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new DateAsStringBean(0L)); assertEquals("{\"date\":\"1970-01-01\"}", json); // and with different DateFormat; CET is one hour ahead of GMT json = mapper.writeValueAsString(new DateInCETBean(0L)); assertEquals("{\"date\":\"1970-01-01,01:00\"}", json); // and for [Issue#423] as well: json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new CalendarAsStringBean(0L)); assertEquals("{\"value\":\"1970-01-01\"}", json); // and with default (ISO8601) format (databind#1109) json = mapper.writeValueAsString(new DateAsDefaultStringBean(0L)); assertEquals("{\"date\":\"1970-01-01T00:00:00.000+0000\"}", json); } /** * Test to ensure that setting a TimeZone _after_ dateformat should enforce * that timezone on format, regardless of TimeZone format had. */ public void testWithTimeZoneOverride() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd/HH:mm z")); mapper.setTimeZone(TimeZone.getTimeZone("PST")); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String json = mapper.writeValueAsString(new Date(0)); // pacific time is GMT-8; so midnight becomes 16:00 previous day: assertEquals(quote("1969-12-31/16:00 PST"), json); // Let's also verify that Locale won't matter too much... mapper.setLocale(Locale.FRANCE); json = mapper.writeValueAsString(new Date(0)); assertEquals(quote("1969-12-31/16:00 PST"), json); // Also: should be able to dynamically change timezone: ObjectWriter w = mapper.writer(); w = w.with(TimeZone.getTimeZone("EST")); json = w.writeValueAsString(new Date(0)); assertEquals(quote("1969-12-31/19:00 EST"), json); } /** * Test to ensure that the default shape is correctly inferred as string or numeric, * when this shape is not explicitly set with a <code>@JsonFormat</code> annotation */ public void testDateDefaultShape() throws Exception { ObjectMapper mapper = new ObjectMapper(); // No @JsonFormat => default to user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String json = mapper.writeValueAsString(new DateAsDefaultBean(0L)); assertEquals(aposToQuotes("{'date':0}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBean(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); // Empty @JsonFormat => default to user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L)); assertEquals(aposToQuotes("{'date':0}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); // @JsonFormat with Shape.ANY and pattern => STRING shape, regardless of user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json); // @JsonFormat with Shape.ANY and locale => STRING shape, regardless of user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); // @JsonFormat with Shape.ANY and timezone => STRING shape, regardless of user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json); } // [databind#1648]: contextual default format should be used public void testFormatWithoutPattern() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss")); String json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01X01:00:00'}"), json); } }
// You are a professional Java test case writer, please create a test case named `testFormatWithoutPattern` for the issue `JacksonDatabind-1648`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1648 // // ## Issue-Title: // DateTimeSerializerBase ignores configured date format when creating contextual // // ## Issue-Description: // `DateTimeSerializerBase#createContextual` creates a new serializer with `StdDateFormat.DATE_FORMAT_STR_ISO8601` format instead of re-using the actual format that may have been specified on the configuration. See the following code: // // // // ``` // final String pattern = format.hasPattern() // ? format.getPattern() // : StdDateFormat.DATE_FORMAT_STR_ISO8601; // // ``` // // Using the `@JsonFormat` annotation on a field will therefore reset the format to Jackson's default even if the annotation doesn't specify any custom format. // // // `DateBasedDeserializer#createContextual` behaves differently and tries to re-use the configured format: // // // // ``` // DateFormat df = ctxt.getConfig().getDateFormat(); // // one shortcut: with our custom format, can simplify handling a bit // if (df.getClass() == StdDateFormat.class) { // ... // StdDateFormat std = (StdDateFormat) df; // std = std.withTimeZone(tz); // ... // } else { // // otherwise need to clone, re-set timezone: // df = (DateFormat) df.clone(); // df.setTimeZone(tz); // } // // ``` // // Shouldn't the serializer follow the same approach ? // // // // public void testFormatWithoutPattern() throws Exception {
316
// [databind#1648]: contextual default format should be used
85
310
src/test/java/com/fasterxml/jackson/databind/ser/DateSerializationTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1648 ## Issue-Title: DateTimeSerializerBase ignores configured date format when creating contextual ## Issue-Description: `DateTimeSerializerBase#createContextual` creates a new serializer with `StdDateFormat.DATE_FORMAT_STR_ISO8601` format instead of re-using the actual format that may have been specified on the configuration. See the following code: ``` final String pattern = format.hasPattern() ? format.getPattern() : StdDateFormat.DATE_FORMAT_STR_ISO8601; ``` Using the `@JsonFormat` annotation on a field will therefore reset the format to Jackson's default even if the annotation doesn't specify any custom format. `DateBasedDeserializer#createContextual` behaves differently and tries to re-use the configured format: ``` DateFormat df = ctxt.getConfig().getDateFormat(); // one shortcut: with our custom format, can simplify handling a bit if (df.getClass() == StdDateFormat.class) { ... StdDateFormat std = (StdDateFormat) df; std = std.withTimeZone(tz); ... } else { // otherwise need to clone, re-set timezone: df = (DateFormat) df.clone(); df.setTimeZone(tz); } ``` Shouldn't the serializer follow the same approach ? ``` You are a professional Java test case writer, please create a test case named `testFormatWithoutPattern` for the issue `JacksonDatabind-1648`, utilizing the provided issue report information and the following function signature. ```java public void testFormatWithoutPattern() throws Exception { ```
310
[ "com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase" ]
e73e44934e4f872e5d084f25c36cd51d8859712bbc4425f78bd9a7898ccf5264
public void testFormatWithoutPattern() throws Exception
// You are a professional Java test case writer, please create a test case named `testFormatWithoutPattern` for the issue `JacksonDatabind-1648`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1648 // // ## Issue-Title: // DateTimeSerializerBase ignores configured date format when creating contextual // // ## Issue-Description: // `DateTimeSerializerBase#createContextual` creates a new serializer with `StdDateFormat.DATE_FORMAT_STR_ISO8601` format instead of re-using the actual format that may have been specified on the configuration. See the following code: // // // // ``` // final String pattern = format.hasPattern() // ? format.getPattern() // : StdDateFormat.DATE_FORMAT_STR_ISO8601; // // ``` // // Using the `@JsonFormat` annotation on a field will therefore reset the format to Jackson's default even if the annotation doesn't specify any custom format. // // // `DateBasedDeserializer#createContextual` behaves differently and tries to re-use the configured format: // // // // ``` // DateFormat df = ctxt.getConfig().getDateFormat(); // // one shortcut: with our custom format, can simplify handling a bit // if (df.getClass() == StdDateFormat.class) { // ... // StdDateFormat std = (StdDateFormat) df; // std = std.withTimeZone(tz); // ... // } else { // // otherwise need to clone, re-set timezone: // df = (DateFormat) df.clone(); // df.setTimeZone(tz); // } // // ``` // // Shouldn't the serializer follow the same approach ? // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.ser; import java.io.*; import java.text.*; import java.util.*; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.*; public class DateSerializationTest extends BaseMapTest { static class TimeZoneBean { private TimeZone tz; public TimeZoneBean(String name) { tz = TimeZone.getTimeZone(name); } public TimeZone getTz() { return tz; } } static class DateAsNumberBean { @JsonFormat(shape=JsonFormat.Shape.NUMBER) public Date date; public DateAsNumberBean(long l) { date = new java.util.Date(l); } } static class SqlDateAsDefaultBean { public java.sql.Date date; public SqlDateAsDefaultBean(long l) { date = new java.sql.Date(l); } } static class SqlDateAsNumberBean { @JsonFormat(shape=JsonFormat.Shape.NUMBER) public java.sql.Date date; public SqlDateAsNumberBean(long l) { date = new java.sql.Date(l); } } static class DateAsStringBean { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") public Date date; public DateAsStringBean(long l) { date = new java.util.Date(l); } } static class DateAsDefaultStringBean { @JsonFormat(shape=JsonFormat.Shape.STRING) public Date date; public DateAsDefaultStringBean(long l) { date = new java.util.Date(l); } } static class DateInCETBean { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET") public Date date; public DateInCETBean(long l) { date = new java.util.Date(l); } } static class CalendarAsStringBean { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") public Calendar value; public CalendarAsStringBean(long l) { value = new GregorianCalendar(); value.setTimeInMillis(l); } } static class DateAsDefaultBean { public Date date; public DateAsDefaultBean(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithEmptyJsonFormat { @JsonFormat public Date date; public DateAsDefaultBeanWithEmptyJsonFormat(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithPattern { @JsonFormat(pattern="yyyy-MM-dd") public Date date; public DateAsDefaultBeanWithPattern(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithLocale { @JsonFormat(locale = "fr") public Date date; public DateAsDefaultBeanWithLocale(long l) { date = new java.util.Date(l); } } static class DateAsDefaultBeanWithTimezone { @JsonFormat(timezone="CET") public Date date; public DateAsDefaultBeanWithTimezone(long l) { date = new java.util.Date(l); } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testDateNumeric() throws IOException { // default is to output time stamps... assertTrue(MAPPER.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)); // shouldn't matter which offset we give... String json = MAPPER.writeValueAsString(new Date(199L)); assertEquals("199", json); } public void testDateISO8601() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // let's hit epoch start String json = mapper.writeValueAsString(new Date(0L)); assertEquals("\"1970-01-01T00:00:00.000+0000\"", json); } public void testDateOther() throws IOException { ObjectMapper mapper = new ObjectMapper(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss"); mapper.setDateFormat(df); mapper.setTimeZone(TimeZone.getTimeZone("PST")); // let's hit epoch start, offset by a bit assertEquals(quote("1969-12-31X16:00:00"), mapper.writeValueAsString(new Date(0L))); } @SuppressWarnings("deprecation") public void testSqlDate() throws IOException { // use date 1999-04-01 (note: months are 0-based, use constant) java.sql.Date date = new java.sql.Date(99, Calendar.APRIL, 1); assertEquals(quote("1999-04-01"), MAPPER.writeValueAsString(date)); java.sql.Date date0 = new java.sql.Date(0L); assertEquals(aposToQuotes("{'date':'"+date0.toString()+"'}"), MAPPER.writeValueAsString(new SqlDateAsDefaultBean(0L))); // but may explicitly force timestamp too assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsNumberBean(0L))); } public void testSqlTime() throws IOException { java.sql.Time time = new java.sql.Time(0L); // not 100% sure what we should expect wrt timezone, but what serializes // does use is quite simple: assertEquals(quote(time.toString()), MAPPER.writeValueAsString(time)); } public void testSqlTimestamp() throws IOException { java.sql.Timestamp input = new java.sql.Timestamp(0L); // just should produce same output as standard `java.util.Date`: Date altTnput = new Date(0L); assertEquals(MAPPER.writeValueAsString(altTnput), MAPPER.writeValueAsString(input)); } public void testTimeZone() throws IOException { TimeZone input = TimeZone.getTimeZone("PST"); String json = MAPPER.writeValueAsString(input); assertEquals(quote("PST"), json); } public void testTimeZoneInBean() throws IOException { String json = MAPPER.writeValueAsString(new TimeZoneBean("PST")); assertEquals("{\"tz\":\"PST\"}", json); } public void testDateUsingObjectWriter() throws IOException { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss"); TimeZone tz = TimeZone.getTimeZone("PST"); assertEquals(quote("1969-12-31X16:00:00"), MAPPER.writer(df) .with(tz) .writeValueAsString(new Date(0L))); ObjectWriter w = MAPPER.writer((DateFormat)null); assertEquals("0", w.writeValueAsString(new Date(0L))); w = w.with(df).with(tz); assertEquals(quote("1969-12-31X16:00:00"), w.writeValueAsString(new Date(0L))); w = w.with((DateFormat) null); assertEquals("0", w.writeValueAsString(new Date(0L))); } public void testDatesAsMapKeys() throws IOException { ObjectMapper mapper = new ObjectMapper(); Map<Date,Integer> map = new HashMap<Date,Integer>(); assertFalse(mapper.isEnabled(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS)); map.put(new Date(0L), Integer.valueOf(1)); // by default will serialize as ISO-8601 values... assertEquals("{\"1970-01-01T00:00:00.000+0000\":1}", mapper.writeValueAsString(map)); // but can change to use timestamps too mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, true); assertEquals("{\"0\":1}", mapper.writeValueAsString(map)); } public void testDateWithJsonFormat() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json; // first: test overriding writing as timestamp mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsNumberBean(0L)); assertEquals(aposToQuotes("{'date':0}"), json); // then reverse mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new DateAsStringBean(0L)); assertEquals("{\"date\":\"1970-01-01\"}", json); // and with different DateFormat; CET is one hour ahead of GMT json = mapper.writeValueAsString(new DateInCETBean(0L)); assertEquals("{\"date\":\"1970-01-01,01:00\"}", json); // and for [Issue#423] as well: json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new CalendarAsStringBean(0L)); assertEquals("{\"value\":\"1970-01-01\"}", json); // and with default (ISO8601) format (databind#1109) json = mapper.writeValueAsString(new DateAsDefaultStringBean(0L)); assertEquals("{\"date\":\"1970-01-01T00:00:00.000+0000\"}", json); } /** * Test to ensure that setting a TimeZone _after_ dateformat should enforce * that timezone on format, regardless of TimeZone format had. */ public void testWithTimeZoneOverride() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd/HH:mm z")); mapper.setTimeZone(TimeZone.getTimeZone("PST")); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String json = mapper.writeValueAsString(new Date(0)); // pacific time is GMT-8; so midnight becomes 16:00 previous day: assertEquals(quote("1969-12-31/16:00 PST"), json); // Let's also verify that Locale won't matter too much... mapper.setLocale(Locale.FRANCE); json = mapper.writeValueAsString(new Date(0)); assertEquals(quote("1969-12-31/16:00 PST"), json); // Also: should be able to dynamically change timezone: ObjectWriter w = mapper.writer(); w = w.with(TimeZone.getTimeZone("EST")); json = w.writeValueAsString(new Date(0)); assertEquals(quote("1969-12-31/19:00 EST"), json); } /** * Test to ensure that the default shape is correctly inferred as string or numeric, * when this shape is not explicitly set with a <code>@JsonFormat</code> annotation */ public void testDateDefaultShape() throws Exception { ObjectMapper mapper = new ObjectMapper(); // No @JsonFormat => default to user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String json = mapper.writeValueAsString(new DateAsDefaultBean(0L)); assertEquals(aposToQuotes("{'date':0}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBean(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); // Empty @JsonFormat => default to user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L)); assertEquals(aposToQuotes("{'date':0}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); // @JsonFormat with Shape.ANY and pattern => STRING shape, regardless of user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json); // @JsonFormat with Shape.ANY and locale => STRING shape, regardless of user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json); // @JsonFormat with Shape.ANY and timezone => STRING shape, regardless of user config mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json); } // [databind#1648]: contextual default format should be used public void testFormatWithoutPattern() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss")); String json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L)); assertEquals(aposToQuotes("{'date':'1970-01-01X01:00:00'}"), json); } }
@Test public void testMath1021() { final int N = 43130568; final int m = 42976365; final int n = 50; final HypergeometricDistribution dist = new HypergeometricDistribution(N, m, n); for (int i = 0; i < 100; i++) { final int sample = dist.sample(); Assert.assertTrue("sample=" + sample, 0 <= sample); Assert.assertTrue("sample=" + sample, sample <= n); } }
org.apache.commons.math3.distribution.HypergeometricDistributionTest::testMath1021
src/test/java/org/apache/commons/math3/distribution/HypergeometricDistributionTest.java
299
src/test/java/org/apache/commons/math3/distribution/HypergeometricDistributionTest.java
testMath1021
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.distribution; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; /** * Test cases for HyperGeometriclDistribution. * Extends IntegerDistributionAbstractTest. See class javadoc for * IntegerDistributionAbstractTest for details. * * @version $Id$ */ public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { //-------------- Implementations for abstract methods ----------------------- /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new HypergeometricDistribution(10, 5, 5); } /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] {-1, 0, 1, 2, 3, 4, 5, 10}; } /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { return new double[] {0d, 0.003968d, 0.099206d, 0.396825d, 0.396825d, 0.099206d, 0.003968d, 0d}; } /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0d, .003968d, .103175d, .50000d, .896825d, .996032d, 1.00000d, 1d}; } /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] {0d, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d, 1d}; } /** Creates the default inverse cumulative probability density test expected values */ @Override public int[] makeInverseCumulativeTestValues() { return new int[] {0, 0, 1, 1, 1, 1, 5, 4, 4, 4, 4, 5}; } //-------------------- Additional test cases ------------------------------ /** Verify that if there are no failures, mass is concentrated on sampleSize */ @Test public void testDegenerateNoFailures() { HypergeometricDistribution dist = new HypergeometricDistribution(5,5,3); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 0d, 0d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 0d, 0d, 1d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {3, 3}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 3); Assert.assertEquals(dist.getSupportUpperBound(), 3); } /** Verify that if there are no successes, mass is concentrated on 0 */ @Test public void testDegenerateNoSuccesses() { HypergeometricDistribution dist = new HypergeometricDistribution(5,0,3); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 1d, 1d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 1d, 0d, 0d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {0, 0}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 0); Assert.assertEquals(dist.getSupportUpperBound(), 0); } /** Verify that if sampleSize = populationSize, mass is concentrated on numberOfSuccesses */ @Test public void testDegenerateFullSample() { HypergeometricDistribution dist = new HypergeometricDistribution(5,3,5); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 0d, 0d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 0d, 0d, 1d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {3, 3}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 3); Assert.assertEquals(dist.getSupportUpperBound(), 3); } @Test public void testPreconditions() { try { new HypergeometricDistribution(0, 3, 5); Assert.fail("negative population size. NotStrictlyPositiveException expected"); } catch(NotStrictlyPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, -1, 5); Assert.fail("negative number of successes. NotPositiveException expected"); } catch(NotPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, 3, -1); Assert.fail("negative sample size. NotPositiveException expected"); } catch(NotPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, 6, 5); Assert.fail("numberOfSuccesses > populationSize. NumberIsTooLargeException expected"); } catch(NumberIsTooLargeException ex) { // Expected. } try { new HypergeometricDistribution(5, 3, 6); Assert.fail("sampleSize > populationSize. NumberIsTooLargeException expected"); } catch(NumberIsTooLargeException ex) { // Expected. } } @Test public void testAccessors() { HypergeometricDistribution dist = new HypergeometricDistribution(5, 3, 4); Assert.assertEquals(5, dist.getPopulationSize()); Assert.assertEquals(3, dist.getNumberOfSuccesses()); Assert.assertEquals(4, dist.getSampleSize()); } @Test public void testLargeValues() { int populationSize = 3456; int sampleSize = 789; int numberOfSucceses = 101; double[][] data = { {0.0, 2.75646034603961e-12, 2.75646034603961e-12, 1.0}, {1.0, 8.55705370142386e-11, 8.83269973602783e-11, 0.999999999997244}, {2.0, 1.31288129219665e-9, 1.40120828955693e-9, 0.999999999911673}, {3.0, 1.32724172984193e-8, 1.46736255879763e-8, 0.999999998598792}, {4.0, 9.94501711734089e-8, 1.14123796761385e-7, 0.999999985326375}, {5.0, 5.89080768883643e-7, 7.03204565645028e-7, 0.999999885876203}, {20.0, 0.0760051397707708, 0.27349758476299, 0.802507555007781}, {21.0, 0.087144222047629, 0.360641806810619, 0.72650241523701}, {22.0, 0.0940378846881819, 0.454679691498801, 0.639358193189381}, {23.0, 0.0956897500614809, 0.550369441560282, 0.545320308501199}, {24.0, 0.0919766921922999, 0.642346133752582, 0.449630558439718}, {25.0, 0.083641637261095, 0.725987771013677, 0.357653866247418}, {96.0, 5.93849188852098e-57, 1.0, 6.01900244560712e-57}, {97.0, 7.96593036832547e-59, 1.0, 8.05105570861321e-59}, {98.0, 8.44582921934367e-61, 1.0, 8.5125340287733e-61}, {99.0, 6.63604297068222e-63, 1.0, 6.670480942963e-63}, {100.0, 3.43501099007557e-65, 1.0, 3.4437972280786e-65}, {101.0, 8.78623800302957e-68, 1.0, 8.78623800302957e-68}, }; testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data) { HypergeometricDistribution dist = new HypergeometricDistribution(populationSize, numberOfSucceses, sampleSize); for (int i = 0; i < data.length; ++i) { int x = (int)data[i][0]; double pmf = data[i][1]; double actualPmf = dist.probability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> pmf",pmf, actualPmf, 1.0e-9); double cdf = data[i][2]; double actualCdf = dist.cumulativeProbability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> cdf",cdf, actualCdf, 1.0e-9); double cdf1 = data[i][3]; double actualCdf1 = dist.upperCumulativeProbability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> cdf1",cdf1, actualCdf1, 1.0e-9); } } @Test public void testMoreLargeValues() { int populationSize = 26896; int sampleSize = 895; int numberOfSucceses = 55; double[][] data = { {0.0, 0.155168304750504, 0.155168304750504, 1.0}, {1.0, 0.29437545000746, 0.449543754757964, 0.844831695249496}, {2.0, 0.273841321577003, 0.723385076334967, 0.550456245242036}, {3.0, 0.166488572570786, 0.889873648905753, 0.276614923665033}, {4.0, 0.0743969744713231, 0.964270623377076, 0.110126351094247}, {5.0, 0.0260542785784855, 0.990324901955562, 0.0357293766229237}, {20.0, 3.57101101678792e-16, 1.0, 3.78252101622096e-16}, {21.0, 2.00551638598312e-17, 1.0, 2.11509999433041e-17}, {22.0, 1.04317070180562e-18, 1.0, 1.09583608347287e-18}, {23.0, 5.03153504903308e-20, 1.0, 5.266538166725e-20}, {24.0, 2.2525984149695e-21, 1.0, 2.35003117691919e-21}, {25.0, 9.3677424515947e-23, 1.0, 9.74327619496943e-23}, {50.0, 9.83633962945521e-69, 1.0, 9.8677629437617e-69}, {51.0, 3.13448949497553e-71, 1.0, 3.14233143064882e-71}, {52.0, 7.82755221928122e-74, 1.0, 7.84193567329055e-74}, {53.0, 1.43662126065532e-76, 1.0, 1.43834540093295e-76}, {54.0, 1.72312692517348e-79, 1.0, 1.7241402776278e-79}, {55.0, 1.01335245432581e-82, 1.0, 1.01335245432581e-82}, }; testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } @Test public void testMoments() { final double tol = 1e-9; HypergeometricDistribution dist; dist = new HypergeometricDistribution(1500, 40, 100); Assert.assertEquals(dist.getNumericalMean(), 40d * 100d / 1500d, tol); Assert.assertEquals(dist.getNumericalVariance(), ( 100d * 40d * (1500d - 100d) * (1500d - 40d) ) / ( (1500d * 1500d * 1499d) ), tol); dist = new HypergeometricDistribution(3000, 55, 200); Assert.assertEquals(dist.getNumericalMean(), 55d * 200d / 3000d, tol); Assert.assertEquals(dist.getNumericalVariance(), ( 200d * 55d * (3000d - 200d) * (3000d - 55d) ) / ( (3000d * 3000d * 2999d) ), tol); } @Test public void testMath644() { int N = 14761461; // population int m = 1035; // successes in population int n = 1841; // number of trials int k = 0; final HypergeometricDistribution dist = new HypergeometricDistribution(N, m, n); Assert.assertTrue(Precision.compareTo(1.0, dist.upperCumulativeProbability(k), 1) == 0); Assert.assertTrue(Precision.compareTo(dist.cumulativeProbability(k), 0.0, 1) > 0); // another way to calculate the upper cumulative probability double upper = 1.0 - dist.cumulativeProbability(k) + dist.probability(k); Assert.assertTrue(Precision.compareTo(1.0, upper, 1) == 0); } @Test public void testMath1021() { final int N = 43130568; final int m = 42976365; final int n = 50; final HypergeometricDistribution dist = new HypergeometricDistribution(N, m, n); for (int i = 0; i < 100; i++) { final int sample = dist.sample(); Assert.assertTrue("sample=" + sample, 0 <= sample); Assert.assertTrue("sample=" + sample, sample <= n); } } }
// You are a professional Java test case writer, please create a test case named `testMath1021` for the issue `Math-MATH-1021`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-1021 // // ## Issue-Title: // HypergeometricDistribution.sample suffers from integer overflow // // ## Issue-Description: // // Hi, I have an application which broke when ported from commons math 2.2 to 3.2. It looks like the HypergeometricDistribution.sample() method doesn't work as well as it used to with large integer values – the example code below should return a sample between 0 and 50, but usually returns -50. // // // // // ``` // import org.apache.commons.math3.distribution.HypergeometricDistribution; // // public class Foo { // public static void main(String[] args) { // HypergeometricDistribution a = new HypergeometricDistribution( // 43130568, 42976365, 50); // System.out.printf("%d %d%n", a.getSupportLowerBound(), a.getSupportUpperBound()); // Prints "0 50" // System.out.printf("%d%n",a.sample()); // Prints "-50" // } // } // // ``` // // // In the debugger, I traced it as far as an integer overflow in HypergeometricDistribution.getNumericalMean() – instead of doing // // // // // ``` // return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize(); // // ``` // // // it could do: // // // // // ``` // return getSampleSize() * ((double) getNumberOfSuccesses() / (double) getPopulationSize()); // // ``` // // // This seemed to fix it, based on a quick test. // // // // // @Test public void testMath1021() {
299
2
287
src/test/java/org/apache/commons/math3/distribution/HypergeometricDistributionTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-1021 ## Issue-Title: HypergeometricDistribution.sample suffers from integer overflow ## Issue-Description: Hi, I have an application which broke when ported from commons math 2.2 to 3.2. It looks like the HypergeometricDistribution.sample() method doesn't work as well as it used to with large integer values – the example code below should return a sample between 0 and 50, but usually returns -50. ``` import org.apache.commons.math3.distribution.HypergeometricDistribution; public class Foo { public static void main(String[] args) { HypergeometricDistribution a = new HypergeometricDistribution( 43130568, 42976365, 50); System.out.printf("%d %d%n", a.getSupportLowerBound(), a.getSupportUpperBound()); // Prints "0 50" System.out.printf("%d%n",a.sample()); // Prints "-50" } } ``` In the debugger, I traced it as far as an integer overflow in HypergeometricDistribution.getNumericalMean() – instead of doing ``` return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize(); ``` it could do: ``` return getSampleSize() * ((double) getNumberOfSuccesses() / (double) getPopulationSize()); ``` This seemed to fix it, based on a quick test. ``` You are a professional Java test case writer, please create a test case named `testMath1021` for the issue `Math-MATH-1021`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMath1021() { ```
287
[ "org.apache.commons.math3.distribution.HypergeometricDistribution" ]
e74c92afcb0524e0fa900f22edf2c42dcde6a9aadedf4e0277ae78b03eb28834
@Test public void testMath1021()
// You are a professional Java test case writer, please create a test case named `testMath1021` for the issue `Math-MATH-1021`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-1021 // // ## Issue-Title: // HypergeometricDistribution.sample suffers from integer overflow // // ## Issue-Description: // // Hi, I have an application which broke when ported from commons math 2.2 to 3.2. It looks like the HypergeometricDistribution.sample() method doesn't work as well as it used to with large integer values – the example code below should return a sample between 0 and 50, but usually returns -50. // // // // // ``` // import org.apache.commons.math3.distribution.HypergeometricDistribution; // // public class Foo { // public static void main(String[] args) { // HypergeometricDistribution a = new HypergeometricDistribution( // 43130568, 42976365, 50); // System.out.printf("%d %d%n", a.getSupportLowerBound(), a.getSupportUpperBound()); // Prints "0 50" // System.out.printf("%d%n",a.sample()); // Prints "-50" // } // } // // ``` // // // In the debugger, I traced it as far as an integer overflow in HypergeometricDistribution.getNumericalMean() – instead of doing // // // // // ``` // return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize(); // // ``` // // // it could do: // // // // // ``` // return getSampleSize() * ((double) getNumberOfSuccesses() / (double) getPopulationSize()); // // ``` // // // This seemed to fix it, based on a quick test. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.distribution; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; /** * Test cases for HyperGeometriclDistribution. * Extends IntegerDistributionAbstractTest. See class javadoc for * IntegerDistributionAbstractTest for details. * * @version $Id$ */ public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { //-------------- Implementations for abstract methods ----------------------- /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new HypergeometricDistribution(10, 5, 5); } /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] {-1, 0, 1, 2, 3, 4, 5, 10}; } /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { return new double[] {0d, 0.003968d, 0.099206d, 0.396825d, 0.396825d, 0.099206d, 0.003968d, 0d}; } /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0d, .003968d, .103175d, .50000d, .896825d, .996032d, 1.00000d, 1d}; } /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] {0d, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d, 1d}; } /** Creates the default inverse cumulative probability density test expected values */ @Override public int[] makeInverseCumulativeTestValues() { return new int[] {0, 0, 1, 1, 1, 1, 5, 4, 4, 4, 4, 5}; } //-------------------- Additional test cases ------------------------------ /** Verify that if there are no failures, mass is concentrated on sampleSize */ @Test public void testDegenerateNoFailures() { HypergeometricDistribution dist = new HypergeometricDistribution(5,5,3); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 0d, 0d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 0d, 0d, 1d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {3, 3}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 3); Assert.assertEquals(dist.getSupportUpperBound(), 3); } /** Verify that if there are no successes, mass is concentrated on 0 */ @Test public void testDegenerateNoSuccesses() { HypergeometricDistribution dist = new HypergeometricDistribution(5,0,3); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 1d, 1d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 1d, 0d, 0d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {0, 0}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 0); Assert.assertEquals(dist.getSupportUpperBound(), 0); } /** Verify that if sampleSize = populationSize, mass is concentrated on numberOfSuccesses */ @Test public void testDegenerateFullSample() { HypergeometricDistribution dist = new HypergeometricDistribution(5,3,5); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 0d, 0d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 0d, 0d, 1d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {3, 3}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 3); Assert.assertEquals(dist.getSupportUpperBound(), 3); } @Test public void testPreconditions() { try { new HypergeometricDistribution(0, 3, 5); Assert.fail("negative population size. NotStrictlyPositiveException expected"); } catch(NotStrictlyPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, -1, 5); Assert.fail("negative number of successes. NotPositiveException expected"); } catch(NotPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, 3, -1); Assert.fail("negative sample size. NotPositiveException expected"); } catch(NotPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, 6, 5); Assert.fail("numberOfSuccesses > populationSize. NumberIsTooLargeException expected"); } catch(NumberIsTooLargeException ex) { // Expected. } try { new HypergeometricDistribution(5, 3, 6); Assert.fail("sampleSize > populationSize. NumberIsTooLargeException expected"); } catch(NumberIsTooLargeException ex) { // Expected. } } @Test public void testAccessors() { HypergeometricDistribution dist = new HypergeometricDistribution(5, 3, 4); Assert.assertEquals(5, dist.getPopulationSize()); Assert.assertEquals(3, dist.getNumberOfSuccesses()); Assert.assertEquals(4, dist.getSampleSize()); } @Test public void testLargeValues() { int populationSize = 3456; int sampleSize = 789; int numberOfSucceses = 101; double[][] data = { {0.0, 2.75646034603961e-12, 2.75646034603961e-12, 1.0}, {1.0, 8.55705370142386e-11, 8.83269973602783e-11, 0.999999999997244}, {2.0, 1.31288129219665e-9, 1.40120828955693e-9, 0.999999999911673}, {3.0, 1.32724172984193e-8, 1.46736255879763e-8, 0.999999998598792}, {4.0, 9.94501711734089e-8, 1.14123796761385e-7, 0.999999985326375}, {5.0, 5.89080768883643e-7, 7.03204565645028e-7, 0.999999885876203}, {20.0, 0.0760051397707708, 0.27349758476299, 0.802507555007781}, {21.0, 0.087144222047629, 0.360641806810619, 0.72650241523701}, {22.0, 0.0940378846881819, 0.454679691498801, 0.639358193189381}, {23.0, 0.0956897500614809, 0.550369441560282, 0.545320308501199}, {24.0, 0.0919766921922999, 0.642346133752582, 0.449630558439718}, {25.0, 0.083641637261095, 0.725987771013677, 0.357653866247418}, {96.0, 5.93849188852098e-57, 1.0, 6.01900244560712e-57}, {97.0, 7.96593036832547e-59, 1.0, 8.05105570861321e-59}, {98.0, 8.44582921934367e-61, 1.0, 8.5125340287733e-61}, {99.0, 6.63604297068222e-63, 1.0, 6.670480942963e-63}, {100.0, 3.43501099007557e-65, 1.0, 3.4437972280786e-65}, {101.0, 8.78623800302957e-68, 1.0, 8.78623800302957e-68}, }; testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data) { HypergeometricDistribution dist = new HypergeometricDistribution(populationSize, numberOfSucceses, sampleSize); for (int i = 0; i < data.length; ++i) { int x = (int)data[i][0]; double pmf = data[i][1]; double actualPmf = dist.probability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> pmf",pmf, actualPmf, 1.0e-9); double cdf = data[i][2]; double actualCdf = dist.cumulativeProbability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> cdf",cdf, actualCdf, 1.0e-9); double cdf1 = data[i][3]; double actualCdf1 = dist.upperCumulativeProbability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> cdf1",cdf1, actualCdf1, 1.0e-9); } } @Test public void testMoreLargeValues() { int populationSize = 26896; int sampleSize = 895; int numberOfSucceses = 55; double[][] data = { {0.0, 0.155168304750504, 0.155168304750504, 1.0}, {1.0, 0.29437545000746, 0.449543754757964, 0.844831695249496}, {2.0, 0.273841321577003, 0.723385076334967, 0.550456245242036}, {3.0, 0.166488572570786, 0.889873648905753, 0.276614923665033}, {4.0, 0.0743969744713231, 0.964270623377076, 0.110126351094247}, {5.0, 0.0260542785784855, 0.990324901955562, 0.0357293766229237}, {20.0, 3.57101101678792e-16, 1.0, 3.78252101622096e-16}, {21.0, 2.00551638598312e-17, 1.0, 2.11509999433041e-17}, {22.0, 1.04317070180562e-18, 1.0, 1.09583608347287e-18}, {23.0, 5.03153504903308e-20, 1.0, 5.266538166725e-20}, {24.0, 2.2525984149695e-21, 1.0, 2.35003117691919e-21}, {25.0, 9.3677424515947e-23, 1.0, 9.74327619496943e-23}, {50.0, 9.83633962945521e-69, 1.0, 9.8677629437617e-69}, {51.0, 3.13448949497553e-71, 1.0, 3.14233143064882e-71}, {52.0, 7.82755221928122e-74, 1.0, 7.84193567329055e-74}, {53.0, 1.43662126065532e-76, 1.0, 1.43834540093295e-76}, {54.0, 1.72312692517348e-79, 1.0, 1.7241402776278e-79}, {55.0, 1.01335245432581e-82, 1.0, 1.01335245432581e-82}, }; testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } @Test public void testMoments() { final double tol = 1e-9; HypergeometricDistribution dist; dist = new HypergeometricDistribution(1500, 40, 100); Assert.assertEquals(dist.getNumericalMean(), 40d * 100d / 1500d, tol); Assert.assertEquals(dist.getNumericalVariance(), ( 100d * 40d * (1500d - 100d) * (1500d - 40d) ) / ( (1500d * 1500d * 1499d) ), tol); dist = new HypergeometricDistribution(3000, 55, 200); Assert.assertEquals(dist.getNumericalMean(), 55d * 200d / 3000d, tol); Assert.assertEquals(dist.getNumericalVariance(), ( 200d * 55d * (3000d - 200d) * (3000d - 55d) ) / ( (3000d * 3000d * 2999d) ), tol); } @Test public void testMath644() { int N = 14761461; // population int m = 1035; // successes in population int n = 1841; // number of trials int k = 0; final HypergeometricDistribution dist = new HypergeometricDistribution(N, m, n); Assert.assertTrue(Precision.compareTo(1.0, dist.upperCumulativeProbability(k), 1) == 0); Assert.assertTrue(Precision.compareTo(dist.cumulativeProbability(k), 0.0, 1) > 0); // another way to calculate the upper cumulative probability double upper = 1.0 - dist.cumulativeProbability(k) + dist.probability(k); Assert.assertTrue(Precision.compareTo(1.0, upper, 1) == 0); } @Test public void testMath1021() { final int N = 43130568; final int m = 42976365; final int n = 50; final HypergeometricDistribution dist = new HypergeometricDistribution(N, m, n); for (int i = 0; i < 100; i++) { final int sample = dist.sample(); Assert.assertTrue("sample=" + sample, 0 <= sample); Assert.assertTrue("sample=" + sample, sample <= n); } } }
public void testIssue1125WithDefault() throws Exception { Issue1125Wrapper result = MAPPER.readValue(aposToQuotes("{'value':{'a':3,'def':9,'b':5}}"), Issue1125Wrapper.class); assertNotNull(result.value); assertEquals(Default1125.class, result.value.getClass()); Default1125 impl = (Default1125) result.value; assertEquals(3, impl.a); assertEquals(5, impl.b); assertEquals(9, impl.def); }
com.fasterxml.jackson.databind.jsontype.TestSubtypes::testIssue1125WithDefault
src/test/java/com/fasterxml/jackson/databind/jsontype/TestSubtypes.java
326
src/test/java/com/fasterxml/jackson/databind/jsontype/TestSubtypes.java
testIssue1125WithDefault
package com.fasterxml.jackson.databind.jsontype; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.fasterxml.jackson.databind.module.SimpleModule; public class TestSubtypes extends com.fasterxml.jackson.databind.BaseMapTest { @JsonTypeInfo(use=JsonTypeInfo.Id.NAME) static abstract class SuperType { } @JsonTypeName("TypeB") static class SubB extends SuperType { public int b = 1; } static class SubC extends SuperType { public int c = 2; } static class SubD extends SuperType { public int d; } // "Empty" bean @JsonTypeInfo(use=JsonTypeInfo.Id.NAME) static abstract class BaseBean { } static class EmptyBean extends BaseBean { } static class EmptyNonFinal { } // Verify combinations static class PropertyBean { @JsonTypeInfo(use=JsonTypeInfo.Id.NAME) public SuperType value; public PropertyBean() { this(null); } public PropertyBean(SuperType v) { value = v; } } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="#type", defaultImpl=DefaultImpl.class) static abstract class SuperTypeWithDefault { } static class DefaultImpl extends SuperTypeWithDefault { public int a; } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="#type") static abstract class SuperTypeWithoutDefault { } static class DefaultImpl505 extends SuperTypeWithoutDefault { public int a; } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="type") @JsonSubTypes({ @JsonSubTypes.Type(ImplX.class), @JsonSubTypes.Type(ImplY.class) }) static abstract class BaseX { } @JsonTypeName("x") static class ImplX extends BaseX { public int x; public ImplX() { } public ImplX(int x) { this.x = x; } } @JsonTypeName("y") static class ImplY extends BaseX { public int y; } // [databind#663] static class AtomicWrapper { public BaseX value; public AtomicWrapper() { } public AtomicWrapper(int x) { value = new ImplX(x); } } // [databind#1125] static class Issue1125Wrapper { public Base1125 value; public Issue1125Wrapper() { } public Issue1125Wrapper(Base1125 v) { value = v; } } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, defaultImpl=Default1125.class) @JsonSubTypes({ @JsonSubTypes.Type(Interm1125.class) }) static class Base1125 { public int a; } @JsonSubTypes({ @JsonSubTypes.Type(value=Impl1125.class, name="impl") }) static class Interm1125 extends Base1125 { public int b; } static class Impl1125 extends Interm1125 { public int c; public Impl1125() { } public Impl1125(int a0, int b0, int c0) { a = a0; b = b0; c = c0; } } static class Default1125 extends Interm1125 { public int def; Default1125() { } public Default1125(int a0, int b0, int def0) { a = a0; b = b0; def = def0; } } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); // JACKSON-510 public void testPropertyWithSubtypes() throws Exception { ObjectMapper mapper = new ObjectMapper(); // must register subtypes mapper.registerSubtypes(SubB.class, SubC.class, SubD.class); String json = mapper.writeValueAsString(new PropertyBean(new SubC())); PropertyBean result = mapper.readValue(json, PropertyBean.class); assertSame(SubC.class, result.value.getClass()); } // [JACKSON-748]: also works via modules public void testSubtypesViaModule() throws Exception { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.registerSubtypes(SubB.class, SubC.class, SubD.class); mapper.registerModule(module); String json = mapper.writeValueAsString(new PropertyBean(new SubC())); PropertyBean result = mapper.readValue(json, PropertyBean.class); assertSame(SubC.class, result.value.getClass()); } public void testSerialization() throws Exception { // serialization can detect type name ok without anything extra: SubB bean = new SubB(); assertEquals("{\"@type\":\"TypeB\",\"b\":1}", MAPPER.writeValueAsString(bean)); // but we can override type name here too ObjectMapper mapper = new ObjectMapper(); mapper.registerSubtypes(new NamedType(SubB.class, "typeB")); assertEquals("{\"@type\":\"typeB\",\"b\":1}", mapper.writeValueAsString(bean)); // and default name ought to be simple class name; with context assertEquals("{\"@type\":\"TestSubtypes$SubD\",\"d\":0}", mapper.writeValueAsString(new SubD())); } public void testDeserializationNonNamed() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerSubtypes(SubC.class); // default name should be unqualified class name SuperType bean = mapper.readValue("{\"@type\":\"TestSubtypes$SubC\", \"c\":1}", SuperType.class); assertSame(SubC.class, bean.getClass()); assertEquals(1, ((SubC) bean).c); } public void testDeserializatioNamed() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerSubtypes(SubB.class); mapper.registerSubtypes(new NamedType(SubD.class, "TypeD")); SuperType bean = mapper.readValue("{\"@type\":\"TypeB\", \"b\":13}", SuperType.class); assertSame(SubB.class, bean.getClass()); assertEquals(13, ((SubB) bean).b); // but we can also explicitly register name too bean = mapper.readValue("{\"@type\":\"TypeD\", \"d\":-4}", SuperType.class); assertSame(SubD.class, bean.getClass()); assertEquals(-4, ((SubD) bean).d); } // Trying to reproduce [JACKSON-366] public void testEmptyBean() throws Exception { // First, with annotations ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true); String json = mapper.writeValueAsString(new EmptyBean()); assertEquals("{\"@type\":\"TestSubtypes$EmptyBean\"}", json); mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); json = mapper.writeValueAsString(new EmptyBean()); assertEquals("{\"@type\":\"TestSubtypes$EmptyBean\"}", json); // and then with defaults mapper = new ObjectMapper(); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); json = mapper.writeValueAsString(new EmptyNonFinal()); assertEquals("[\"com.fasterxml.jackson.databind.jsontype.TestSubtypes$EmptyNonFinal\",{}]", json); } public void testDefaultImpl() throws Exception { // first, test with no type information SuperTypeWithDefault bean = MAPPER.readValue("{\"a\":13}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(13, ((DefaultImpl) bean).a); // and then with unmapped info bean = MAPPER.readValue("{\"a\":14,\"#type\":\"foobar\"}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(14, ((DefaultImpl) bean).a); bean = MAPPER.readValue("{\"#type\":\"foobar\",\"a\":15}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(15, ((DefaultImpl) bean).a); bean = MAPPER.readValue("{\"#type\":\"foobar\"}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(0, ((DefaultImpl) bean).a); } // [JACKSON-505]: ok to also default to mapping there might be for base type public void testDefaultImplViaModule() throws Exception { final String JSON = "{\"a\":123}"; // first: without registration etc, epic fail: try { MAPPER.readValue(JSON, SuperTypeWithoutDefault.class); fail("Expected an exception"); } catch (JsonMappingException e) { verifyException(e, "missing property"); } // but then succeed when we register default impl ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("test", Version.unknownVersion()); module.addAbstractTypeMapping(SuperTypeWithoutDefault.class, DefaultImpl505.class); mapper.registerModule(module); SuperTypeWithoutDefault bean = mapper.readValue(JSON, SuperTypeWithoutDefault.class); assertNotNull(bean); assertEquals(DefaultImpl505.class, bean.getClass()); assertEquals(123, ((DefaultImpl505) bean).a); bean = mapper.readValue("{\"#type\":\"foobar\"}", SuperTypeWithoutDefault.class); assertEquals(DefaultImpl505.class, bean.getClass()); assertEquals(0, ((DefaultImpl505) bean).a); } public void testErrorMessage() throws Exception { ObjectMapper mapper = new ObjectMapper(); try { mapper.readValue("{ \"type\": \"z\"}", BaseX.class); fail("Should have failed"); } catch (JsonMappingException e) { verifyException(e, "known type ids ="); } } public void testViaAtomic() throws Exception { AtomicWrapper input = new AtomicWrapper(3); String json = MAPPER.writeValueAsString(input); AtomicWrapper output = MAPPER.readValue(json, AtomicWrapper.class); assertNotNull(output); assertEquals(ImplX.class, output.value.getClass()); assertEquals(3, ((ImplX) output.value).x); } // [databind#1125]: properties from base class too public void testIssue1125NonDefault() throws Exception { String json = MAPPER.writeValueAsString(new Issue1125Wrapper(new Impl1125(1, 2, 3))); Issue1125Wrapper result = MAPPER.readValue(json, Issue1125Wrapper.class); assertNotNull(result.value); assertEquals(Impl1125.class, result.value.getClass()); Impl1125 impl = (Impl1125) result.value; assertEquals(1, impl.a); assertEquals(2, impl.b); assertEquals(3, impl.c); } public void testIssue1125WithDefault() throws Exception { Issue1125Wrapper result = MAPPER.readValue(aposToQuotes("{'value':{'a':3,'def':9,'b':5}}"), Issue1125Wrapper.class); assertNotNull(result.value); assertEquals(Default1125.class, result.value.getClass()); Default1125 impl = (Default1125) result.value; assertEquals(3, impl.a); assertEquals(5, impl.b); assertEquals(9, impl.def); } }
// You are a professional Java test case writer, please create a test case named `testIssue1125WithDefault` for the issue `JacksonDatabind-1125`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1125 // // ## Issue-Title: // Problem with polymorphic types, losing properties from base type(s) // // ## Issue-Description: // (background, see: [dropwizard/dropwizard#1449](https://github.com/dropwizard/dropwizard/pull/1449)) // // // Looks like sub-type resolution may be broken for one particular case: that of using `defaultImpl`. If so, appears like properties from super-types are not properly resolved; guessing this could be follow-up item for [#1083](https://github.com/FasterXML/jackson-databind/issues/1083) (even sooner than I thought...). // // // // public void testIssue1125WithDefault() throws Exception {
326
44
316
src/test/java/com/fasterxml/jackson/databind/jsontype/TestSubtypes.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1125 ## Issue-Title: Problem with polymorphic types, losing properties from base type(s) ## Issue-Description: (background, see: [dropwizard/dropwizard#1449](https://github.com/dropwizard/dropwizard/pull/1449)) Looks like sub-type resolution may be broken for one particular case: that of using `defaultImpl`. If so, appears like properties from super-types are not properly resolved; guessing this could be follow-up item for [#1083](https://github.com/FasterXML/jackson-databind/issues/1083) (even sooner than I thought...). ``` You are a professional Java test case writer, please create a test case named `testIssue1125WithDefault` for the issue `JacksonDatabind-1125`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1125WithDefault() throws Exception { ```
316
[ "com.fasterxml.jackson.databind.type.SimpleType" ]
e75b45fd73c0453bbb1a55ad03e01efea928eecc043a114b98487ec26aa5e27b
public void testIssue1125WithDefault() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue1125WithDefault` for the issue `JacksonDatabind-1125`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1125 // // ## Issue-Title: // Problem with polymorphic types, losing properties from base type(s) // // ## Issue-Description: // (background, see: [dropwizard/dropwizard#1449](https://github.com/dropwizard/dropwizard/pull/1449)) // // // Looks like sub-type resolution may be broken for one particular case: that of using `defaultImpl`. If so, appears like properties from super-types are not properly resolved; guessing this could be follow-up item for [#1083](https://github.com/FasterXML/jackson-databind/issues/1083) (even sooner than I thought...). // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.jsontype; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.fasterxml.jackson.databind.module.SimpleModule; public class TestSubtypes extends com.fasterxml.jackson.databind.BaseMapTest { @JsonTypeInfo(use=JsonTypeInfo.Id.NAME) static abstract class SuperType { } @JsonTypeName("TypeB") static class SubB extends SuperType { public int b = 1; } static class SubC extends SuperType { public int c = 2; } static class SubD extends SuperType { public int d; } // "Empty" bean @JsonTypeInfo(use=JsonTypeInfo.Id.NAME) static abstract class BaseBean { } static class EmptyBean extends BaseBean { } static class EmptyNonFinal { } // Verify combinations static class PropertyBean { @JsonTypeInfo(use=JsonTypeInfo.Id.NAME) public SuperType value; public PropertyBean() { this(null); } public PropertyBean(SuperType v) { value = v; } } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="#type", defaultImpl=DefaultImpl.class) static abstract class SuperTypeWithDefault { } static class DefaultImpl extends SuperTypeWithDefault { public int a; } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="#type") static abstract class SuperTypeWithoutDefault { } static class DefaultImpl505 extends SuperTypeWithoutDefault { public int a; } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="type") @JsonSubTypes({ @JsonSubTypes.Type(ImplX.class), @JsonSubTypes.Type(ImplY.class) }) static abstract class BaseX { } @JsonTypeName("x") static class ImplX extends BaseX { public int x; public ImplX() { } public ImplX(int x) { this.x = x; } } @JsonTypeName("y") static class ImplY extends BaseX { public int y; } // [databind#663] static class AtomicWrapper { public BaseX value; public AtomicWrapper() { } public AtomicWrapper(int x) { value = new ImplX(x); } } // [databind#1125] static class Issue1125Wrapper { public Base1125 value; public Issue1125Wrapper() { } public Issue1125Wrapper(Base1125 v) { value = v; } } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, defaultImpl=Default1125.class) @JsonSubTypes({ @JsonSubTypes.Type(Interm1125.class) }) static class Base1125 { public int a; } @JsonSubTypes({ @JsonSubTypes.Type(value=Impl1125.class, name="impl") }) static class Interm1125 extends Base1125 { public int b; } static class Impl1125 extends Interm1125 { public int c; public Impl1125() { } public Impl1125(int a0, int b0, int c0) { a = a0; b = b0; c = c0; } } static class Default1125 extends Interm1125 { public int def; Default1125() { } public Default1125(int a0, int b0, int def0) { a = a0; b = b0; def = def0; } } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); // JACKSON-510 public void testPropertyWithSubtypes() throws Exception { ObjectMapper mapper = new ObjectMapper(); // must register subtypes mapper.registerSubtypes(SubB.class, SubC.class, SubD.class); String json = mapper.writeValueAsString(new PropertyBean(new SubC())); PropertyBean result = mapper.readValue(json, PropertyBean.class); assertSame(SubC.class, result.value.getClass()); } // [JACKSON-748]: also works via modules public void testSubtypesViaModule() throws Exception { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.registerSubtypes(SubB.class, SubC.class, SubD.class); mapper.registerModule(module); String json = mapper.writeValueAsString(new PropertyBean(new SubC())); PropertyBean result = mapper.readValue(json, PropertyBean.class); assertSame(SubC.class, result.value.getClass()); } public void testSerialization() throws Exception { // serialization can detect type name ok without anything extra: SubB bean = new SubB(); assertEquals("{\"@type\":\"TypeB\",\"b\":1}", MAPPER.writeValueAsString(bean)); // but we can override type name here too ObjectMapper mapper = new ObjectMapper(); mapper.registerSubtypes(new NamedType(SubB.class, "typeB")); assertEquals("{\"@type\":\"typeB\",\"b\":1}", mapper.writeValueAsString(bean)); // and default name ought to be simple class name; with context assertEquals("{\"@type\":\"TestSubtypes$SubD\",\"d\":0}", mapper.writeValueAsString(new SubD())); } public void testDeserializationNonNamed() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerSubtypes(SubC.class); // default name should be unqualified class name SuperType bean = mapper.readValue("{\"@type\":\"TestSubtypes$SubC\", \"c\":1}", SuperType.class); assertSame(SubC.class, bean.getClass()); assertEquals(1, ((SubC) bean).c); } public void testDeserializatioNamed() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerSubtypes(SubB.class); mapper.registerSubtypes(new NamedType(SubD.class, "TypeD")); SuperType bean = mapper.readValue("{\"@type\":\"TypeB\", \"b\":13}", SuperType.class); assertSame(SubB.class, bean.getClass()); assertEquals(13, ((SubB) bean).b); // but we can also explicitly register name too bean = mapper.readValue("{\"@type\":\"TypeD\", \"d\":-4}", SuperType.class); assertSame(SubD.class, bean.getClass()); assertEquals(-4, ((SubD) bean).d); } // Trying to reproduce [JACKSON-366] public void testEmptyBean() throws Exception { // First, with annotations ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true); String json = mapper.writeValueAsString(new EmptyBean()); assertEquals("{\"@type\":\"TestSubtypes$EmptyBean\"}", json); mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); json = mapper.writeValueAsString(new EmptyBean()); assertEquals("{\"@type\":\"TestSubtypes$EmptyBean\"}", json); // and then with defaults mapper = new ObjectMapper(); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); json = mapper.writeValueAsString(new EmptyNonFinal()); assertEquals("[\"com.fasterxml.jackson.databind.jsontype.TestSubtypes$EmptyNonFinal\",{}]", json); } public void testDefaultImpl() throws Exception { // first, test with no type information SuperTypeWithDefault bean = MAPPER.readValue("{\"a\":13}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(13, ((DefaultImpl) bean).a); // and then with unmapped info bean = MAPPER.readValue("{\"a\":14,\"#type\":\"foobar\"}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(14, ((DefaultImpl) bean).a); bean = MAPPER.readValue("{\"#type\":\"foobar\",\"a\":15}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(15, ((DefaultImpl) bean).a); bean = MAPPER.readValue("{\"#type\":\"foobar\"}", SuperTypeWithDefault.class); assertEquals(DefaultImpl.class, bean.getClass()); assertEquals(0, ((DefaultImpl) bean).a); } // [JACKSON-505]: ok to also default to mapping there might be for base type public void testDefaultImplViaModule() throws Exception { final String JSON = "{\"a\":123}"; // first: without registration etc, epic fail: try { MAPPER.readValue(JSON, SuperTypeWithoutDefault.class); fail("Expected an exception"); } catch (JsonMappingException e) { verifyException(e, "missing property"); } // but then succeed when we register default impl ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("test", Version.unknownVersion()); module.addAbstractTypeMapping(SuperTypeWithoutDefault.class, DefaultImpl505.class); mapper.registerModule(module); SuperTypeWithoutDefault bean = mapper.readValue(JSON, SuperTypeWithoutDefault.class); assertNotNull(bean); assertEquals(DefaultImpl505.class, bean.getClass()); assertEquals(123, ((DefaultImpl505) bean).a); bean = mapper.readValue("{\"#type\":\"foobar\"}", SuperTypeWithoutDefault.class); assertEquals(DefaultImpl505.class, bean.getClass()); assertEquals(0, ((DefaultImpl505) bean).a); } public void testErrorMessage() throws Exception { ObjectMapper mapper = new ObjectMapper(); try { mapper.readValue("{ \"type\": \"z\"}", BaseX.class); fail("Should have failed"); } catch (JsonMappingException e) { verifyException(e, "known type ids ="); } } public void testViaAtomic() throws Exception { AtomicWrapper input = new AtomicWrapper(3); String json = MAPPER.writeValueAsString(input); AtomicWrapper output = MAPPER.readValue(json, AtomicWrapper.class); assertNotNull(output); assertEquals(ImplX.class, output.value.getClass()); assertEquals(3, ((ImplX) output.value).x); } // [databind#1125]: properties from base class too public void testIssue1125NonDefault() throws Exception { String json = MAPPER.writeValueAsString(new Issue1125Wrapper(new Impl1125(1, 2, 3))); Issue1125Wrapper result = MAPPER.readValue(json, Issue1125Wrapper.class); assertNotNull(result.value); assertEquals(Impl1125.class, result.value.getClass()); Impl1125 impl = (Impl1125) result.value; assertEquals(1, impl.a); assertEquals(2, impl.b); assertEquals(3, impl.c); } public void testIssue1125WithDefault() throws Exception { Issue1125Wrapper result = MAPPER.readValue(aposToQuotes("{'value':{'a':3,'def':9,'b':5}}"), Issue1125Wrapper.class); assertNotNull(result.value); assertEquals(Default1125.class, result.value.getClass()); Default1125 impl = (Default1125) result.value; assertEquals(3, impl.a); assertEquals(5, impl.b); assertEquals(9, impl.def); } }
@Test public void testKeepsPreTextAtDepth() { String h = "<pre><code><span><b>code\n\ncode</b></span></code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code><span><b>code\n\ncode</b></span></code></pre>", doc.body().html()); }
org.jsoup.nodes.ElementTest::testKeepsPreTextAtDepth
src/test/java/org/jsoup/nodes/ElementTest.java
111
src/test/java/org/jsoup/nodes/ElementTest.java
testKeepsPreTextAtDepth
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testKeepsPreTextAtDepth() { String h = "<pre><code><span><b>code\n\ncode</b></span></code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code><span><b>code\n\ncode</b></span></code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testHasClassDomMethods() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); Element el = new Element(tag, "", attribs); attribs.put("class", "toto"); boolean hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto"); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "\ttoto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "ab"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", " "); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "tototo"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd raulpismuth efgh "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth"); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("CLASS", "second").text("now"); // manually specifying tag and attributes should now preserve case, regardless of parse mode assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><P CLASS=\"second\">now</P></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testShallowClone() { String base = "http://example.com/"; Document doc = Jsoup.parse("<div id=1 class=one><p id=2 class=two>One", base); Element d = doc.selectFirst("div"); Element p = doc.selectFirst("p"); TextNode t = p.textNodes().get(0); Element d2 = d.shallowClone(); Element p2 = p.shallowClone(); TextNode t2 = (TextNode) t.shallowClone(); assertEquals(1, d.childNodeSize()); assertEquals(0, d2.childNodeSize()); assertEquals(1, p.childNodeSize()); assertEquals(0, p2.childNodeSize()); assertEquals("", p2.text()); assertEquals("two", p2.className()); assertEquals("One", t2.text()); d2.append("<p id=3>Three"); assertEquals(1, d2.childNodeSize()); assertEquals("Three", d2.text()); assertEquals("One", d.text()); assertEquals(base, d2.baseUri()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, (Collection<? extends Node>) null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4"); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEqualsAndValue() { // .equals and hashcode are identity. value is content. String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e0); assertTrue(e0.hasSameValue(e1)); assertTrue(e0.hasSameValue(e4)); assertTrue(e0.hasSameValue(e5)); assertFalse(e0.equals(e2)); assertFalse(e0.hasSameValue(e2)); assertFalse(e0.hasSameValue(e3)); assertFalse(e0.hasSameValue(e6)); assertFalse(e0.hasSameValue(e7)); assertEquals(e0.hashCode(), e0.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } @Test public void testHashcodeIsStableWithContentChanges() { Element root = new Element(Tag.valueOf("root"), ""); HashSet<Element> set = new HashSet<>(); // Add root node: set.add(root); root.appendChild(new Element(Tag.valueOf("a"), "")); assertTrue(set.contains(root)); } @Test public void testNamespacedElements() { // Namespaces with ns:tag in HTML must be translated to ns|tag in CSS. String html = "<html><body><fb:comments /></body></html>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("fb|comments"); assertEquals(1, els.size()); assertEquals("html > body > fb|comments", els.get(0).cssSelector()); } @Test public void testChainedRemoveAttributes() { String html = "<a one two three four>Text</a>"; Document doc = Jsoup.parse(html); Element a = doc.select("a").first(); a .removeAttr("zero") .removeAttr("one") .removeAttr("two") .removeAttr("three") .removeAttr("four") .removeAttr("five"); assertEquals("<a>Text</a>", a.outerHtml()); } @Test public void testLoopedRemoveAttributes() { String html = "<a one two three four>Text</a><p foo>Two</p>"; Document doc = Jsoup.parse(html); for (Element el : doc.getAllElements()) { el.clearAttributes(); } assertEquals("<a>Text</a>\n<p>Two</p>", doc.body().html()); } @Test public void testIs() { String html = "<div><p>One <a class=big>Two</a> Three</p><p>Another</p>"; Document doc = Jsoup.parse(html); Element p = doc.select("p").first(); assertTrue(p.is("p")); assertFalse(p.is("div")); assertTrue(p.is("p:has(a)")); assertTrue(p.is("p:first-child")); assertFalse(p.is("p:last-child")); assertTrue(p.is("*")); assertTrue(p.is("div p")); Element q = doc.select("p").last(); assertTrue(q.is("p")); assertTrue(q.is("p ~ p")); assertTrue(q.is("p + p")); assertTrue(q.is("p:last-child")); assertFalse(q.is("p a")); assertFalse(q.is("a")); } @Test public void elementByTagName() { Element a = new Element("P"); assertTrue(a.tagName().equals("P")); } @Test public void testChildrenElements() { String html = "<div><p><a>One</a></p><p><a>Two</a></p>Three</div><span>Four</span><foo></foo><img>"; Document doc = Jsoup.parse(html); Element div = doc.select("div").first(); Element p = doc.select("p").first(); Element span = doc.select("span").first(); Element foo = doc.select("foo").first(); Element img = doc.select("img").first(); Elements docChildren = div.children(); assertEquals(2, docChildren.size()); assertEquals("<p><a>One</a></p>", docChildren.get(0).outerHtml()); assertEquals("<p><a>Two</a></p>", docChildren.get(1).outerHtml()); assertEquals(3, div.childNodes().size()); assertEquals("Three", div.childNodes().get(2).outerHtml()); assertEquals(1, p.children().size()); assertEquals("One", p.children().text()); assertEquals(0, span.children().size()); assertEquals(1, span.childNodes().size()); assertEquals("Four", span.childNodes().get(0).outerHtml()); assertEquals(0, foo.children().size()); assertEquals(0, foo.childNodes().size()); assertEquals(0, img.children().size()); assertEquals(0, img.childNodes().size()); } @Test public void testShadowElementsAreUpdated() { String html = "<div><p><a>One</a></p><p><a>Two</a></p>Three</div><span>Four</span><foo></foo><img>"; Document doc = Jsoup.parse(html); Element div = doc.select("div").first(); Elements els = div.children(); List<Node> nodes = div.childNodes(); assertEquals(2, els.size()); // the two Ps assertEquals(3, nodes.size()); // the "Three" textnode Element p3 = new Element("p").text("P3"); Element p4 = new Element("p").text("P4"); div.insertChildren(1, p3); div.insertChildren(3, p4); Elements els2 = div.children(); // first els should not have changed assertEquals(2, els.size()); assertEquals(4, els2.size()); assertEquals("<p><a>One</a></p>\n" + "<p>P3</p>\n" + "<p><a>Two</a></p>\n" + "<p>P4</p>Three", div.html()); assertEquals("P3", els2.get(1).text()); assertEquals("P4", els2.get(3).text()); p3.after("<span>Another</span"); Elements els3 = div.children(); assertEquals(5, els3.size()); assertEquals("span", els3.get(2).tagName()); assertEquals("Another", els3.get(2).text()); assertEquals("<p><a>One</a></p>\n" + "<p>P3</p>\n" + "<span>Another</span>\n" + "<p><a>Two</a></p>\n" + "<p>P4</p>Three", div.html()); } @Test public void classNamesAndAttributeNameIsCaseInsensitive() { String html = "<p Class='SomeText AnotherText'>One</p>"; Document doc = Jsoup.parse(html); Element p = doc.select("p").first(); assertEquals("SomeText AnotherText", p.className()); assertTrue(p.classNames().contains("SomeText")); assertTrue(p.classNames().contains("AnotherText")); assertTrue(p.hasClass("SomeText")); assertTrue(p.hasClass("sometext")); assertTrue(p.hasClass("AnotherText")); assertTrue(p.hasClass("anothertext")); Element p1 = doc.select(".SomeText").first(); Element p2 = doc.select(".sometext").first(); Element p3 = doc.select("[class=SomeText AnotherText]").first(); Element p4 = doc.select("[Class=SomeText AnotherText]").first(); Element p5 = doc.select("[class=sometext anothertext]").first(); Element p6 = doc.select("[class=SomeText AnotherText]").first(); Element p7 = doc.select("[class^=sometext]").first(); Element p8 = doc.select("[class$=nothertext]").first(); Element p9 = doc.select("[class^=sometext]").first(); Element p10 = doc.select("[class$=AnotherText]").first(); assertEquals("One", p1.text()); assertEquals(p1, p2); assertEquals(p1, p3); assertEquals(p1, p4); assertEquals(p1, p5); assertEquals(p1, p6); assertEquals(p1, p7); assertEquals(p1, p8); assertEquals(p1, p9); assertEquals(p1, p10); } @Test public void testAppendTo() { String parentHtml = "<div class='a'></div>"; String childHtml = "<div class='b'></div><p>Two</p>"; Document parentDoc = Jsoup.parse(parentHtml); Element parent = parentDoc.body(); Document childDoc = Jsoup.parse(childHtml); Element div = childDoc.select("div").first(); Element p = childDoc.select("p").first(); Element appendTo1 = div.appendTo(parent); assertEquals(div, appendTo1); Element appendTo2 = p.appendTo(div); assertEquals(p, appendTo2); assertEquals("<div class=\"a\"></div>\n<div class=\"b\">\n <p>Two</p>\n</div>", parentDoc.body().html()); assertEquals("", childDoc.body().html()); // got moved out } @Test public void testNormalizesNbspInText() { String escaped = "You can't always get what you&nbsp;want."; String withNbsp = "You can't always get what you want."; // there is an nbsp char in there Document doc = Jsoup.parse("<p>" + escaped); Element p = doc.select("p").first(); assertEquals("You can't always get what you want.", p.text()); // text is normalized assertEquals("<p>" + escaped + "</p>", p.outerHtml()); // html / whole text keeps &nbsp; assertEquals(withNbsp, p.textNodes().get(0).getWholeText()); assertEquals(160, withNbsp.charAt(29)); Element matched = doc.select("p:contains(get what you want)").first(); assertEquals("p", matched.nodeName()); assertTrue(matched.is(":containsOwn(get what you want)")); } @Test public void testRemoveBeforeIndex() { Document doc = Jsoup.parse( "<html><body><div><p>before1</p><p>before2</p><p>XXX</p><p>after1</p><p>after2</p></div></body></html>", ""); Element body = doc.select("body").first(); Elements elems = body.select("p:matchesOwn(XXX)"); Element xElem = elems.first(); Elements beforeX = xElem.parent().getElementsByIndexLessThan(xElem.elementSiblingIndex()); for(Element p : beforeX) { p.remove(); } assertEquals("<body><div><p>XXX</p><p>after1</p><p>after2</p></div></body>", TextUtil.stripNewlines(body.outerHtml())); } @Test public void testRemoveAfterIndex() { Document doc2 = Jsoup.parse( "<html><body><div><p>before1</p><p>before2</p><p>XXX</p><p>after1</p><p>after2</p></div></body></html>", ""); Element body = doc2.select("body").first(); Elements elems = body.select("p:matchesOwn(XXX)"); Element xElem = elems.first(); Elements afterX = xElem.parent().getElementsByIndexGreaterThan(xElem.elementSiblingIndex()); for(Element p : afterX) { p.remove(); } assertEquals("<body><div><p>before1</p><p>before2</p><p>XXX</p></div></body>", TextUtil.stripNewlines(body.outerHtml())); } @Test public void whiteSpaceClassElement(){ Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); Element el = new Element(tag, "", attribs); attribs.put("class", "abc "); boolean hasClass = el.hasClass("ab"); assertFalse(hasClass); } @Test public void testNextElementSiblingAfterClone() { // via https://github.com/jhy/jsoup/issues/951 String html = "<!DOCTYPE html><html lang=\"en\"><head></head><body><div>Initial element</div></body></html>"; String expectedText = "New element"; String cloneExpect = "New element in clone"; Document original = Jsoup.parse(html); Document clone = original.clone(); Element originalElement = original.body().child(0); originalElement.after("<div>" + expectedText + "</div>"); Element originalNextElementSibling = originalElement.nextElementSibling(); Element originalNextSibling = (Element) originalElement.nextSibling(); assertEquals(expectedText, originalNextElementSibling.text()); assertEquals(expectedText, originalNextSibling.text()); Element cloneElement = clone.body().child(0); cloneElement.after("<div>" + cloneExpect + "</div>"); Element cloneNextElementSibling = cloneElement.nextElementSibling(); Element cloneNextSibling = (Element) cloneElement.nextSibling(); assertEquals(cloneExpect, cloneNextElementSibling.text()); assertEquals(cloneExpect, cloneNextSibling.text()); } @Test public void testRemovingEmptyClassAttributeWhenLastClassRemoved() { // https://github.com/jhy/jsoup/issues/947 Document doc = Jsoup.parse("<img class=\"one two\" />"); Element img = doc.select("img").first(); img.removeClass("one"); img.removeClass("two"); assertFalse(doc.body().html().contains("class=\"\"")); } }
// You are a professional Java test case writer, please create a test case named `testKeepsPreTextAtDepth` for the issue `Jsoup-722`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-722 // // ## Issue-Title: // Whitespaces not properly handled in <pre> tag // // ## Issue-Description: // If a "pre" tag contains deep nested tags, whitespaces in nested tags are not preserved. // // // Example: // -------- // // // // ``` // String s = "<pre><code>\n" // + " message <span style=\"color:red\"> other \n message with \n" // + " whitespaces </span>\n" // + "</code></pre>"; // Document doc = Jsoup.parse(s); // System.out.println(doc.select("pre").first().outerHtml()); // // ``` // // Will output: // // <pre><code> // //   message <span style="color:red"> other message with whiptespaces </span> // // </pre></code> // // // // // --- // // // Output is OK if we omit the "code" tag // // // // @Test public void testKeepsPreTextAtDepth() {
111
70
106
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-722 ## Issue-Title: Whitespaces not properly handled in <pre> tag ## Issue-Description: If a "pre" tag contains deep nested tags, whitespaces in nested tags are not preserved. Example: -------- ``` String s = "<pre><code>\n" + " message <span style=\"color:red\"> other \n message with \n" + " whitespaces </span>\n" + "</code></pre>"; Document doc = Jsoup.parse(s); System.out.println(doc.select("pre").first().outerHtml()); ``` Will output: <pre><code>   message <span style="color:red"> other message with whiptespaces </span> </pre></code> --- Output is OK if we omit the "code" tag ``` You are a professional Java test case writer, please create a test case named `testKeepsPreTextAtDepth` for the issue `Jsoup-722`, utilizing the provided issue report information and the following function signature. ```java @Test public void testKeepsPreTextAtDepth() { ```
106
[ "org.jsoup.nodes.Element" ]
e8159b1e3426a49b2d460550ef7da662d65dfcdd019925a2ff47a55bb1aaf661
@Test public void testKeepsPreTextAtDepth()
// You are a professional Java test case writer, please create a test case named `testKeepsPreTextAtDepth` for the issue `Jsoup-722`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-722 // // ## Issue-Title: // Whitespaces not properly handled in <pre> tag // // ## Issue-Description: // If a "pre" tag contains deep nested tags, whitespaces in nested tags are not preserved. // // // Example: // -------- // // // // ``` // String s = "<pre><code>\n" // + " message <span style=\"color:red\"> other \n message with \n" // + " whitespaces </span>\n" // + "</code></pre>"; // Document doc = Jsoup.parse(s); // System.out.println(doc.select("pre").first().outerHtml()); // // ``` // // Will output: // // <pre><code> // //   message <span style="color:red"> other message with whiptespaces </span> // // </pre></code> // // // // // --- // // // Output is OK if we omit the "code" tag // // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testKeepsPreTextAtDepth() { String h = "<pre><code><span><b>code\n\ncode</b></span></code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code><span><b>code\n\ncode</b></span></code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testHasClassDomMethods() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); Element el = new Element(tag, "", attribs); attribs.put("class", "toto"); boolean hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto"); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "\ttoto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto "); hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", "ab"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", " "); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "tototo"); hasClass = el.hasClass("toto"); assertFalse(hasClass); attribs.put("class", "raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd raulpismuth efgh "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth"); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); attribs.put("class", " abcd efgh raulpismuth "); hasClass = el.hasClass("raulpismuth"); assertTrue(hasClass); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("CLASS", "second").text("now"); // manually specifying tag and attributes should now preserve case, regardless of parse mode assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><P CLASS=\"second\">now</P></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testShallowClone() { String base = "http://example.com/"; Document doc = Jsoup.parse("<div id=1 class=one><p id=2 class=two>One", base); Element d = doc.selectFirst("div"); Element p = doc.selectFirst("p"); TextNode t = p.textNodes().get(0); Element d2 = d.shallowClone(); Element p2 = p.shallowClone(); TextNode t2 = (TextNode) t.shallowClone(); assertEquals(1, d.childNodeSize()); assertEquals(0, d2.childNodeSize()); assertEquals(1, p.childNodeSize()); assertEquals(0, p2.childNodeSize()); assertEquals("", p2.text()); assertEquals("two", p2.className()); assertEquals("One", t2.text()); d2.append("<p id=3>Three"); assertEquals(1, d2.childNodeSize()); assertEquals("Three", d2.text()); assertEquals("One", d.text()); assertEquals(base, d2.baseUri()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, (Collection<? extends Node>) null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4"); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEqualsAndValue() { // .equals and hashcode are identity. value is content. String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e0); assertTrue(e0.hasSameValue(e1)); assertTrue(e0.hasSameValue(e4)); assertTrue(e0.hasSameValue(e5)); assertFalse(e0.equals(e2)); assertFalse(e0.hasSameValue(e2)); assertFalse(e0.hasSameValue(e3)); assertFalse(e0.hasSameValue(e6)); assertFalse(e0.hasSameValue(e7)); assertEquals(e0.hashCode(), e0.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } @Test public void testHashcodeIsStableWithContentChanges() { Element root = new Element(Tag.valueOf("root"), ""); HashSet<Element> set = new HashSet<>(); // Add root node: set.add(root); root.appendChild(new Element(Tag.valueOf("a"), "")); assertTrue(set.contains(root)); } @Test public void testNamespacedElements() { // Namespaces with ns:tag in HTML must be translated to ns|tag in CSS. String html = "<html><body><fb:comments /></body></html>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("fb|comments"); assertEquals(1, els.size()); assertEquals("html > body > fb|comments", els.get(0).cssSelector()); } @Test public void testChainedRemoveAttributes() { String html = "<a one two three four>Text</a>"; Document doc = Jsoup.parse(html); Element a = doc.select("a").first(); a .removeAttr("zero") .removeAttr("one") .removeAttr("two") .removeAttr("three") .removeAttr("four") .removeAttr("five"); assertEquals("<a>Text</a>", a.outerHtml()); } @Test public void testLoopedRemoveAttributes() { String html = "<a one two three four>Text</a><p foo>Two</p>"; Document doc = Jsoup.parse(html); for (Element el : doc.getAllElements()) { el.clearAttributes(); } assertEquals("<a>Text</a>\n<p>Two</p>", doc.body().html()); } @Test public void testIs() { String html = "<div><p>One <a class=big>Two</a> Three</p><p>Another</p>"; Document doc = Jsoup.parse(html); Element p = doc.select("p").first(); assertTrue(p.is("p")); assertFalse(p.is("div")); assertTrue(p.is("p:has(a)")); assertTrue(p.is("p:first-child")); assertFalse(p.is("p:last-child")); assertTrue(p.is("*")); assertTrue(p.is("div p")); Element q = doc.select("p").last(); assertTrue(q.is("p")); assertTrue(q.is("p ~ p")); assertTrue(q.is("p + p")); assertTrue(q.is("p:last-child")); assertFalse(q.is("p a")); assertFalse(q.is("a")); } @Test public void elementByTagName() { Element a = new Element("P"); assertTrue(a.tagName().equals("P")); } @Test public void testChildrenElements() { String html = "<div><p><a>One</a></p><p><a>Two</a></p>Three</div><span>Four</span><foo></foo><img>"; Document doc = Jsoup.parse(html); Element div = doc.select("div").first(); Element p = doc.select("p").first(); Element span = doc.select("span").first(); Element foo = doc.select("foo").first(); Element img = doc.select("img").first(); Elements docChildren = div.children(); assertEquals(2, docChildren.size()); assertEquals("<p><a>One</a></p>", docChildren.get(0).outerHtml()); assertEquals("<p><a>Two</a></p>", docChildren.get(1).outerHtml()); assertEquals(3, div.childNodes().size()); assertEquals("Three", div.childNodes().get(2).outerHtml()); assertEquals(1, p.children().size()); assertEquals("One", p.children().text()); assertEquals(0, span.children().size()); assertEquals(1, span.childNodes().size()); assertEquals("Four", span.childNodes().get(0).outerHtml()); assertEquals(0, foo.children().size()); assertEquals(0, foo.childNodes().size()); assertEquals(0, img.children().size()); assertEquals(0, img.childNodes().size()); } @Test public void testShadowElementsAreUpdated() { String html = "<div><p><a>One</a></p><p><a>Two</a></p>Three</div><span>Four</span><foo></foo><img>"; Document doc = Jsoup.parse(html); Element div = doc.select("div").first(); Elements els = div.children(); List<Node> nodes = div.childNodes(); assertEquals(2, els.size()); // the two Ps assertEquals(3, nodes.size()); // the "Three" textnode Element p3 = new Element("p").text("P3"); Element p4 = new Element("p").text("P4"); div.insertChildren(1, p3); div.insertChildren(3, p4); Elements els2 = div.children(); // first els should not have changed assertEquals(2, els.size()); assertEquals(4, els2.size()); assertEquals("<p><a>One</a></p>\n" + "<p>P3</p>\n" + "<p><a>Two</a></p>\n" + "<p>P4</p>Three", div.html()); assertEquals("P3", els2.get(1).text()); assertEquals("P4", els2.get(3).text()); p3.after("<span>Another</span"); Elements els3 = div.children(); assertEquals(5, els3.size()); assertEquals("span", els3.get(2).tagName()); assertEquals("Another", els3.get(2).text()); assertEquals("<p><a>One</a></p>\n" + "<p>P3</p>\n" + "<span>Another</span>\n" + "<p><a>Two</a></p>\n" + "<p>P4</p>Three", div.html()); } @Test public void classNamesAndAttributeNameIsCaseInsensitive() { String html = "<p Class='SomeText AnotherText'>One</p>"; Document doc = Jsoup.parse(html); Element p = doc.select("p").first(); assertEquals("SomeText AnotherText", p.className()); assertTrue(p.classNames().contains("SomeText")); assertTrue(p.classNames().contains("AnotherText")); assertTrue(p.hasClass("SomeText")); assertTrue(p.hasClass("sometext")); assertTrue(p.hasClass("AnotherText")); assertTrue(p.hasClass("anothertext")); Element p1 = doc.select(".SomeText").first(); Element p2 = doc.select(".sometext").first(); Element p3 = doc.select("[class=SomeText AnotherText]").first(); Element p4 = doc.select("[Class=SomeText AnotherText]").first(); Element p5 = doc.select("[class=sometext anothertext]").first(); Element p6 = doc.select("[class=SomeText AnotherText]").first(); Element p7 = doc.select("[class^=sometext]").first(); Element p8 = doc.select("[class$=nothertext]").first(); Element p9 = doc.select("[class^=sometext]").first(); Element p10 = doc.select("[class$=AnotherText]").first(); assertEquals("One", p1.text()); assertEquals(p1, p2); assertEquals(p1, p3); assertEquals(p1, p4); assertEquals(p1, p5); assertEquals(p1, p6); assertEquals(p1, p7); assertEquals(p1, p8); assertEquals(p1, p9); assertEquals(p1, p10); } @Test public void testAppendTo() { String parentHtml = "<div class='a'></div>"; String childHtml = "<div class='b'></div><p>Two</p>"; Document parentDoc = Jsoup.parse(parentHtml); Element parent = parentDoc.body(); Document childDoc = Jsoup.parse(childHtml); Element div = childDoc.select("div").first(); Element p = childDoc.select("p").first(); Element appendTo1 = div.appendTo(parent); assertEquals(div, appendTo1); Element appendTo2 = p.appendTo(div); assertEquals(p, appendTo2); assertEquals("<div class=\"a\"></div>\n<div class=\"b\">\n <p>Two</p>\n</div>", parentDoc.body().html()); assertEquals("", childDoc.body().html()); // got moved out } @Test public void testNormalizesNbspInText() { String escaped = "You can't always get what you&nbsp;want."; String withNbsp = "You can't always get what you want."; // there is an nbsp char in there Document doc = Jsoup.parse("<p>" + escaped); Element p = doc.select("p").first(); assertEquals("You can't always get what you want.", p.text()); // text is normalized assertEquals("<p>" + escaped + "</p>", p.outerHtml()); // html / whole text keeps &nbsp; assertEquals(withNbsp, p.textNodes().get(0).getWholeText()); assertEquals(160, withNbsp.charAt(29)); Element matched = doc.select("p:contains(get what you want)").first(); assertEquals("p", matched.nodeName()); assertTrue(matched.is(":containsOwn(get what you want)")); } @Test public void testRemoveBeforeIndex() { Document doc = Jsoup.parse( "<html><body><div><p>before1</p><p>before2</p><p>XXX</p><p>after1</p><p>after2</p></div></body></html>", ""); Element body = doc.select("body").first(); Elements elems = body.select("p:matchesOwn(XXX)"); Element xElem = elems.first(); Elements beforeX = xElem.parent().getElementsByIndexLessThan(xElem.elementSiblingIndex()); for(Element p : beforeX) { p.remove(); } assertEquals("<body><div><p>XXX</p><p>after1</p><p>after2</p></div></body>", TextUtil.stripNewlines(body.outerHtml())); } @Test public void testRemoveAfterIndex() { Document doc2 = Jsoup.parse( "<html><body><div><p>before1</p><p>before2</p><p>XXX</p><p>after1</p><p>after2</p></div></body></html>", ""); Element body = doc2.select("body").first(); Elements elems = body.select("p:matchesOwn(XXX)"); Element xElem = elems.first(); Elements afterX = xElem.parent().getElementsByIndexGreaterThan(xElem.elementSiblingIndex()); for(Element p : afterX) { p.remove(); } assertEquals("<body><div><p>before1</p><p>before2</p><p>XXX</p></div></body>", TextUtil.stripNewlines(body.outerHtml())); } @Test public void whiteSpaceClassElement(){ Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); Element el = new Element(tag, "", attribs); attribs.put("class", "abc "); boolean hasClass = el.hasClass("ab"); assertFalse(hasClass); } @Test public void testNextElementSiblingAfterClone() { // via https://github.com/jhy/jsoup/issues/951 String html = "<!DOCTYPE html><html lang=\"en\"><head></head><body><div>Initial element</div></body></html>"; String expectedText = "New element"; String cloneExpect = "New element in clone"; Document original = Jsoup.parse(html); Document clone = original.clone(); Element originalElement = original.body().child(0); originalElement.after("<div>" + expectedText + "</div>"); Element originalNextElementSibling = originalElement.nextElementSibling(); Element originalNextSibling = (Element) originalElement.nextSibling(); assertEquals(expectedText, originalNextElementSibling.text()); assertEquals(expectedText, originalNextSibling.text()); Element cloneElement = clone.body().child(0); cloneElement.after("<div>" + cloneExpect + "</div>"); Element cloneNextElementSibling = cloneElement.nextElementSibling(); Element cloneNextSibling = (Element) cloneElement.nextSibling(); assertEquals(cloneExpect, cloneNextElementSibling.text()); assertEquals(cloneExpect, cloneNextSibling.text()); } @Test public void testRemovingEmptyClassAttributeWhenLastClassRemoved() { // https://github.com/jhy/jsoup/issues/947 Document doc = Jsoup.parse("<img class=\"one two\" />"); Element img = doc.select("img").first(); img.removeClass("one"); img.removeClass("two"); assertFalse(doc.body().html().contains("class=\"\"")); } }
public void testBuilderIsResettedAlways() { try { OptionBuilder.withDescription("JUnit").create('"'); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); try { OptionBuilder.withDescription("JUnit").create(); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); }
org.apache.commons.cli.OptionBuilderTest::testBuilderIsResettedAlways
src/test/org/apache/commons/cli/OptionBuilderTest.java
175
src/test/org/apache/commons/cli/OptionBuilderTest.java
testBuilderIsResettedAlways
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import junit.framework.TestCase; public class OptionBuilderTest extends TestCase { public void testCompleteOption( ) { Option simple = OptionBuilder.withLongOpt( "simple option") .hasArg( ) .isRequired( ) .hasArgs( ) .withType( new Float( 10 ) ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); } public void testTwoCompleteOptions( ) { Option simple = OptionBuilder.withLongOpt( "simple option") .hasArg( ) .isRequired( ) .hasArgs( ) .withType( new Float( 10 ) ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); simple = OptionBuilder.withLongOpt( "dimple option") .hasArg( ) .withDescription( "this is a dimple option" ) .create( 'd' ); assertEquals( "d", simple.getOpt() ); assertEquals( "dimple option", simple.getLongOpt() ); assertEquals( "this is a dimple option", simple.getDescription() ); assertNull( simple.getType() ); assertTrue( simple.hasArg() ); assertTrue( !simple.isRequired() ); assertTrue( !simple.hasArgs() ); } public void testBaseOptionCharOpt() { Option base = OptionBuilder.withDescription( "option description") .create( 'o' ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testBaseOptionStringOpt() { Option base = OptionBuilder.withDescription( "option description") .create( "o" ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testSpecialOptChars() throws Exception { // '?' Option opt1 = OptionBuilder.withDescription("help options").create('?'); assertEquals("?", opt1.getOpt()); // '@' Option opt2 = OptionBuilder.withDescription("read from stdin").create('@'); assertEquals("@", opt2.getOpt()); } public void testOptionArgNumbers() { Option opt = OptionBuilder.withDescription( "option description" ) .hasArgs( 2 ) .create( 'o' ); assertEquals( 2, opt.getArgs() ); } public void testIllegalOptions() { // bad single character option try { OptionBuilder.withDescription( "option description" ).create( '"' ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // bad character in option string try { Option opt = OptionBuilder.create( "opt`" ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // valid option try { Option opt = OptionBuilder.create( "opt" ); // success } catch( IllegalArgumentException exp ) { fail( "IllegalArgumentException caught" ); } } public void testCreateIncompleteOption() { try { OptionBuilder.hasArg().create(); fail("Incomplete option should be rejected"); } catch (IllegalArgumentException e) { // expected // implicitly reset the builder OptionBuilder.create( "opt" ); } } public void testBuilderIsResettedAlways() { try { OptionBuilder.withDescription("JUnit").create('"'); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); try { OptionBuilder.withDescription("JUnit").create(); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); } }
// You are a professional Java test case writer, please create a test case named `testBuilderIsResettedAlways` for the issue `Cli-CLI-177`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-177 // // ## Issue-Title: // OptionBuilder is not reseted in case of an IAE at create // // ## Issue-Description: // // If the call to OptionBuilder.create() fails with an IllegalArgumentException, the OptionBuilder is not resetted and its next usage may contain unwanted settings. Actually this let the [~~CLI-1~~](https://issues.apache.org/jira/browse/CLI-1 "PosixParser interupts \"-target opt\" as \"-t arget opt\"").2 RCs fail on IBM JDK 6 running on Maven 2.0.10. // // // // // public void testBuilderIsResettedAlways() {
175
26
153
src/test/org/apache/commons/cli/OptionBuilderTest.java
src/test
```markdown ## Issue-ID: Cli-CLI-177 ## Issue-Title: OptionBuilder is not reseted in case of an IAE at create ## Issue-Description: If the call to OptionBuilder.create() fails with an IllegalArgumentException, the OptionBuilder is not resetted and its next usage may contain unwanted settings. Actually this let the [~~CLI-1~~](https://issues.apache.org/jira/browse/CLI-1 "PosixParser interupts \"-target opt\" as \"-t arget opt\"").2 RCs fail on IBM JDK 6 running on Maven 2.0.10. ``` You are a professional Java test case writer, please create a test case named `testBuilderIsResettedAlways` for the issue `Cli-CLI-177`, utilizing the provided issue report information and the following function signature. ```java public void testBuilderIsResettedAlways() { ```
153
[ "org.apache.commons.cli.OptionBuilder" ]
e849723b9a305801a19d59892d50d676d595d19fe5f77f0ac61dca9ab809b32e
public void testBuilderIsResettedAlways()
// You are a professional Java test case writer, please create a test case named `testBuilderIsResettedAlways` for the issue `Cli-CLI-177`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-177 // // ## Issue-Title: // OptionBuilder is not reseted in case of an IAE at create // // ## Issue-Description: // // If the call to OptionBuilder.create() fails with an IllegalArgumentException, the OptionBuilder is not resetted and its next usage may contain unwanted settings. Actually this let the [~~CLI-1~~](https://issues.apache.org/jira/browse/CLI-1 "PosixParser interupts \"-target opt\" as \"-t arget opt\"").2 RCs fail on IBM JDK 6 running on Maven 2.0.10. // // // // //
Cli
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import junit.framework.TestCase; public class OptionBuilderTest extends TestCase { public void testCompleteOption( ) { Option simple = OptionBuilder.withLongOpt( "simple option") .hasArg( ) .isRequired( ) .hasArgs( ) .withType( new Float( 10 ) ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); } public void testTwoCompleteOptions( ) { Option simple = OptionBuilder.withLongOpt( "simple option") .hasArg( ) .isRequired( ) .hasArgs( ) .withType( new Float( 10 ) ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); simple = OptionBuilder.withLongOpt( "dimple option") .hasArg( ) .withDescription( "this is a dimple option" ) .create( 'd' ); assertEquals( "d", simple.getOpt() ); assertEquals( "dimple option", simple.getLongOpt() ); assertEquals( "this is a dimple option", simple.getDescription() ); assertNull( simple.getType() ); assertTrue( simple.hasArg() ); assertTrue( !simple.isRequired() ); assertTrue( !simple.hasArgs() ); } public void testBaseOptionCharOpt() { Option base = OptionBuilder.withDescription( "option description") .create( 'o' ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testBaseOptionStringOpt() { Option base = OptionBuilder.withDescription( "option description") .create( "o" ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testSpecialOptChars() throws Exception { // '?' Option opt1 = OptionBuilder.withDescription("help options").create('?'); assertEquals("?", opt1.getOpt()); // '@' Option opt2 = OptionBuilder.withDescription("read from stdin").create('@'); assertEquals("@", opt2.getOpt()); } public void testOptionArgNumbers() { Option opt = OptionBuilder.withDescription( "option description" ) .hasArgs( 2 ) .create( 'o' ); assertEquals( 2, opt.getArgs() ); } public void testIllegalOptions() { // bad single character option try { OptionBuilder.withDescription( "option description" ).create( '"' ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // bad character in option string try { Option opt = OptionBuilder.create( "opt`" ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // valid option try { Option opt = OptionBuilder.create( "opt" ); // success } catch( IllegalArgumentException exp ) { fail( "IllegalArgumentException caught" ); } } public void testCreateIncompleteOption() { try { OptionBuilder.hasArg().create(); fail("Incomplete option should be rejected"); } catch (IllegalArgumentException e) { // expected // implicitly reset the builder OptionBuilder.create( "opt" ); } } public void testBuilderIsResettedAlways() { try { OptionBuilder.withDescription("JUnit").create('"'); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); try { OptionBuilder.withDescription("JUnit").create(); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); } }
public void testRequire() { assertRequire("goog.require('foo')"); assertNotRequire("goog.require(foo)"); assertNotRequire("goog.require()"); assertNotRequire("foo()"); }
com.google.javascript.jscomp.ClosureCodingConventionTest::testRequire
test/com/google/javascript/jscomp/ClosureCodingConventionTest.java
198
test/com/google/javascript/jscomp/ClosureCodingConventionTest.java
testRequire
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CodingConvention.SubclassRelationship; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; /** * Test class for {@link GoogleCodingConvention}. */ public class ClosureCodingConventionTest extends TestCase { private ClosureCodingConvention conv = new ClosureCodingConvention(); public void testVarAndOptionalParams() { Node args = new Node(Token.LP, Node.newString(Token.NAME, "a"), Node.newString(Token.NAME, "b")); Node optArgs = new Node(Token.LP, Node.newString(Token.NAME, "opt_a"), Node.newString(Token.NAME, "opt_b")); assertFalse(conv.isVarArgsParameter(args.getFirstChild())); assertFalse(conv.isVarArgsParameter(args.getLastChild())); assertFalse(conv.isVarArgsParameter(optArgs.getFirstChild())); assertFalse(conv.isVarArgsParameter(optArgs.getLastChild())); assertFalse(conv.isOptionalParameter(args.getFirstChild())); assertFalse(conv.isOptionalParameter(args.getLastChild())); assertFalse(conv.isOptionalParameter(optArgs.getFirstChild())); assertFalse(conv.isOptionalParameter(optArgs.getLastChild())); } public void testInlineName() { assertFalse(conv.isConstant("a")); assertFalse(conv.isConstant("XYZ123_")); assertFalse(conv.isConstant("ABC")); assertFalse(conv.isConstant("ABCdef")); assertFalse(conv.isConstant("aBC")); assertFalse(conv.isConstant("A")); assertFalse(conv.isConstant("_XYZ123")); assertFalse(conv.isConstant("a$b$XYZ123_")); assertFalse(conv.isConstant("a$b$ABC_DEF")); assertFalse(conv.isConstant("a$b$A")); assertFalse(conv.isConstant("a$b$a")); assertFalse(conv.isConstant("a$b$ABCdef")); assertFalse(conv.isConstant("a$b$aBC")); assertFalse(conv.isConstant("a$b$")); assertFalse(conv.isConstant("$")); } public void testExportedName() { assertFalse(conv.isExported("_a")); assertFalse(conv.isExported("_a_")); assertFalse(conv.isExported("a")); assertFalse(conv.isExported("$super", false)); assertTrue(conv.isExported("$super", true)); assertTrue(conv.isExported("$super")); } public void testPrivateName() { assertFalse(conv.isPrivate("a_")); assertFalse(conv.isPrivate("a")); assertFalse(conv.isPrivate("_a_")); } public void testEnumKey() { assertTrue(conv.isValidEnumKey("A")); assertTrue(conv.isValidEnumKey("123")); assertTrue(conv.isValidEnumKey("FOO_BAR")); assertTrue(conv.isValidEnumKey("a")); assertTrue(conv.isValidEnumKey("someKeyInCamelCase")); assertTrue(conv.isValidEnumKey("_FOO_BAR")); } public void testInheritanceDetection1() { assertNotClassDefining("goog.foo(A, B);"); } public void testInheritanceDetection2() { assertDefinesClasses("goog.inherits(A, B);", "A", "B"); } public void testInheritanceDetection3() { assertDefinesClasses("A.inherits(B);", "A", "B"); } public void testInheritanceDetection4() { assertDefinesClasses("goog.inherits(goog.A, goog.B);", "goog.A", "goog.B"); } public void testInheritanceDetection5() { assertDefinesClasses("goog.A.inherits(goog.B);", "goog.A", "goog.B"); } public void testInheritanceDetection6() { assertNotClassDefining("A.inherits(this.B);"); } public void testInheritanceDetection7() { assertNotClassDefining("this.A.inherits(B);"); } public void testInheritanceDetection8() { assertNotClassDefining("goog.inherits(A, B, C);"); } public void testInheritanceDetection9() { assertDefinesClasses("A.mixin(B.prototype);", "A", "B"); } public void testInheritanceDetection10() { assertDefinesClasses("goog.mixin(A.prototype, B.prototype);", "A", "B"); } public void testInheritanceDetection11() { assertNotClassDefining("A.mixin(B)"); } public void testInheritanceDetection12() { assertNotClassDefining("goog.mixin(A.prototype, B)"); } public void testInheritanceDetection13() { assertNotClassDefining("goog.mixin(A, B)"); } public void testInheritanceDetection14() { assertNotClassDefining("goog$mixin((function(){}).prototype)"); } public void testInheritanceDetectionPostCollapseProperties() { assertDefinesClasses("goog$inherits(A, B);", "A", "B"); assertNotClassDefining("goog$inherits(A);"); } public void testObjectLiteralCast() { assertNotObjectLiteralCast("goog.reflect.object();"); assertNotObjectLiteralCast("goog.reflect.object(A);"); assertNotObjectLiteralCast("goog.reflect.object(1, {});"); assertObjectLiteralCast("goog.reflect.object(A, {});"); } public void testFunctionBind() { assertNotFunctionBind("goog.bind()"); // invalid bind assertFunctionBind("goog.bind(f)"); assertFunctionBind("goog.bind(f, obj)"); assertFunctionBind("goog.bind(f, obj, p1)"); assertNotFunctionBind("goog$bind()"); // invalid bind assertFunctionBind("goog$bind(f)"); assertFunctionBind("goog$bind(f, obj)"); assertFunctionBind("goog$bind(f, obj, p1)"); assertNotFunctionBind("goog.partial()"); // invalid bind assertFunctionBind("goog.partial(f)"); assertFunctionBind("goog.partial(f, obj)"); assertFunctionBind("goog.partial(f, obj, p1)"); assertNotFunctionBind("goog$partial()"); // invalid bind assertFunctionBind("goog$partial(f)"); assertFunctionBind("goog$partial(f, obj)"); assertFunctionBind("goog$partial(f, obj, p1)"); assertFunctionBind("(function(){}).bind()"); assertFunctionBind("(function(){}).bind(obj)"); assertFunctionBind("(function(){}).bind(obj, p1)"); assertNotFunctionBind("Function.prototype.bind.call()"); assertFunctionBind("Function.prototype.bind.call(obj)"); assertFunctionBind("Function.prototype.bind.call(obj, p1)"); } public void testRequire() { assertRequire("goog.require('foo')"); assertNotRequire("goog.require(foo)"); assertNotRequire("goog.require()"); assertNotRequire("foo()"); } private void assertFunctionBind(String code) { Node n = parseTestCode(code); assertNotNull(conv.describeFunctionBind(n.getFirstChild())); } private void assertNotFunctionBind(String code) { Node n = parseTestCode(code); assertNull(conv.describeFunctionBind(n.getFirstChild())); } private void assertRequire(String code) { Node n = parseTestCode(code); assertNotNull(conv.extractClassNameIfRequire(n.getFirstChild(), n)); } private void assertNotRequire(String code) { Node n = parseTestCode(code); assertNull(conv.extractClassNameIfRequire(n.getFirstChild(), n)); } private void assertNotObjectLiteralCast(String code) { Node n = parseTestCode(code); assertNull(conv.getObjectLiteralCast(null, n.getFirstChild())); } private void assertObjectLiteralCast(String code) { Node n = parseTestCode(code); assertNotNull(conv.getObjectLiteralCast(null, n.getFirstChild())); } private void assertNotClassDefining(String code) { Node n = parseTestCode(code); assertNull(conv.getClassesDefinedByCall(n.getFirstChild())); } private void assertDefinesClasses(String code, String subclassName, String superclassName) { Node n = parseTestCode(code); SubclassRelationship classes = conv.getClassesDefinedByCall(n.getFirstChild()); assertNotNull(classes); assertEquals(subclassName, classes.subclassName); assertEquals(superclassName, classes.superclassName); } private Node parseTestCode(String code) { Compiler compiler = new Compiler(); return compiler.parseTestCode(code).getFirstChild(); } }
// You are a professional Java test case writer, please create a test case named `testRequire` for the issue `Closure-530`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-530 // // ## Issue-Title: // compiler crashes when goog.provide used with non string // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. insert goog.provide(some.function); // 2. compile. // **3.** // **What is the expected output? What do you see instead?** // // This should give an error diagnostic. What it gives is: // // java.lang.RuntimeException: java.lang.RuntimeException: INTERNAL COMPILER ERROR. // Please email js-compiler@google.com with this stack trace. // GETPROP 17 [originalname: Spike] [source\_file: file.js] is not a string node // Node(CALL): file.js:17:12 // goog.provide(mine.Spike); // ... // [stack traces...] // // I think this is the current build as of the day of this report. // // public void testRequire() {
198
57
193
test/com/google/javascript/jscomp/ClosureCodingConventionTest.java
test
```markdown ## Issue-ID: Closure-530 ## Issue-Title: compiler crashes when goog.provide used with non string ## Issue-Description: **What steps will reproduce the problem?** 1. insert goog.provide(some.function); 2. compile. **3.** **What is the expected output? What do you see instead?** This should give an error diagnostic. What it gives is: java.lang.RuntimeException: java.lang.RuntimeException: INTERNAL COMPILER ERROR. Please email js-compiler@google.com with this stack trace. GETPROP 17 [originalname: Spike] [source\_file: file.js] is not a string node Node(CALL): file.js:17:12 goog.provide(mine.Spike); ... [stack traces...] I think this is the current build as of the day of this report. ``` You are a professional Java test case writer, please create a test case named `testRequire` for the issue `Closure-530`, utilizing the provided issue report information and the following function signature. ```java public void testRequire() { ```
193
[ "com.google.javascript.jscomp.ClosureCodingConvention" ]
e86bbc18afdc58c4266f956d36bb8dcc142cd07ccfa83ce0854496367c43af93
public void testRequire()
// You are a professional Java test case writer, please create a test case named `testRequire` for the issue `Closure-530`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-530 // // ## Issue-Title: // compiler crashes when goog.provide used with non string // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. insert goog.provide(some.function); // 2. compile. // **3.** // **What is the expected output? What do you see instead?** // // This should give an error diagnostic. What it gives is: // // java.lang.RuntimeException: java.lang.RuntimeException: INTERNAL COMPILER ERROR. // Please email js-compiler@google.com with this stack trace. // GETPROP 17 [originalname: Spike] [source\_file: file.js] is not a string node // Node(CALL): file.js:17:12 // goog.provide(mine.Spike); // ... // [stack traces...] // // I think this is the current build as of the day of this report. // //
Closure
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CodingConvention.SubclassRelationship; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; /** * Test class for {@link GoogleCodingConvention}. */ public class ClosureCodingConventionTest extends TestCase { private ClosureCodingConvention conv = new ClosureCodingConvention(); public void testVarAndOptionalParams() { Node args = new Node(Token.LP, Node.newString(Token.NAME, "a"), Node.newString(Token.NAME, "b")); Node optArgs = new Node(Token.LP, Node.newString(Token.NAME, "opt_a"), Node.newString(Token.NAME, "opt_b")); assertFalse(conv.isVarArgsParameter(args.getFirstChild())); assertFalse(conv.isVarArgsParameter(args.getLastChild())); assertFalse(conv.isVarArgsParameter(optArgs.getFirstChild())); assertFalse(conv.isVarArgsParameter(optArgs.getLastChild())); assertFalse(conv.isOptionalParameter(args.getFirstChild())); assertFalse(conv.isOptionalParameter(args.getLastChild())); assertFalse(conv.isOptionalParameter(optArgs.getFirstChild())); assertFalse(conv.isOptionalParameter(optArgs.getLastChild())); } public void testInlineName() { assertFalse(conv.isConstant("a")); assertFalse(conv.isConstant("XYZ123_")); assertFalse(conv.isConstant("ABC")); assertFalse(conv.isConstant("ABCdef")); assertFalse(conv.isConstant("aBC")); assertFalse(conv.isConstant("A")); assertFalse(conv.isConstant("_XYZ123")); assertFalse(conv.isConstant("a$b$XYZ123_")); assertFalse(conv.isConstant("a$b$ABC_DEF")); assertFalse(conv.isConstant("a$b$A")); assertFalse(conv.isConstant("a$b$a")); assertFalse(conv.isConstant("a$b$ABCdef")); assertFalse(conv.isConstant("a$b$aBC")); assertFalse(conv.isConstant("a$b$")); assertFalse(conv.isConstant("$")); } public void testExportedName() { assertFalse(conv.isExported("_a")); assertFalse(conv.isExported("_a_")); assertFalse(conv.isExported("a")); assertFalse(conv.isExported("$super", false)); assertTrue(conv.isExported("$super", true)); assertTrue(conv.isExported("$super")); } public void testPrivateName() { assertFalse(conv.isPrivate("a_")); assertFalse(conv.isPrivate("a")); assertFalse(conv.isPrivate("_a_")); } public void testEnumKey() { assertTrue(conv.isValidEnumKey("A")); assertTrue(conv.isValidEnumKey("123")); assertTrue(conv.isValidEnumKey("FOO_BAR")); assertTrue(conv.isValidEnumKey("a")); assertTrue(conv.isValidEnumKey("someKeyInCamelCase")); assertTrue(conv.isValidEnumKey("_FOO_BAR")); } public void testInheritanceDetection1() { assertNotClassDefining("goog.foo(A, B);"); } public void testInheritanceDetection2() { assertDefinesClasses("goog.inherits(A, B);", "A", "B"); } public void testInheritanceDetection3() { assertDefinesClasses("A.inherits(B);", "A", "B"); } public void testInheritanceDetection4() { assertDefinesClasses("goog.inherits(goog.A, goog.B);", "goog.A", "goog.B"); } public void testInheritanceDetection5() { assertDefinesClasses("goog.A.inherits(goog.B);", "goog.A", "goog.B"); } public void testInheritanceDetection6() { assertNotClassDefining("A.inherits(this.B);"); } public void testInheritanceDetection7() { assertNotClassDefining("this.A.inherits(B);"); } public void testInheritanceDetection8() { assertNotClassDefining("goog.inherits(A, B, C);"); } public void testInheritanceDetection9() { assertDefinesClasses("A.mixin(B.prototype);", "A", "B"); } public void testInheritanceDetection10() { assertDefinesClasses("goog.mixin(A.prototype, B.prototype);", "A", "B"); } public void testInheritanceDetection11() { assertNotClassDefining("A.mixin(B)"); } public void testInheritanceDetection12() { assertNotClassDefining("goog.mixin(A.prototype, B)"); } public void testInheritanceDetection13() { assertNotClassDefining("goog.mixin(A, B)"); } public void testInheritanceDetection14() { assertNotClassDefining("goog$mixin((function(){}).prototype)"); } public void testInheritanceDetectionPostCollapseProperties() { assertDefinesClasses("goog$inherits(A, B);", "A", "B"); assertNotClassDefining("goog$inherits(A);"); } public void testObjectLiteralCast() { assertNotObjectLiteralCast("goog.reflect.object();"); assertNotObjectLiteralCast("goog.reflect.object(A);"); assertNotObjectLiteralCast("goog.reflect.object(1, {});"); assertObjectLiteralCast("goog.reflect.object(A, {});"); } public void testFunctionBind() { assertNotFunctionBind("goog.bind()"); // invalid bind assertFunctionBind("goog.bind(f)"); assertFunctionBind("goog.bind(f, obj)"); assertFunctionBind("goog.bind(f, obj, p1)"); assertNotFunctionBind("goog$bind()"); // invalid bind assertFunctionBind("goog$bind(f)"); assertFunctionBind("goog$bind(f, obj)"); assertFunctionBind("goog$bind(f, obj, p1)"); assertNotFunctionBind("goog.partial()"); // invalid bind assertFunctionBind("goog.partial(f)"); assertFunctionBind("goog.partial(f, obj)"); assertFunctionBind("goog.partial(f, obj, p1)"); assertNotFunctionBind("goog$partial()"); // invalid bind assertFunctionBind("goog$partial(f)"); assertFunctionBind("goog$partial(f, obj)"); assertFunctionBind("goog$partial(f, obj, p1)"); assertFunctionBind("(function(){}).bind()"); assertFunctionBind("(function(){}).bind(obj)"); assertFunctionBind("(function(){}).bind(obj, p1)"); assertNotFunctionBind("Function.prototype.bind.call()"); assertFunctionBind("Function.prototype.bind.call(obj)"); assertFunctionBind("Function.prototype.bind.call(obj, p1)"); } public void testRequire() { assertRequire("goog.require('foo')"); assertNotRequire("goog.require(foo)"); assertNotRequire("goog.require()"); assertNotRequire("foo()"); } private void assertFunctionBind(String code) { Node n = parseTestCode(code); assertNotNull(conv.describeFunctionBind(n.getFirstChild())); } private void assertNotFunctionBind(String code) { Node n = parseTestCode(code); assertNull(conv.describeFunctionBind(n.getFirstChild())); } private void assertRequire(String code) { Node n = parseTestCode(code); assertNotNull(conv.extractClassNameIfRequire(n.getFirstChild(), n)); } private void assertNotRequire(String code) { Node n = parseTestCode(code); assertNull(conv.extractClassNameIfRequire(n.getFirstChild(), n)); } private void assertNotObjectLiteralCast(String code) { Node n = parseTestCode(code); assertNull(conv.getObjectLiteralCast(null, n.getFirstChild())); } private void assertObjectLiteralCast(String code) { Node n = parseTestCode(code); assertNotNull(conv.getObjectLiteralCast(null, n.getFirstChild())); } private void assertNotClassDefining(String code) { Node n = parseTestCode(code); assertNull(conv.getClassesDefinedByCall(n.getFirstChild())); } private void assertDefinesClasses(String code, String subclassName, String superclassName) { Node n = parseTestCode(code); SubclassRelationship classes = conv.getClassesDefinedByCall(n.getFirstChild()); assertNotNull(classes); assertEquals(subclassName, classes.subclassName); assertEquals(superclassName, classes.superclassName); } private Node parseTestCode(String code) { Compiler compiler = new Compiler(); return compiler.parseTestCode(code).getFirstChild(); } }
public void testDeserializeBagOfStrings() throws Exception { WithBagOfStrings result = MAPPER.readerFor(WithBagOfStrings.class) .readValue("{\"strings\": [ \"a\", \"b\", \"c\"]}"); assertEquals(3, result.getStrings().size()); }
com.fasterxml.jackson.databind.deser.creators.DelegatingArrayCreator2324Test::testDeserializeBagOfStrings
src/test/java/com/fasterxml/jackson/databind/deser/creators/DelegatingArrayCreator2324Test.java
61
src/test/java/com/fasterxml/jackson/databind/deser/creators/DelegatingArrayCreator2324Test.java
testDeserializeBagOfStrings
package com.fasterxml.jackson.databind.deser.creators; import java.util.AbstractCollection; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; // for [databind#2324] public class DelegatingArrayCreator2324Test extends BaseMapTest { @JsonDeserialize(as=ImmutableBag.class) public interface Bag<T> extends Collection<T> { } public static class ImmutableBag<T> extends AbstractCollection<T> implements Bag<T> { @Override public Iterator<T> iterator() { return elements.iterator(); } @Override public int size() { return elements.size(); } @JsonCreator(mode=JsonCreator.Mode.DELEGATING) private ImmutableBag(Collection<T> elements ) { this.elements = Collections.unmodifiableCollection(elements); } private final Collection<T> elements; } static class Value { public String value; public Value(String v) { value = v; } @Override public boolean equals(Object o) { return value.equals(((Value) o).value); } } static class WithBagOfStrings { public Bag<String> getStrings() { return this.bagOfStrings; } public void setStrings(Bag<String> bagOfStrings) { this.bagOfStrings = bagOfStrings; } private Bag<String> bagOfStrings; } static class WithBagOfValues { public Bag<Value> getValues() { return this.bagOfValues; } public void setValues(Bag<Value> bagOfValues) { this.bagOfValues = bagOfValues; } private Bag<Value> bagOfValues; } private final ObjectMapper MAPPER = objectMapper(); public void testDeserializeBagOfStrings() throws Exception { WithBagOfStrings result = MAPPER.readerFor(WithBagOfStrings.class) .readValue("{\"strings\": [ \"a\", \"b\", \"c\"]}"); assertEquals(3, result.getStrings().size()); } public void testDeserializeBagOfPOJOs() throws Exception { WithBagOfValues result = MAPPER.readerFor(WithBagOfValues.class) .readValue("{\"values\": [ \"a\", \"b\", \"c\"]}"); assertEquals(3, result.getValues().size()); assertEquals(new Value("a"), result.getValues().iterator().next()); } }
// You are a professional Java test case writer, please create a test case named `testDeserializeBagOfStrings` for the issue `JacksonDatabind-2324`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2324 // // ## Issue-Title: // StringCollectionDeserializer fails with custom collection // // ## Issue-Description: // Seeing this with Jackson 2.9.8. // // // We have a custom collection implementation, which is wired to use its "immutable" version for deserialization. The rationale is that we don't want accidental modifications to the data structures that come from the wire, so they all are forced to be immutable. // // // After upgrade from 2.6.3 to 2.9.8, the deserialization started breaking with the message: // // // // > // > Cannot construct instance of `XXX` (although at least one Creator exists): no default no-arguments constructor found // > // > // > // // // This happens ONLY when you deserialize a custom collection of strings as a property of the other object. Deserializing the custom collection of strings directly works fine, and so does the deserialization of custom collection of non-strings. I believe either the `StringCollectionDeserializer` should not be invoked for custom collections, or perhaps it does not handle the delegation as expected. // // // Please see comments for repro and workaround. // // // Thanks! // // // // public void testDeserializeBagOfStrings() throws Exception {
61
112
57
src/test/java/com/fasterxml/jackson/databind/deser/creators/DelegatingArrayCreator2324Test.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-2324 ## Issue-Title: StringCollectionDeserializer fails with custom collection ## Issue-Description: Seeing this with Jackson 2.9.8. We have a custom collection implementation, which is wired to use its "immutable" version for deserialization. The rationale is that we don't want accidental modifications to the data structures that come from the wire, so they all are forced to be immutable. After upgrade from 2.6.3 to 2.9.8, the deserialization started breaking with the message: > > Cannot construct instance of `XXX` (although at least one Creator exists): no default no-arguments constructor found > > > This happens ONLY when you deserialize a custom collection of strings as a property of the other object. Deserializing the custom collection of strings directly works fine, and so does the deserialization of custom collection of non-strings. I believe either the `StringCollectionDeserializer` should not be invoked for custom collections, or perhaps it does not handle the delegation as expected. Please see comments for repro and workaround. Thanks! ``` You are a professional Java test case writer, please create a test case named `testDeserializeBagOfStrings` for the issue `JacksonDatabind-2324`, utilizing the provided issue report information and the following function signature. ```java public void testDeserializeBagOfStrings() throws Exception { ```
57
[ "com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer" ]
e938c5663d7983d2cd9aedf3be871304d14b947a20a3bb064e21e1ef8821c9bb
public void testDeserializeBagOfStrings() throws Exception
// You are a professional Java test case writer, please create a test case named `testDeserializeBagOfStrings` for the issue `JacksonDatabind-2324`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2324 // // ## Issue-Title: // StringCollectionDeserializer fails with custom collection // // ## Issue-Description: // Seeing this with Jackson 2.9.8. // // // We have a custom collection implementation, which is wired to use its "immutable" version for deserialization. The rationale is that we don't want accidental modifications to the data structures that come from the wire, so they all are forced to be immutable. // // // After upgrade from 2.6.3 to 2.9.8, the deserialization started breaking with the message: // // // // > // > Cannot construct instance of `XXX` (although at least one Creator exists): no default no-arguments constructor found // > // > // > // // // This happens ONLY when you deserialize a custom collection of strings as a property of the other object. Deserializing the custom collection of strings directly works fine, and so does the deserialization of custom collection of non-strings. I believe either the `StringCollectionDeserializer` should not be invoked for custom collections, or perhaps it does not handle the delegation as expected. // // // Please see comments for repro and workaround. // // // Thanks! // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.deser.creators; import java.util.AbstractCollection; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; // for [databind#2324] public class DelegatingArrayCreator2324Test extends BaseMapTest { @JsonDeserialize(as=ImmutableBag.class) public interface Bag<T> extends Collection<T> { } public static class ImmutableBag<T> extends AbstractCollection<T> implements Bag<T> { @Override public Iterator<T> iterator() { return elements.iterator(); } @Override public int size() { return elements.size(); } @JsonCreator(mode=JsonCreator.Mode.DELEGATING) private ImmutableBag(Collection<T> elements ) { this.elements = Collections.unmodifiableCollection(elements); } private final Collection<T> elements; } static class Value { public String value; public Value(String v) { value = v; } @Override public boolean equals(Object o) { return value.equals(((Value) o).value); } } static class WithBagOfStrings { public Bag<String> getStrings() { return this.bagOfStrings; } public void setStrings(Bag<String> bagOfStrings) { this.bagOfStrings = bagOfStrings; } private Bag<String> bagOfStrings; } static class WithBagOfValues { public Bag<Value> getValues() { return this.bagOfValues; } public void setValues(Bag<Value> bagOfValues) { this.bagOfValues = bagOfValues; } private Bag<Value> bagOfValues; } private final ObjectMapper MAPPER = objectMapper(); public void testDeserializeBagOfStrings() throws Exception { WithBagOfStrings result = MAPPER.readerFor(WithBagOfStrings.class) .readValue("{\"strings\": [ \"a\", \"b\", \"c\"]}"); assertEquals(3, result.getStrings().size()); } public void testDeserializeBagOfPOJOs() throws Exception { WithBagOfValues result = MAPPER.readerFor(WithBagOfValues.class) .readValue("{\"values\": [ \"a\", \"b\", \"c\"]}"); assertEquals(3, result.getValues().size()); assertEquals(new Value("a"), result.getValues().iterator().next()); } }
public void testUnexpectedToken() throws Exception { try { DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class); adapter.fromJson("{}"); fail("Unexpected token should fail."); } catch (IllegalStateException expected) { } }
com.google.gson.DefaultDateTypeAdapterTest::testUnexpectedToken
gson/src/test/java/com/google/gson/DefaultDateTypeAdapterTest.java
175
gson/src/test/java/com/google/gson/DefaultDateTypeAdapterTest.java
testUnexpectedToken
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; /** * A simple unit test for the {@link DefaultDateTypeAdapter} class. * * @author Joel Leitch */ public class DefaultDateTypeAdapterTest extends TestCase { public void testFormattingInEnUs() { assertFormattingAlwaysEmitsUsLocale(Locale.US); } public void testFormattingInFr() { assertFormattingAlwaysEmitsUsLocale(Locale.FRANCE); } private void assertFormattingAlwaysEmitsUsLocale(Locale locale) { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(locale); try { assertFormatted("Jan 1, 1970 12:00:00 AM", new DefaultDateTypeAdapter(Date.class)); assertFormatted("1/1/70", new DefaultDateTypeAdapter(Date.class, DateFormat.SHORT)); assertFormatted("Jan 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.MEDIUM)); assertFormatted("January 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.LONG)); assertFormatted("1/1/70 12:00 AM", new DefaultDateTypeAdapter(DateFormat.SHORT, DateFormat.SHORT)); assertFormatted("Jan 1, 1970 12:00:00 AM", new DefaultDateTypeAdapter(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertFormatted("January 1, 1970 12:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.LONG, DateFormat.LONG)); assertFormatted("Thursday, January 1, 1970 12:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testParsingDatesFormattedWithSystemLocale() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); try { assertParsed("1 janv. 1970 00:00:00", new DefaultDateTypeAdapter(Date.class)); assertParsed("01/01/70", new DefaultDateTypeAdapter(Date.class, DateFormat.SHORT)); assertParsed("1 janv. 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.MEDIUM)); assertParsed("1 janvier 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.LONG)); assertParsed("01/01/70 00:00", new DefaultDateTypeAdapter(DateFormat.SHORT, DateFormat.SHORT)); assertParsed("1 janv. 1970 00:00:00", new DefaultDateTypeAdapter(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertParsed("1 janvier 1970 00:00:00 UTC", new DefaultDateTypeAdapter(DateFormat.LONG, DateFormat.LONG)); assertParsed("jeudi 1 janvier 1970 00 h 00 UTC", new DefaultDateTypeAdapter(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testParsingDatesFormattedWithUsLocale() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { assertParsed("Jan 1, 1970 0:00:00 AM", new DefaultDateTypeAdapter(Date.class)); assertParsed("1/1/70", new DefaultDateTypeAdapter(Date.class, DateFormat.SHORT)); assertParsed("Jan 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.MEDIUM)); assertParsed("January 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.LONG)); assertParsed("1/1/70 0:00 AM", new DefaultDateTypeAdapter(DateFormat.SHORT, DateFormat.SHORT)); assertParsed("Jan 1, 1970 0:00:00 AM", new DefaultDateTypeAdapter(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertParsed("January 1, 1970 0:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.LONG, DateFormat.LONG)); assertParsed("Thursday, January 1, 1970 0:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testFormatUsesDefaultTimezone() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { assertFormatted("Dec 31, 1969 4:00:00 PM", new DefaultDateTypeAdapter(Date.class)); assertParsed("Dec 31, 1969 4:00:00 PM", new DefaultDateTypeAdapter(Date.class)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testDateDeserializationISO8601() throws Exception { DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class); assertParsed("1970-01-01T00:00:00.000Z", adapter); assertParsed("1970-01-01T00:00Z", adapter); assertParsed("1970-01-01T00:00:00+00:00", adapter); assertParsed("1970-01-01T01:00:00+01:00", adapter); assertParsed("1970-01-01T01:00:00+01", adapter); } public void testDateSerialization() throws Exception { int dateStyle = DateFormat.LONG; DefaultDateTypeAdapter dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, dateStyle); DateFormat formatter = DateFormat.getDateInstance(dateStyle, Locale.US); Date currentDate = new Date(); String dateString = dateTypeAdapter.toJson(currentDate); assertEquals(toLiteral(formatter.format(currentDate)), dateString); } public void testDatePattern() throws Exception { String pattern = "yyyy-MM-dd"; DefaultDateTypeAdapter dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, pattern); DateFormat formatter = new SimpleDateFormat(pattern); Date currentDate = new Date(); String dateString = dateTypeAdapter.toJson(currentDate); assertEquals(toLiteral(formatter.format(currentDate)), dateString); } public void testInvalidDatePattern() throws Exception { try { new DefaultDateTypeAdapter(Date.class, "I am a bad Date pattern...."); fail("Invalid date pattern should fail."); } catch (IllegalArgumentException expected) { } } public void testNullValue() throws Exception { DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class); assertNull(adapter.fromJson("null")); assertEquals("null", adapter.toJson(null)); } public void testUnexpectedToken() throws Exception { try { DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class); adapter.fromJson("{}"); fail("Unexpected token should fail."); } catch (IllegalStateException expected) { } } private void assertFormatted(String formatted, DefaultDateTypeAdapter adapter) { assertEquals(toLiteral(formatted), adapter.toJson(new Date(0))); } private void assertParsed(String date, DefaultDateTypeAdapter adapter) throws IOException { assertEquals(date, new Date(0), adapter.fromJson(toLiteral(date))); assertEquals("ISO 8601", new Date(0), adapter.fromJson(toLiteral("1970-01-01T00:00:00Z"))); } private static String toLiteral(String s) { return '"' + s + '"'; } }
// You are a professional Java test case writer, please create a test case named `testUnexpectedToken` for the issue `Gson-1100`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-1100 // // ## Issue-Title: // Fixed DefaultDateTypeAdapter nullability issue and JSON primitives contract // // ## Issue-Description: // Regression in: // // // * [b8f616c](https://github.com/google/gson/commit/b8f616c939c652b8540c95fa2b377b8c628ef3ff) - Migrate DefaultDateTypeAdapter to streaming adapter ([#1070](https://github.com/google/gson/pull/1070)) // // // Bug reports: // // // * [#1096](https://github.com/google/gson/issues/1096) - 2.8.1 can't serialize and deserialize date null (2.8.0 works fine) // * [#1098](https://github.com/google/gson/issues/1098) - Gson 2.8.1 DefaultDateTypeAdapter is not null safe. // * [#1095](https://github.com/google/gson/issues/1095) - serialize date sometimes TreeTypeAdapter, sometimes DefaultDateTypeAdapter? // // // public void testUnexpectedToken() throws Exception {
175
17
169
gson/src/test/java/com/google/gson/DefaultDateTypeAdapterTest.java
gson/src/test/java
```markdown ## Issue-ID: Gson-1100 ## Issue-Title: Fixed DefaultDateTypeAdapter nullability issue and JSON primitives contract ## Issue-Description: Regression in: * [b8f616c](https://github.com/google/gson/commit/b8f616c939c652b8540c95fa2b377b8c628ef3ff) - Migrate DefaultDateTypeAdapter to streaming adapter ([#1070](https://github.com/google/gson/pull/1070)) Bug reports: * [#1096](https://github.com/google/gson/issues/1096) - 2.8.1 can't serialize and deserialize date null (2.8.0 works fine) * [#1098](https://github.com/google/gson/issues/1098) - Gson 2.8.1 DefaultDateTypeAdapter is not null safe. * [#1095](https://github.com/google/gson/issues/1095) - serialize date sometimes TreeTypeAdapter, sometimes DefaultDateTypeAdapter? ``` You are a professional Java test case writer, please create a test case named `testUnexpectedToken` for the issue `Gson-1100`, utilizing the provided issue report information and the following function signature. ```java public void testUnexpectedToken() throws Exception { ```
169
[ "com.google.gson.DefaultDateTypeAdapter" ]
e9e4b4e89cd8de82ea6e4a2653acd2efffc9ae21f4bf6f1eb248221a36614f24
public void testUnexpectedToken() throws Exception
// You are a professional Java test case writer, please create a test case named `testUnexpectedToken` for the issue `Gson-1100`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-1100 // // ## Issue-Title: // Fixed DefaultDateTypeAdapter nullability issue and JSON primitives contract // // ## Issue-Description: // Regression in: // // // * [b8f616c](https://github.com/google/gson/commit/b8f616c939c652b8540c95fa2b377b8c628ef3ff) - Migrate DefaultDateTypeAdapter to streaming adapter ([#1070](https://github.com/google/gson/pull/1070)) // // // Bug reports: // // // * [#1096](https://github.com/google/gson/issues/1096) - 2.8.1 can't serialize and deserialize date null (2.8.0 works fine) // * [#1098](https://github.com/google/gson/issues/1098) - Gson 2.8.1 DefaultDateTypeAdapter is not null safe. // * [#1095](https://github.com/google/gson/issues/1095) - serialize date sometimes TreeTypeAdapter, sometimes DefaultDateTypeAdapter? // // //
Gson
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; /** * A simple unit test for the {@link DefaultDateTypeAdapter} class. * * @author Joel Leitch */ public class DefaultDateTypeAdapterTest extends TestCase { public void testFormattingInEnUs() { assertFormattingAlwaysEmitsUsLocale(Locale.US); } public void testFormattingInFr() { assertFormattingAlwaysEmitsUsLocale(Locale.FRANCE); } private void assertFormattingAlwaysEmitsUsLocale(Locale locale) { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(locale); try { assertFormatted("Jan 1, 1970 12:00:00 AM", new DefaultDateTypeAdapter(Date.class)); assertFormatted("1/1/70", new DefaultDateTypeAdapter(Date.class, DateFormat.SHORT)); assertFormatted("Jan 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.MEDIUM)); assertFormatted("January 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.LONG)); assertFormatted("1/1/70 12:00 AM", new DefaultDateTypeAdapter(DateFormat.SHORT, DateFormat.SHORT)); assertFormatted("Jan 1, 1970 12:00:00 AM", new DefaultDateTypeAdapter(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertFormatted("January 1, 1970 12:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.LONG, DateFormat.LONG)); assertFormatted("Thursday, January 1, 1970 12:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testParsingDatesFormattedWithSystemLocale() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); try { assertParsed("1 janv. 1970 00:00:00", new DefaultDateTypeAdapter(Date.class)); assertParsed("01/01/70", new DefaultDateTypeAdapter(Date.class, DateFormat.SHORT)); assertParsed("1 janv. 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.MEDIUM)); assertParsed("1 janvier 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.LONG)); assertParsed("01/01/70 00:00", new DefaultDateTypeAdapter(DateFormat.SHORT, DateFormat.SHORT)); assertParsed("1 janv. 1970 00:00:00", new DefaultDateTypeAdapter(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertParsed("1 janvier 1970 00:00:00 UTC", new DefaultDateTypeAdapter(DateFormat.LONG, DateFormat.LONG)); assertParsed("jeudi 1 janvier 1970 00 h 00 UTC", new DefaultDateTypeAdapter(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testParsingDatesFormattedWithUsLocale() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { assertParsed("Jan 1, 1970 0:00:00 AM", new DefaultDateTypeAdapter(Date.class)); assertParsed("1/1/70", new DefaultDateTypeAdapter(Date.class, DateFormat.SHORT)); assertParsed("Jan 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.MEDIUM)); assertParsed("January 1, 1970", new DefaultDateTypeAdapter(Date.class, DateFormat.LONG)); assertParsed("1/1/70 0:00 AM", new DefaultDateTypeAdapter(DateFormat.SHORT, DateFormat.SHORT)); assertParsed("Jan 1, 1970 0:00:00 AM", new DefaultDateTypeAdapter(DateFormat.MEDIUM, DateFormat.MEDIUM)); assertParsed("January 1, 1970 0:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.LONG, DateFormat.LONG)); assertParsed("Thursday, January 1, 1970 0:00:00 AM UTC", new DefaultDateTypeAdapter(DateFormat.FULL, DateFormat.FULL)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testFormatUsesDefaultTimezone() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { assertFormatted("Dec 31, 1969 4:00:00 PM", new DefaultDateTypeAdapter(Date.class)); assertParsed("Dec 31, 1969 4:00:00 PM", new DefaultDateTypeAdapter(Date.class)); } finally { TimeZone.setDefault(defaultTimeZone); Locale.setDefault(defaultLocale); } } public void testDateDeserializationISO8601() throws Exception { DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class); assertParsed("1970-01-01T00:00:00.000Z", adapter); assertParsed("1970-01-01T00:00Z", adapter); assertParsed("1970-01-01T00:00:00+00:00", adapter); assertParsed("1970-01-01T01:00:00+01:00", adapter); assertParsed("1970-01-01T01:00:00+01", adapter); } public void testDateSerialization() throws Exception { int dateStyle = DateFormat.LONG; DefaultDateTypeAdapter dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, dateStyle); DateFormat formatter = DateFormat.getDateInstance(dateStyle, Locale.US); Date currentDate = new Date(); String dateString = dateTypeAdapter.toJson(currentDate); assertEquals(toLiteral(formatter.format(currentDate)), dateString); } public void testDatePattern() throws Exception { String pattern = "yyyy-MM-dd"; DefaultDateTypeAdapter dateTypeAdapter = new DefaultDateTypeAdapter(Date.class, pattern); DateFormat formatter = new SimpleDateFormat(pattern); Date currentDate = new Date(); String dateString = dateTypeAdapter.toJson(currentDate); assertEquals(toLiteral(formatter.format(currentDate)), dateString); } public void testInvalidDatePattern() throws Exception { try { new DefaultDateTypeAdapter(Date.class, "I am a bad Date pattern...."); fail("Invalid date pattern should fail."); } catch (IllegalArgumentException expected) { } } public void testNullValue() throws Exception { DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class); assertNull(adapter.fromJson("null")); assertEquals("null", adapter.toJson(null)); } public void testUnexpectedToken() throws Exception { try { DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class); adapter.fromJson("{}"); fail("Unexpected token should fail."); } catch (IllegalStateException expected) { } } private void assertFormatted(String formatted, DefaultDateTypeAdapter adapter) { assertEquals(toLiteral(formatted), adapter.toJson(new Date(0))); } private void assertParsed(String date, DefaultDateTypeAdapter adapter) throws IOException { assertEquals(date, new Date(0), adapter.fromJson(toLiteral(date))); assertEquals("ISO 8601", new Date(0), adapter.fromJson(toLiteral("1970-01-01T00:00:00Z"))); } private static String toLiteral(String s) { return '"' + s + '"'; } }
public void testDoubleMetaphoneAlternate() { String value = null; for (int i = 0; i < TEST_DATA.length; i++) { value = TEST_DATA[i][0]; assertEquals("Test [" + i + "]=" + value, TEST_DATA[i][2], doubleMetaphone.doubleMetaphone(value, true)); } }
org.apache.commons.codec.language.DoubleMetaphone2Test::testDoubleMetaphoneAlternate
src/test/org/apache/commons/codec/language/DoubleMetaphone2Test.java
85
src/test/org/apache/commons/codec/language/DoubleMetaphone2Test.java
testDoubleMetaphoneAlternate
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.language; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests {@link DoubleMetaphone}. * <p> * The test data was extracted from Stephen Woodbridge's * <a href="http://swoodbridge.com/DoubleMetaPhone/surnames.txt">php test program</a>. * * @see http://swoodbridge.com/DoubleMetaPhone/surnames.txt * @version $Id$ */ public class DoubleMetaphone2Test extends TestCase { public static Test suite() { return new TestSuite(DoubleMetaphone2Test.class); } private DoubleMetaphone doubleMetaphone = null; /** * Construct a new test case. * * @param name The name of the test */ public DoubleMetaphone2Test(String name) { super(name); } /** * Set up. */ public void setUp() throws Exception { super.setUp(); this.doubleMetaphone = new DoubleMetaphone(); } /** * Tear Down. */ public void tearDown() throws Exception { super.tearDown(); this.doubleMetaphone = null; } /** * Test primary encoding. */ public void testDoubleMetaphonePrimary() { String value = null; for (int i = 0; i < TEST_DATA.length; i++) { value = TEST_DATA[i][0]; assertEquals("Test [" + i + "]=" + value, TEST_DATA[i][1], doubleMetaphone.doubleMetaphone(value, false)); } } /** * Test alternative encoding. */ public void testDoubleMetaphoneAlternate() { String value = null; for (int i = 0; i < TEST_DATA.length; i++) { value = TEST_DATA[i][0]; assertEquals("Test [" + i + "]=" + value, TEST_DATA[i][2], doubleMetaphone.doubleMetaphone(value, true)); } } /** Test values and their expected primary & alternate Double Metaphone encodings */ private static final String[][] TEST_DATA = new String[][] { new String[] {"ALLERTON", "ALRT", "ALRT"}, new String[] {"Acton", "AKTN", "AKTN"}, new String[] {"Adams", "ATMS", "ATMS"}, new String[] {"Aggar", "AKR", "AKR"}, new String[] {"Ahl", "AL", "AL"}, new String[] {"Aiken", "AKN", "AKN"}, new String[] {"Alan", "ALN", "ALN"}, new String[] {"Alcock", "ALKK", "ALKK"}, new String[] {"Alden", "ALTN", "ALTN"}, new String[] {"Aldham", "ALTM", "ALTM"}, new String[] {"Allen", "ALN", "ALN"}, new String[] {"Allerton", "ALRT", "ALRT"}, new String[] {"Alsop", "ALSP", "ALSP"}, new String[] {"Alwein", "ALN", "ALN"}, new String[] {"Ambler", "AMPL", "AMPL"}, new String[] {"Andevill", "ANTF", "ANTF"}, new String[] {"Andrews", "ANTR", "ANTR"}, new String[] {"Andreyco", "ANTR", "ANTR"}, new String[] {"Andriesse", "ANTR", "ANTR"}, new String[] {"Angier", "ANJ", "ANJR"}, new String[] {"Annabel", "ANPL", "ANPL"}, new String[] {"Anne", "AN", "AN"}, new String[] {"Anstye", "ANST", "ANST"}, new String[] {"Appling", "APLN", "APLN"}, new String[] {"Apuke", "APK", "APK"}, new String[] {"Arnold", "ARNL", "ARNL"}, new String[] {"Ashby", "AXP", "AXP"}, new String[] {"Astwood", "ASTT", "ASTT"}, new String[] {"Atkinson", "ATKN", "ATKN"}, new String[] {"Audley", "ATL", "ATL"}, new String[] {"Austin", "ASTN", "ASTN"}, new String[] {"Avenal", "AFNL", "AFNL"}, new String[] {"Ayer", "AR", "AR"}, new String[] {"Ayot", "AT", "AT"}, new String[] {"Babbitt", "PPT", "PPT"}, new String[] {"Bachelor", "PXLR", "PKLR"}, new String[] {"Bachelour", "PXLR", "PKLR"}, new String[] {"Bailey", "PL", "PL"}, new String[] {"Baivel", "PFL", "PFL"}, new String[] {"Baker", "PKR", "PKR"}, new String[] {"Baldwin", "PLTN", "PLTN"}, new String[] {"Balsley", "PLSL", "PLSL"}, new String[] {"Barber", "PRPR", "PRPR"}, new String[] {"Barker", "PRKR", "PRKR"}, new String[] {"Barlow", "PRL", "PRLF"}, new String[] {"Barnard", "PRNR", "PRNR"}, new String[] {"Barnes", "PRNS", "PRNS"}, new String[] {"Barnsley", "PRNS", "PRNS"}, new String[] {"Barouxis", "PRKS", "PRKS"}, new String[] {"Bartlet", "PRTL", "PRTL"}, new String[] {"Basley", "PSL", "PSL"}, new String[] {"Basset", "PST", "PST"}, new String[] {"Bassett", "PST", "PST"}, new String[] {"Batchlor", "PXLR", "PXLR"}, new String[] {"Bates", "PTS", "PTS"}, new String[] {"Batson", "PTSN", "PTSN"}, new String[] {"Bayes", "PS", "PS"}, new String[] {"Bayley", "PL", "PL"}, new String[] {"Beale", "PL", "PL"}, new String[] {"Beauchamp", "PXMP", "PKMP"}, new String[] {"Beauclerc", "PKLR", "PKLR"}, new String[] {"Beech", "PK", "PK"}, new String[] {"Beers", "PRS", "PRS"}, new String[] {"Beke", "PK", "PK"}, new String[] {"Belcher", "PLXR", "PLKR"}, new String[] {"Benjamin", "PNJM", "PNJM"}, new String[] {"Benningham", "PNNK", "PNNK"}, new String[] {"Bereford", "PRFR", "PRFR"}, new String[] {"Bergen", "PRJN", "PRKN"}, new String[] {"Berkeley", "PRKL", "PRKL"}, new String[] {"Berry", "PR", "PR"}, new String[] {"Besse", "PS", "PS"}, new String[] {"Bessey", "PS", "PS"}, new String[] {"Bessiles", "PSLS", "PSLS"}, new String[] {"Bigelow", "PJL", "PKLF"}, new String[] {"Bigg", "PK", "PK"}, new String[] {"Bigod", "PKT", "PKT"}, new String[] {"Billings", "PLNK", "PLNK"}, new String[] {"Bimper", "PMPR", "PMPR"}, new String[] {"Binker", "PNKR", "PNKR"}, new String[] {"Birdsill", "PRTS", "PRTS"}, new String[] {"Bishop", "PXP", "PXP"}, new String[] {"Black", "PLK", "PLK"}, new String[] {"Blagge", "PLK", "PLK"}, new String[] {"Blake", "PLK", "PLK"}, new String[] {"Blanck", "PLNK", "PLNK"}, new String[] {"Bledsoe", "PLTS", "PLTS"}, new String[] {"Blennerhasset","PLNR", "PLNR"}, new String[] {"Blessing", "PLSN", "PLSN"}, new String[] {"Blewett", "PLT", "PLT"}, new String[] {"Bloctgoed", "PLKT", "PLKT"}, new String[] {"Bloetgoet", "PLTK", "PLTK"}, new String[] {"Bloodgood", "PLTK", "PLTK"}, new String[] {"Blossom", "PLSM", "PLSM"}, new String[] {"Blount", "PLNT", "PLNT"}, new String[] {"Bodine", "PTN", "PTN"}, new String[] {"Bodman", "PTMN", "PTMN"}, new String[] {"BonCoeur", "PNKR", "PNKR"}, new String[] {"Bond", "PNT", "PNT"}, new String[] {"Boscawen", "PSKN", "PSKN"}, new String[] {"Bosworth", "PSR0", "PSRT"}, new String[] {"Bouchier", "PX", "PKR"}, new String[] {"Bowne", "PN", "PN"}, new String[] {"Bradbury", "PRTP", "PRTP"}, new String[] {"Bradder", "PRTR", "PRTR"}, new String[] {"Bradford", "PRTF", "PRTF"}, new String[] {"Bradstreet", "PRTS", "PRTS"}, new String[] {"Braham", "PRHM", "PRHM"}, new String[] {"Brailsford", "PRLS", "PRLS"}, new String[] {"Brainard", "PRNR", "PRNR"}, new String[] {"Brandish", "PRNT", "PRNT"}, new String[] {"Braun", "PRN", "PRN"}, new String[] {"Brecc", "PRK", "PRK"}, new String[] {"Brent", "PRNT", "PRNT"}, new String[] {"Brenton", "PRNT", "PRNT"}, new String[] {"Briggs", "PRKS", "PRKS"}, new String[] {"Brigham", "PRM", "PRM"}, new String[] {"Brobst", "PRPS", "PRPS"}, new String[] {"Brome", "PRM", "PRM"}, new String[] {"Bronson", "PRNS", "PRNS"}, new String[] {"Brooks", "PRKS", "PRKS"}, new String[] {"Brouillard", "PRLR", "PRLR"}, new String[] {"Brown", "PRN", "PRN"}, new String[] {"Browne", "PRN", "PRN"}, new String[] {"Brownell", "PRNL", "PRNL"}, new String[] {"Bruley", "PRL", "PRL"}, new String[] {"Bryant", "PRNT", "PRNT"}, new String[] {"Brzozowski", "PRSS", "PRTS"}, new String[] {"Buide", "PT", "PT"}, new String[] {"Bulmer", "PLMR", "PLMR"}, new String[] {"Bunker", "PNKR", "PNKR"}, new String[] {"Burden", "PRTN", "PRTN"}, new String[] {"Burge", "PRJ", "PRK"}, new String[] {"Burgoyne", "PRKN", "PRKN"}, new String[] {"Burke", "PRK", "PRK"}, new String[] {"Burnett", "PRNT", "PRNT"}, new String[] {"Burpee", "PRP", "PRP"}, new String[] {"Bursley", "PRSL", "PRSL"}, new String[] {"Burton", "PRTN", "PRTN"}, new String[] {"Bushnell", "PXNL", "PXNL"}, new String[] {"Buss", "PS", "PS"}, new String[] {"Buswell", "PSL", "PSL"}, new String[] {"Butler", "PTLR", "PTLR"}, new String[] {"Calkin", "KLKN", "KLKN"}, new String[] {"Canada", "KNT", "KNT"}, new String[] {"Canmore", "KNMR", "KNMR"}, new String[] {"Canney", "KN", "KN"}, new String[] {"Capet", "KPT", "KPT"}, new String[] {"Card", "KRT", "KRT"}, new String[] {"Carman", "KRMN", "KRMN"}, new String[] {"Carpenter", "KRPN", "KRPN"}, new String[] {"Cartwright", "KRTR", "KRTR"}, new String[] {"Casey", "KS", "KS"}, new String[] {"Catterfield", "KTRF", "KTRF"}, new String[] {"Ceeley", "SL", "SL"}, new String[] {"Chambers", "XMPR", "XMPR"}, new String[] {"Champion", "XMPN", "XMPN"}, new String[] {"Chapman", "XPMN", "XPMN"}, new String[] {"Chase", "XS", "XS"}, new String[] {"Cheney", "XN", "XN"}, new String[] {"Chetwynd", "XTNT", "XTNT"}, new String[] {"Chevalier", "XFL", "XFLR"}, new String[] {"Chillingsworth","XLNK", "XLNK"}, new String[] {"Christie", "KRST", "KRST"}, new String[] {"Chubbuck", "XPK", "XPK"}, new String[] {"Church", "XRX", "XRK"}, new String[] {"Clark", "KLRK", "KLRK"}, new String[] {"Clarke", "KLRK", "KLRK"}, new String[] {"Cleare", "KLR", "KLR"}, new String[] {"Clement", "KLMN", "KLMN"}, new String[] {"Clerke", "KLRK", "KLRK"}, new String[] {"Clibben", "KLPN", "KLPN"}, new String[] {"Clifford", "KLFR", "KLFR"}, new String[] {"Clivedon", "KLFT", "KLFT"}, new String[] {"Close", "KLS", "KLS"}, new String[] {"Clothilde", "KL0L", "KLTL"}, new String[] {"Cobb", "KP", "KP"}, new String[] {"Coburn", "KPRN", "KPRN"}, new String[] {"Coburne", "KPRN", "KPRN"}, new String[] {"Cocke", "KK", "KK"}, new String[] {"Coffin", "KFN", "KFN"}, new String[] {"Coffyn", "KFN", "KFN"}, new String[] {"Colborne", "KLPR", "KLPR"}, new String[] {"Colby", "KLP", "KLP"}, new String[] {"Cole", "KL", "KL"}, new String[] {"Coleman", "KLMN", "KLMN"}, new String[] {"Collier", "KL", "KLR"}, new String[] {"Compton", "KMPT", "KMPT"}, new String[] {"Cone", "KN", "KN"}, new String[] {"Cook", "KK", "KK"}, new String[] {"Cooke", "KK", "KK"}, new String[] {"Cooper", "KPR", "KPR"}, new String[] {"Copperthwaite","KPR0", "KPRT"}, new String[] {"Corbet", "KRPT", "KRPT"}, new String[] {"Corell", "KRL", "KRL"}, new String[] {"Corey", "KR", "KR"}, new String[] {"Corlies", "KRLS", "KRLS"}, new String[] {"Corneliszen", "KRNL", "KRNL"}, new String[] {"Cornelius", "KRNL", "KRNL"}, new String[] {"Cornwallis", "KRNL", "KRNL"}, new String[] {"Cosgrove", "KSKR", "KSKR"}, new String[] {"Count of Brionne","KNTF", "KNTF"}, new String[] {"Covill", "KFL", "KFL"}, new String[] {"Cowperthwaite","KPR0", "KPRT"}, new String[] {"Cowperwaite", "KPRT", "KPRT"}, new String[] {"Crane", "KRN", "KRN"}, new String[] {"Creagmile", "KRKM", "KRKM"}, new String[] {"Crew", "KR", "KRF"}, new String[] {"Crispin", "KRSP", "KRSP"}, new String[] {"Crocker", "KRKR", "KRKR"}, new String[] {"Crockett", "KRKT", "KRKT"}, new String[] {"Crosby", "KRSP", "KRSP"}, new String[] {"Crump", "KRMP", "KRMP"}, new String[] {"Cunningham", "KNNK", "KNNK"}, new String[] {"Curtis", "KRTS", "KRTS"}, new String[] {"Cutha", "K0", "KT"}, new String[] {"Cutter", "KTR", "KTR"}, new String[] {"D'Aubigny", "TPN", "TPKN"}, new String[] {"DAVIS", "TFS", "TFS"}, new String[] {"Dabinott", "TPNT", "TPNT"}, new String[] {"Dacre", "TKR", "TKR"}, new String[] {"Daggett", "TKT", "TKT"}, new String[] {"Danvers", "TNFR", "TNFR"}, new String[] {"Darcy", "TRS", "TRS"}, new String[] {"Davis", "TFS", "TFS"}, new String[] {"Dawn", "TN", "TN"}, new String[] {"Dawson", "TSN", "TSN"}, new String[] {"Day", "T", "T"}, new String[] {"Daye", "T", "T"}, new String[] {"DeGrenier", "TKRN", "TKRN"}, new String[] {"Dean", "TN", "TN"}, new String[] {"Deekindaugh", "TKNT", "TKNT"}, new String[] {"Dennis", "TNS", "TNS"}, new String[] {"Denny", "TN", "TN"}, new String[] {"Denton", "TNTN", "TNTN"}, new String[] {"Desborough", "TSPR", "TSPR"}, new String[] {"Despenser", "TSPN", "TSPN"}, new String[] {"Deverill", "TFRL", "TFRL"}, new String[] {"Devine", "TFN", "TFN"}, new String[] {"Dexter", "TKST", "TKST"}, new String[] {"Dillaway", "TL", "TL"}, new String[] {"Dimmick", "TMK", "TMK"}, new String[] {"Dinan", "TNN", "TNN"}, new String[] {"Dix", "TKS", "TKS"}, new String[] {"Doggett", "TKT", "TKT"}, new String[] {"Donahue", "TNH", "TNH"}, new String[] {"Dorfman", "TRFM", "TRFM"}, new String[] {"Dorris", "TRS", "TRS"}, new String[] {"Dow", "T", "TF"}, new String[] {"Downey", "TN", "TN"}, new String[] {"Downing", "TNNK", "TNNK"}, new String[] {"Dowsett", "TST", "TST"}, new String[] {"Duck?", "TK", "TK"}, new String[] {"Dudley", "TTL", "TTL"}, new String[] {"Duffy", "TF", "TF"}, new String[] {"Dunn", "TN", "TN"}, new String[] {"Dunsterville","TNST", "TNST"}, new String[] {"Durrant", "TRNT", "TRNT"}, new String[] {"Durrin", "TRN", "TRN"}, new String[] {"Dustin", "TSTN", "TSTN"}, new String[] {"Duston", "TSTN", "TSTN"}, new String[] {"Eames", "AMS", "AMS"}, new String[] {"Early", "ARL", "ARL"}, new String[] {"Easty", "AST", "AST"}, new String[] {"Ebbett", "APT", "APT"}, new String[] {"Eberbach", "APRP", "APRP"}, new String[] {"Eberhard", "APRR", "APRR"}, new String[] {"Eddy", "AT", "AT"}, new String[] {"Edenden", "ATNT", "ATNT"}, new String[] {"Edwards", "ATRT", "ATRT"}, new String[] {"Eglinton", "AKLN", "ALNT"}, new String[] {"Eliot", "ALT", "ALT"}, new String[] {"Elizabeth", "ALSP", "ALSP"}, new String[] {"Ellis", "ALS", "ALS"}, new String[] {"Ellison", "ALSN", "ALSN"}, new String[] {"Ellot", "ALT", "ALT"}, new String[] {"Elny", "ALN", "ALN"}, new String[] {"Elsner", "ALSN", "ALSN"}, new String[] {"Emerson", "AMRS", "AMRS"}, new String[] {"Empson", "AMPS", "AMPS"}, new String[] {"Est", "AST", "AST"}, new String[] {"Estabrook", "ASTP", "ASTP"}, new String[] {"Estes", "ASTS", "ASTS"}, new String[] {"Estey", "AST", "AST"}, new String[] {"Evans", "AFNS", "AFNS"}, new String[] {"Fallowell", "FLL", "FLL"}, new String[] {"Farnsworth", "FRNS", "FRNS"}, new String[] {"Feake", "FK", "FK"}, new String[] {"Feke", "FK", "FK"}, new String[] {"Fellows", "FLS", "FLS"}, new String[] {"Fettiplace", "FTPL", "FTPL"}, new String[] {"Finney", "FN", "FN"}, new String[] {"Fischer", "FXR", "FSKR"}, new String[] {"Fisher", "FXR", "FXR"}, new String[] {"Fisk", "FSK", "FSK"}, new String[] {"Fiske", "FSK", "FSK"}, new String[] {"Fletcher", "FLXR", "FLXR"}, new String[] {"Folger", "FLKR", "FLJR"}, new String[] {"Foliot", "FLT", "FLT"}, new String[] {"Folyot", "FLT", "FLT"}, new String[] {"Fones", "FNS", "FNS"}, new String[] {"Fordham", "FRTM", "FRTM"}, new String[] {"Forstner", "FRST", "FRST"}, new String[] {"Fosten", "FSTN", "FSTN"}, new String[] {"Foster", "FSTR", "FSTR"}, new String[] {"Foulke", "FLK", "FLK"}, new String[] {"Fowler", "FLR", "FLR"}, new String[] {"Foxwell", "FKSL", "FKSL"}, new String[] {"Fraley", "FRL", "FRL"}, new String[] {"Franceys", "FRNS", "FRNS"}, new String[] {"Franke", "FRNK", "FRNK"}, new String[] {"Frascella", "FRSL", "FRSL"}, new String[] {"Frazer", "FRSR", "FRSR"}, new String[] {"Fredd", "FRT", "FRT"}, new String[] {"Freeman", "FRMN", "FRMN"}, new String[] {"French", "FRNX", "FRNK"}, new String[] {"Freville", "FRFL", "FRFL"}, new String[] {"Frey", "FR", "FR"}, new String[] {"Frick", "FRK", "FRK"}, new String[] {"Frier", "FR", "FRR"}, new String[] {"Froe", "FR", "FR"}, new String[] {"Frorer", "FRRR", "FRRR"}, new String[] {"Frost", "FRST", "FRST"}, new String[] {"Frothingham", "FR0N", "FRTN"}, new String[] {"Fry", "FR", "FR"}, new String[] {"Gaffney", "KFN", "KFN"}, new String[] {"Gage", "KJ", "KK"}, new String[] {"Gallion", "KLN", "KLN"}, new String[] {"Gallishan", "KLXN", "KLXN"}, new String[] {"Gamble", "KMPL", "KMPL"}, new String[] {"Garbrand", "KRPR", "KRPR"}, new String[] {"Gardner", "KRTN", "KRTN"}, new String[] {"Garrett", "KRT", "KRT"}, new String[] {"Gassner", "KSNR", "KSNR"}, new String[] {"Gater", "KTR", "KTR"}, new String[] {"Gaunt", "KNT", "KNT"}, new String[] {"Gayer", "KR", "KR"}, new String[] {"Gerken", "KRKN", "JRKN"}, new String[] {"Gerritsen", "KRTS", "JRTS"}, new String[] {"Gibbs", "KPS", "JPS"}, new String[] {"Giffard", "JFRT", "KFRT"}, new String[] {"Gilbert", "KLPR", "JLPR"}, new String[] {"Gill", "KL", "JL"}, new String[] {"Gilman", "KLMN", "JLMN"}, new String[] {"Glass", "KLS", "KLS"}, new String[] {"Goddard\\Gifford","KTRT", "KTRT"}, new String[] {"Godfrey", "KTFR", "KTFR"}, new String[] {"Godwin", "KTN", "KTN"}, new String[] {"Goodale", "KTL", "KTL"}, new String[] {"Goodnow", "KTN", "KTNF"}, new String[] {"Gorham", "KRM", "KRM"}, new String[] {"Goseline", "KSLN", "KSLN"}, new String[] {"Gott", "KT", "KT"}, new String[] {"Gould", "KLT", "KLT"}, new String[] {"Grafton", "KRFT", "KRFT"}, new String[] {"Grant", "KRNT", "KRNT"}, new String[] {"Gray", "KR", "KR"}, new String[] {"Green", "KRN", "KRN"}, new String[] {"Griffin", "KRFN", "KRFN"}, new String[] {"Grill", "KRL", "KRL"}, new String[] {"Grim", "KRM", "KRM"}, new String[] {"Grisgonelle", "KRSK", "KRSK"}, new String[] {"Gross", "KRS", "KRS"}, new String[] {"Guba", "KP", "KP"}, new String[] {"Gybbes", "KPS", "JPS"}, new String[] {"Haburne", "HPRN", "HPRN"}, new String[] {"Hackburne", "HKPR", "HKPR"}, new String[] {"Haddon?", "HTN", "HTN"}, new String[] {"Haines", "HNS", "HNS"}, new String[] {"Hale", "HL", "HL"}, new String[] {"Hall", "HL", "HL"}, new String[] {"Hallet", "HLT", "HLT"}, new String[] {"Hallock", "HLK", "HLK"}, new String[] {"Halstead", "HLST", "HLST"}, new String[] {"Hammond", "HMNT", "HMNT"}, new String[] {"Hance", "HNS", "HNS"}, new String[] {"Handy", "HNT", "HNT"}, new String[] {"Hanson", "HNSN", "HNSN"}, new String[] {"Harasek", "HRSK", "HRSK"}, new String[] {"Harcourt", "HRKR", "HRKR"}, new String[] {"Hardy", "HRT", "HRT"}, new String[] {"Harlock", "HRLK", "HRLK"}, new String[] {"Harris", "HRS", "HRS"}, new String[] {"Hartley", "HRTL", "HRTL"}, new String[] {"Harvey", "HRF", "HRF"}, new String[] {"Harvie", "HRF", "HRF"}, new String[] {"Harwood", "HRT", "HRT"}, new String[] {"Hathaway", "H0", "HT"}, new String[] {"Haukeness", "HKNS", "HKNS"}, new String[] {"Hawkes", "HKS", "HKS"}, new String[] {"Hawkhurst", "HKRS", "HKRS"}, new String[] {"Hawkins", "HKNS", "HKNS"}, new String[] {"Hawley", "HL", "HL"}, new String[] {"Heald", "HLT", "HLT"}, new String[] {"Helsdon", "HLST", "HLST"}, new String[] {"Hemenway", "HMN", "HMN"}, new String[] {"Hemmenway", "HMN", "HMN"}, new String[] {"Henck", "HNK", "HNK"}, new String[] {"Henderson", "HNTR", "HNTR"}, new String[] {"Hendricks", "HNTR", "HNTR"}, new String[] {"Hersey", "HRS", "HRS"}, new String[] {"Hewes", "HS", "HS"}, new String[] {"Heyman", "HMN", "HMN"}, new String[] {"Hicks", "HKS", "HKS"}, new String[] {"Hidden", "HTN", "HTN"}, new String[] {"Higgs", "HKS", "HKS"}, new String[] {"Hill", "HL", "HL"}, new String[] {"Hills", "HLS", "HLS"}, new String[] {"Hinckley", "HNKL", "HNKL"}, new String[] {"Hipwell", "HPL", "HPL"}, new String[] {"Hobart", "HPRT", "HPRT"}, new String[] {"Hoben", "HPN", "HPN"}, new String[] {"Hoffmann", "HFMN", "HFMN"}, new String[] {"Hogan", "HKN", "HKN"}, new String[] {"Holmes", "HLMS", "HLMS"}, new String[] {"Hoo", "H", "H"}, new String[] {"Hooker", "HKR", "HKR"}, new String[] {"Hopcott", "HPKT", "HPKT"}, new String[] {"Hopkins", "HPKN", "HPKN"}, new String[] {"Hopkinson", "HPKN", "HPKN"}, new String[] {"Hornsey", "HRNS", "HRNS"}, new String[] {"Houckgeest", "HKJS", "HKKS"}, new String[] {"Hough", "H", "H"}, new String[] {"Houstin", "HSTN", "HSTN"}, new String[] {"How", "H", "HF"}, new String[] {"Howe", "H", "H"}, new String[] {"Howland", "HLNT", "HLNT"}, new String[] {"Hubner", "HPNR", "HPNR"}, new String[] {"Hudnut", "HTNT", "HTNT"}, new String[] {"Hughes", "HS", "HS"}, new String[] {"Hull", "HL", "HL"}, new String[] {"Hulme", "HLM", "HLM"}, new String[] {"Hume", "HM", "HM"}, new String[] {"Hundertumark","HNTR", "HNTR"}, new String[] {"Hundley", "HNTL", "HNTL"}, new String[] {"Hungerford", "HNKR", "HNJR"}, new String[] {"Hunt", "HNT", "HNT"}, new String[] {"Hurst", "HRST", "HRST"}, new String[] {"Husbands", "HSPN", "HSPN"}, new String[] {"Hussey", "HS", "HS"}, new String[] {"Husted", "HSTT", "HSTT"}, new String[] {"Hutchins", "HXNS", "HXNS"}, new String[] {"Hutchinson", "HXNS", "HXNS"}, new String[] {"Huttinger", "HTNK", "HTNJ"}, new String[] {"Huybertsen", "HPRT", "HPRT"}, new String[] {"Iddenden", "ATNT", "ATNT"}, new String[] {"Ingraham", "ANKR", "ANKR"}, new String[] {"Ives", "AFS", "AFS"}, new String[] {"Jackson", "JKSN", "AKSN"}, new String[] {"Jacob", "JKP", "AKP"}, new String[] {"Jans", "JNS", "ANS"}, new String[] {"Jenkins", "JNKN", "ANKN"}, new String[] {"Jewett", "JT", "AT"}, new String[] {"Jewitt", "JT", "AT"}, new String[] {"Johnson", "JNSN", "ANSN"}, new String[] {"Jones", "JNS", "ANS"}, new String[] {"Josephine", "JSFN", "HSFN"}, new String[] {"Judd", "JT", "AT"}, new String[] {"June", "JN", "AN"}, new String[] {"Kamarowska", "KMRS", "KMRS"}, new String[] {"Kay", "K", "K"}, new String[] {"Kelley", "KL", "KL"}, new String[] {"Kelly", "KL", "KL"}, new String[] {"Keymber", "KMPR", "KMPR"}, new String[] {"Keynes", "KNS", "KNS"}, new String[] {"Kilham", "KLM", "KLM"}, new String[] {"Kim", "KM", "KM"}, new String[] {"Kimball", "KMPL", "KMPL"}, new String[] {"King", "KNK", "KNK"}, new String[] {"Kinsey", "KNS", "KNS"}, new String[] {"Kirk", "KRK", "KRK"}, new String[] {"Kirton", "KRTN", "KRTN"}, new String[] {"Kistler", "KSTL", "KSTL"}, new String[] {"Kitchen", "KXN", "KXN"}, new String[] {"Kitson", "KTSN", "KTSN"}, new String[] {"Klett", "KLT", "KLT"}, new String[] {"Kline", "KLN", "KLN"}, new String[] {"Knapp", "NP", "NP"}, new String[] {"Knight", "NT", "NT"}, new String[] {"Knote", "NT", "NT"}, new String[] {"Knott", "NT", "NT"}, new String[] {"Knox", "NKS", "NKS"}, new String[] {"Koeller", "KLR", "KLR"}, new String[] {"La Pointe", "LPNT", "LPNT"}, new String[] {"LaPlante", "LPLN", "LPLN"}, new String[] {"Laimbeer", "LMPR", "LMPR"}, new String[] {"Lamb", "LMP", "LMP"}, new String[] {"Lambertson", "LMPR", "LMPR"}, new String[] {"Lancto", "LNKT", "LNKT"}, new String[] {"Landry", "LNTR", "LNTR"}, new String[] {"Lane", "LN", "LN"}, new String[] {"Langendyck", "LNJN", "LNKN"}, new String[] {"Langer", "LNKR", "LNJR"}, new String[] {"Langford", "LNKF", "LNKF"}, new String[] {"Lantersee", "LNTR", "LNTR"}, new String[] {"Laquer", "LKR", "LKR"}, new String[] {"Larkin", "LRKN", "LRKN"}, new String[] {"Latham", "LTM", "LTM"}, new String[] {"Lathrop", "L0RP", "LTRP"}, new String[] {"Lauter", "LTR", "LTR"}, new String[] {"Lawrence", "LRNS", "LRNS"}, new String[] {"Leach", "LK", "LK"}, new String[] {"Leager", "LKR", "LJR"}, new String[] {"Learned", "LRNT", "LRNT"}, new String[] {"Leavitt", "LFT", "LFT"}, new String[] {"Lee", "L", "L"}, new String[] {"Leete", "LT", "LT"}, new String[] {"Leggett", "LKT", "LKT"}, new String[] {"Leland", "LLNT", "LLNT"}, new String[] {"Leonard", "LNRT", "LNRT"}, new String[] {"Lester", "LSTR", "LSTR"}, new String[] {"Lestrange", "LSTR", "LSTR"}, new String[] {"Lethem", "L0M", "LTM"}, new String[] {"Levine", "LFN", "LFN"}, new String[] {"Lewes", "LS", "LS"}, new String[] {"Lewis", "LS", "LS"}, new String[] {"Lincoln", "LNKL", "LNKL"}, new String[] {"Lindsey", "LNTS", "LNTS"}, new String[] {"Linher", "LNR", "LNR"}, new String[] {"Lippet", "LPT", "LPT"}, new String[] {"Lippincott", "LPNK", "LPNK"}, new String[] {"Lockwood", "LKT", "LKT"}, new String[] {"Loines", "LNS", "LNS"}, new String[] {"Lombard", "LMPR", "LMPR"}, new String[] {"Long", "LNK", "LNK"}, new String[] {"Longespee", "LNJS", "LNKS"}, new String[] {"Look", "LK", "LK"}, new String[] {"Lounsberry", "LNSP", "LNSP"}, new String[] {"Lounsbury", "LNSP", "LNSP"}, new String[] {"Louthe", "L0", "LT"}, new String[] {"Loveyne", "LFN", "LFN"}, new String[] {"Lowe", "L", "L"}, new String[] {"Ludlam", "LTLM", "LTLM"}, new String[] {"Lumbard", "LMPR", "LMPR"}, new String[] {"Lund", "LNT", "LNT"}, new String[] {"Luno", "LN", "LN"}, new String[] {"Lutz", "LTS", "LTS"}, new String[] {"Lydia", "LT", "LT"}, new String[] {"Lynne", "LN", "LN"}, new String[] {"Lyon", "LN", "LN"}, new String[] {"MacAlpin", "MKLP", "MKLP"}, new String[] {"MacBricc", "MKPR", "MKPR"}, new String[] {"MacCrinan", "MKRN", "MKRN"}, new String[] {"MacKenneth", "MKN0", "MKNT"}, new String[] {"MacMael nam Bo","MKML", "MKML"}, new String[] {"MacMurchada", "MKMR", "MKMR"}, new String[] {"Macomber", "MKMP", "MKMP"}, new String[] {"Macy", "MS", "MS"}, new String[] {"Magnus", "MNS", "MKNS"}, new String[] {"Mahien", "MHN", "MHN"}, new String[] {"Malmains", "MLMN", "MLMN"}, new String[] {"Malory", "MLR", "MLR"}, new String[] {"Mancinelli", "MNSN", "MNSN"}, new String[] {"Mancini", "MNSN", "MNSN"}, new String[] {"Mann", "MN", "MN"}, new String[] {"Manning", "MNNK", "MNNK"}, new String[] {"Manter", "MNTR", "MNTR"}, new String[] {"Marion", "MRN", "MRN"}, new String[] {"Marley", "MRL", "MRL"}, new String[] {"Marmion", "MRMN", "MRMN"}, new String[] {"Marquart", "MRKR", "MRKR"}, new String[] {"Marsh", "MRX", "MRX"}, new String[] {"Marshal", "MRXL", "MRXL"}, new String[] {"Marshall", "MRXL", "MRXL"}, new String[] {"Martel", "MRTL", "MRTL"}, new String[] {"Martha", "MR0", "MRT"}, new String[] {"Martin", "MRTN", "MRTN"}, new String[] {"Marturano", "MRTR", "MRTR"}, new String[] {"Marvin", "MRFN", "MRFN"}, new String[] {"Mary", "MR", "MR"}, new String[] {"Mason", "MSN", "MSN"}, new String[] {"Maxwell", "MKSL", "MKSL"}, new String[] {"Mayhew", "MH", "MHF"}, new String[] {"McAllaster", "MKLS", "MKLS"}, new String[] {"McAllister", "MKLS", "MKLS"}, new String[] {"McConnell", "MKNL", "MKNL"}, new String[] {"McFarland", "MKFR", "MKFR"}, new String[] {"McIlroy", "MSLR", "MSLR"}, new String[] {"McNair", "MKNR", "MKNR"}, new String[] {"McNair-Landry","MKNR", "MKNR"}, new String[] {"McRaven", "MKRF", "MKRF"}, new String[] {"Mead", "MT", "MT"}, new String[] {"Meade", "MT", "MT"}, new String[] {"Meck", "MK", "MK"}, new String[] {"Melton", "MLTN", "MLTN"}, new String[] {"Mendenhall", "MNTN", "MNTN"}, new String[] {"Mering", "MRNK", "MRNK"}, new String[] {"Merrick", "MRK", "MRK"}, new String[] {"Merry", "MR", "MR"}, new String[] {"Mighill", "ML", "ML"}, new String[] {"Miller", "MLR", "MLR"}, new String[] {"Milton", "MLTN", "MLTN"}, new String[] {"Mohun", "MHN", "MHN"}, new String[] {"Montague", "MNTK", "MNTK"}, new String[] {"Montboucher", "MNTP", "MNTP"}, new String[] {"Moore", "MR", "MR"}, new String[] {"Morrel", "MRL", "MRL"}, new String[] {"Morrill", "MRL", "MRL"}, new String[] {"Morris", "MRS", "MRS"}, new String[] {"Morton", "MRTN", "MRTN"}, new String[] {"Moton", "MTN", "MTN"}, new String[] {"Muir", "MR", "MR"}, new String[] {"Mulferd", "MLFR", "MLFR"}, new String[] {"Mullins", "MLNS", "MLNS"}, new String[] {"Mulso", "MLS", "MLS"}, new String[] {"Munger", "MNKR", "MNJR"}, new String[] {"Munt", "MNT", "MNT"}, new String[] {"Murchad", "MRXT", "MRKT"}, new String[] {"Murdock", "MRTK", "MRTK"}, new String[] {"Murray", "MR", "MR"}, new String[] {"Muskett", "MSKT", "MSKT"}, new String[] {"Myers", "MRS", "MRS"}, new String[] {"Myrick", "MRK", "MRK"}, new String[] {"NORRIS", "NRS", "NRS"}, new String[] {"Nayle", "NL", "NL"}, new String[] {"Newcomb", "NKMP", "NKMP"}, new String[] {"Newcomb(e)", "NKMP", "NKMP"}, new String[] {"Newkirk", "NKRK", "NKRK"}, new String[] {"Newton", "NTN", "NTN"}, new String[] {"Niles", "NLS", "NLS"}, new String[] {"Noble", "NPL", "NPL"}, new String[] {"Noel", "NL", "NL"}, new String[] {"Northend", "NR0N", "NRTN"}, new String[] {"Norton", "NRTN", "NRTN"}, new String[] {"Nutter", "NTR", "NTR"}, new String[] {"Odding", "ATNK", "ATNK"}, new String[] {"Odenbaugh", "ATNP", "ATNP"}, new String[] {"Ogborn", "AKPR", "AKPR"}, new String[] {"Oppenheimer", "APNM", "APNM"}, new String[] {"Otis", "ATS", "ATS"}, new String[] {"Oviatt", "AFT", "AFT"}, new String[] {"PRUST?", "PRST", "PRST"}, new String[] {"Paddock", "PTK", "PTK"}, new String[] {"Page", "PJ", "PK"}, new String[] {"Paine", "PN", "PN"}, new String[] {"Paist", "PST", "PST"}, new String[] {"Palmer", "PLMR", "PLMR"}, new String[] {"Park", "PRK", "PRK"}, new String[] {"Parker", "PRKR", "PRKR"}, new String[] {"Parkhurst", "PRKR", "PRKR"}, new String[] {"Parrat", "PRT", "PRT"}, new String[] {"Parsons", "PRSN", "PRSN"}, new String[] {"Partridge", "PRTR", "PRTR"}, new String[] {"Pashley", "PXL", "PXL"}, new String[] {"Pasley", "PSL", "PSL"}, new String[] {"Patrick", "PTRK", "PTRK"}, new String[] {"Pattee", "PT", "PT"}, new String[] {"Patten", "PTN", "PTN"}, new String[] {"Pawley", "PL", "PL"}, new String[] {"Payne", "PN", "PN"}, new String[] {"Peabody", "PPT", "PPT"}, new String[] {"Peake", "PK", "PK"}, new String[] {"Pearson", "PRSN", "PRSN"}, new String[] {"Peat", "PT", "PT"}, new String[] {"Pedersen", "PTRS", "PTRS"}, new String[] {"Percy", "PRS", "PRS"}, new String[] {"Perkins", "PRKN", "PRKN"}, new String[] {"Perrine", "PRN", "PRN"}, new String[] {"Perry", "PR", "PR"}, new String[] {"Peson", "PSN", "PSN"}, new String[] {"Peterson", "PTRS", "PTRS"}, new String[] {"Peyton", "PTN", "PTN"}, new String[] {"Phinney", "FN", "FN"}, new String[] {"Pickard", "PKRT", "PKRT"}, new String[] {"Pierce", "PRS", "PRS"}, new String[] {"Pierrepont", "PRPN", "PRPN"}, new String[] {"Pike", "PK", "PK"}, new String[] {"Pinkham", "PNKM", "PNKM"}, new String[] {"Pitman", "PTMN", "PTMN"}, new String[] {"Pitt", "PT", "PT"}, new String[] {"Pitts", "PTS", "PTS"}, new String[] {"Plantagenet", "PLNT", "PLNT"}, new String[] {"Platt", "PLT", "PLT"}, new String[] {"Platts", "PLTS", "PLTS"}, new String[] {"Pleis", "PLS", "PLS"}, new String[] {"Pleiss", "PLS", "PLS"}, new String[] {"Plisko", "PLSK", "PLSK"}, new String[] {"Pliskovitch", "PLSK", "PLSK"}, new String[] {"Plum", "PLM", "PLM"}, new String[] {"Plume", "PLM", "PLM"}, new String[] {"Poitou", "PT", "PT"}, new String[] {"Pomeroy", "PMR", "PMR"}, new String[] {"Poretiers", "PRTR", "PRTR"}, new String[] {"Pote", "PT", "PT"}, new String[] {"Potter", "PTR", "PTR"}, new String[] {"Potts", "PTS", "PTS"}, new String[] {"Powell", "PL", "PL"}, new String[] {"Pratt", "PRT", "PRT"}, new String[] {"Presbury", "PRSP", "PRSP"}, new String[] {"Priest", "PRST", "PRST"}, new String[] {"Prindle", "PRNT", "PRNT"}, new String[] {"Prior", "PRR", "PRR"}, new String[] {"Profumo", "PRFM", "PRFM"}, new String[] {"Purdy", "PRT", "PRT"}, new String[] {"Purefoy", "PRF", "PRF"}, new String[] {"Pury", "PR", "PR"}, new String[] {"Quinter", "KNTR", "KNTR"}, new String[] {"Rachel", "RXL", "RKL"}, new String[] {"Rand", "RNT", "RNT"}, new String[] {"Rankin", "RNKN", "RNKN"}, new String[] {"Ravenscroft", "RFNS", "RFNS"}, new String[] {"Raynsford", "RNSF", "RNSF"}, new String[] {"Reakirt", "RKRT", "RKRT"}, new String[] {"Reaves", "RFS", "RFS"}, new String[] {"Reeves", "RFS", "RFS"}, new String[] {"Reichert", "RXRT", "RKRT"}, new String[] {"Remmele", "RML", "RML"}, new String[] {"Reynolds", "RNLT", "RNLT"}, new String[] {"Rhodes", "RTS", "RTS"}, new String[] {"Richards", "RXRT", "RKRT"}, new String[] {"Richardson", "RXRT", "RKRT"}, new String[] {"Ring", "RNK", "RNK"}, new String[] {"Roberts", "RPRT", "RPRT"}, new String[] {"Robertson", "RPRT", "RPRT"}, new String[] {"Robson", "RPSN", "RPSN"}, new String[] {"Rodie", "RT", "RT"}, new String[] {"Rody", "RT", "RT"}, new String[] {"Rogers", "RKRS", "RJRS"}, new String[] {"Ross", "RS", "RS"}, new String[] {"Rosslevin", "RSLF", "RSLF"}, new String[] {"Rowland", "RLNT", "RLNT"}, new String[] {"Ruehl", "RL", "RL"}, new String[] {"Russell", "RSL", "RSL"}, new String[] {"Ruth", "R0", "RT"}, new String[] {"Ryan", "RN", "RN"}, new String[] {"Rysse", "RS", "RS"}, new String[] {"Sadler", "STLR", "STLR"}, new String[] {"Salmon", "SLMN", "SLMN"}, new String[] {"Salter", "SLTR", "SLTR"}, new String[] {"Salvatore", "SLFT", "SLFT"}, new String[] {"Sanders", "SNTR", "SNTR"}, new String[] {"Sands", "SNTS", "SNTS"}, new String[] {"Sanford", "SNFR", "SNFR"}, new String[] {"Sanger", "SNKR", "SNJR"}, new String[] {"Sargent", "SRJN", "SRKN"}, new String[] {"Saunders", "SNTR", "SNTR"}, new String[] {"Schilling", "XLNK", "XLNK"}, new String[] {"Schlegel", "XLKL", "SLKL"}, new String[] {"Scott", "SKT", "SKT"}, new String[] {"Sears", "SRS", "SRS"}, new String[] {"Segersall", "SJRS", "SKRS"}, new String[] {"Senecal", "SNKL", "SNKL"}, new String[] {"Sergeaux", "SRJ", "SRK"}, new String[] {"Severance", "SFRN", "SFRN"}, new String[] {"Sharp", "XRP", "XRP"}, new String[] {"Sharpe", "XRP", "XRP"}, new String[] {"Sharply", "XRPL", "XRPL"}, new String[] {"Shatswell", "XTSL", "XTSL"}, new String[] {"Shattack", "XTK", "XTK"}, new String[] {"Shattock", "XTK", "XTK"}, new String[] {"Shattuck", "XTK", "XTK"}, new String[] {"Shaw", "X", "XF"}, new String[] {"Sheldon", "XLTN", "XLTN"}, new String[] {"Sherman", "XRMN", "XRMN"}, new String[] {"Shinn", "XN", "XN"}, new String[] {"Shirford", "XRFR", "XRFR"}, new String[] {"Shirley", "XRL", "XRL"}, new String[] {"Shively", "XFL", "XFL"}, new String[] {"Shoemaker", "XMKR", "XMKR"}, new String[] {"Short", "XRT", "XRT"}, new String[] {"Shotwell", "XTL", "XTL"}, new String[] {"Shute", "XT", "XT"}, new String[] {"Sibley", "SPL", "SPL"}, new String[] {"Silver", "SLFR", "SLFR"}, new String[] {"Simes", "SMS", "SMS"}, new String[] {"Sinken", "SNKN", "SNKN"}, new String[] {"Sinn", "SN", "SN"}, new String[] {"Skelton", "SKLT", "SKLT"}, new String[] {"Skiffe", "SKF", "SKF"}, new String[] {"Skotkonung", "SKTK", "SKTK"}, new String[] {"Slade", "SLT", "XLT"}, new String[] {"Slye", "SL", "XL"}, new String[] {"Smedley", "SMTL", "XMTL"}, new String[] {"Smith", "SM0", "XMT"}, new String[] {"Snow", "SN", "XNF"}, new String[] {"Soole", "SL", "SL"}, new String[] {"Soule", "SL", "SL"}, new String[] {"Southworth", "S0R0", "STRT"}, new String[] {"Sowles", "SLS", "SLS"}, new String[] {"Spalding", "SPLT", "SPLT"}, new String[] {"Spark", "SPRK", "SPRK"}, new String[] {"Spencer", "SPNS", "SPNS"}, new String[] {"Sperry", "SPR", "SPR"}, new String[] {"Spofford", "SPFR", "SPFR"}, new String[] {"Spooner", "SPNR", "SPNR"}, new String[] {"Sprague", "SPRK", "SPRK"}, new String[] {"Springer", "SPRN", "SPRN"}, new String[] {"St. Clair", "STKL", "STKL"}, new String[] {"St. Claire", "STKL", "STKL"}, new String[] {"St. Leger", "STLJ", "STLK"}, new String[] {"St. Omer", "STMR", "STMR"}, new String[] {"Stafferton", "STFR", "STFR"}, new String[] {"Stafford", "STFR", "STFR"}, new String[] {"Stalham", "STLM", "STLM"}, new String[] {"Stanford", "STNF", "STNF"}, new String[] {"Stanton", "STNT", "STNT"}, new String[] {"Star", "STR", "STR"}, new String[] {"Starbuck", "STRP", "STRP"}, new String[] {"Starkey", "STRK", "STRK"}, new String[] {"Starkweather","STRK", "STRK"}, new String[] {"Stearns", "STRN", "STRN"}, new String[] {"Stebbins", "STPN", "STPN"}, new String[] {"Steele", "STL", "STL"}, new String[] {"Stephenson", "STFN", "STFN"}, new String[] {"Stevens", "STFN", "STFN"}, new String[] {"Stoddard", "STTR", "STTR"}, new String[] {"Stodder", "STTR", "STTR"}, new String[] {"Stone", "STN", "STN"}, new String[] {"Storey", "STR", "STR"}, new String[] {"Storrada", "STRT", "STRT"}, new String[] {"Story", "STR", "STR"}, new String[] {"Stoughton", "STFT", "STFT"}, new String[] {"Stout", "STT", "STT"}, new String[] {"Stow", "ST", "STF"}, new String[] {"Strong", "STRN", "STRN"}, new String[] {"Strutt", "STRT", "STRT"}, new String[] {"Stryker", "STRK", "STRK"}, new String[] {"Stuckeley", "STKL", "STKL"}, new String[] {"Sturges", "STRJ", "STRK"}, new String[] {"Sturgess", "STRJ", "STRK"}, new String[] {"Sturgis", "STRJ", "STRK"}, new String[] {"Suevain", "SFN", "SFN"}, new String[] {"Sulyard", "SLRT", "SLRT"}, new String[] {"Sutton", "STN", "STN"}, new String[] {"Swain", "SN", "XN"}, new String[] {"Swayne", "SN", "XN"}, new String[] {"Swayze", "SS", "XTS"}, new String[] {"Swift", "SFT", "XFT"}, new String[] {"Taber", "TPR", "TPR"}, new String[] {"Talcott", "TLKT", "TLKT"}, new String[] {"Tarne", "TRN", "TRN"}, new String[] {"Tatum", "TTM", "TTM"}, new String[] {"Taverner", "TFRN", "TFRN"}, new String[] {"Taylor", "TLR", "TLR"}, new String[] {"Tenney", "TN", "TN"}, new String[] {"Thayer", "0R", "TR"}, new String[] {"Thember", "0MPR", "TMPR"}, new String[] {"Thomas", "TMS", "TMS"}, new String[] {"Thompson", "TMPS", "TMPS"}, new String[] {"Thorne", "0RN", "TRN"}, new String[] {"Thornycraft", "0RNK", "TRNK"}, new String[] {"Threlkeld", "0RLK", "TRLK"}, new String[] {"Throckmorton","0RKM", "TRKM"}, new String[] {"Thwaits", "0TS", "TTS"}, new String[] {"Tibbetts", "TPTS", "TPTS"}, new String[] {"Tidd", "TT", "TT"}, new String[] {"Tierney", "TRN", "TRN"}, new String[] {"Tilley", "TL", "TL"}, new String[] {"Tillieres", "TLRS", "TLRS"}, new String[] {"Tilly", "TL", "TL"}, new String[] {"Tisdale", "TSTL", "TSTL"}, new String[] {"Titus", "TTS", "TTS"}, new String[] {"Tobey", "TP", "TP"}, new String[] {"Tooker", "TKR", "TKR"}, new String[] {"Towle", "TL", "TL"}, new String[] {"Towne", "TN", "TN"}, new String[] {"Townsend", "TNSN", "TNSN"}, new String[] {"Treadway", "TRT", "TRT"}, new String[] {"Trelawney", "TRLN", "TRLN"}, new String[] {"Trinder", "TRNT", "TRNT"}, new String[] {"Tripp", "TRP", "TRP"}, new String[] {"Trippe", "TRP", "TRP"}, new String[] {"Trott", "TRT", "TRT"}, new String[] {"True", "TR", "TR"}, new String[] {"Trussebut", "TRSP", "TRSP"}, new String[] {"Tucker", "TKR", "TKR"}, new String[] {"Turgeon", "TRJN", "TRKN"}, new String[] {"Turner", "TRNR", "TRNR"}, new String[] {"Tuttle", "TTL", "TTL"}, new String[] {"Tyler", "TLR", "TLR"}, new String[] {"Tylle", "TL", "TL"}, new String[] {"Tyrrel", "TRL", "TRL"}, new String[] {"Ua Tuathail", "AT0L", "ATTL"}, new String[] {"Ulrich", "ALRX", "ALRK"}, new String[] {"Underhill", "ANTR", "ANTR"}, new String[] {"Underwood", "ANTR", "ANTR"}, new String[] {"Unknown", "ANKN", "ANKN"}, new String[] {"Valentine", "FLNT", "FLNT"}, new String[] {"Van Egmond", "FNKM", "FNKM"}, new String[] {"Van der Beek","FNTR", "FNTR"}, new String[] {"Vaughan", "FKN", "FKN"}, new String[] {"Vermenlen", "FRMN", "FRMN"}, new String[] {"Vincent", "FNSN", "FNSN"}, new String[] {"Volentine", "FLNT", "FLNT"}, new String[] {"Wagner", "AKNR", "FKNR"}, new String[] {"Waite", "AT", "FT"}, new String[] {"Walker", "ALKR", "FLKR"}, new String[] {"Walter", "ALTR", "FLTR"}, new String[] {"Wandell", "ANTL", "FNTL"}, new String[] {"Wandesford", "ANTS", "FNTS"}, new String[] {"Warbleton", "ARPL", "FRPL"}, new String[] {"Ward", "ART", "FRT"}, new String[] {"Warde", "ART", "FRT"}, new String[] {"Ware", "AR", "FR"}, new String[] {"Wareham", "ARHM", "FRHM"}, new String[] {"Warner", "ARNR", "FRNR"}, new String[] {"Warren", "ARN", "FRN"}, new String[] {"Washburne", "AXPR", "FXPR"}, new String[] {"Waterbury", "ATRP", "FTRP"}, new String[] {"Watson", "ATSN", "FTSN"}, new String[] {"WatsonEllithorpe","ATSN", "FTSN"}, new String[] {"Watts", "ATS", "FTS"}, new String[] {"Wayne", "AN", "FN"}, new String[] {"Webb", "AP", "FP"}, new String[] {"Weber", "APR", "FPR"}, new String[] {"Webster", "APST", "FPST"}, new String[] {"Weed", "AT", "FT"}, new String[] {"Weeks", "AKS", "FKS"}, new String[] {"Wells", "ALS", "FLS"}, new String[] {"Wenzell", "ANSL", "FNTS"}, new String[] {"West", "AST", "FST"}, new String[] {"Westbury", "ASTP", "FSTP"}, new String[] {"Whatlocke", "ATLK", "ATLK"}, new String[] {"Wheeler", "ALR", "ALR"}, new String[] {"Whiston", "ASTN", "ASTN"}, new String[] {"White", "AT", "AT"}, new String[] {"Whitman", "ATMN", "ATMN"}, new String[] {"Whiton", "ATN", "ATN"}, new String[] {"Whitson", "ATSN", "ATSN"}, new String[] {"Wickes", "AKS", "FKS"}, new String[] {"Wilbur", "ALPR", "FLPR"}, new String[] {"Wilcotes", "ALKT", "FLKT"}, new String[] {"Wilkinson", "ALKN", "FLKN"}, new String[] {"Willets", "ALTS", "FLTS"}, new String[] {"Willett", "ALT", "FLT"}, new String[] {"Willey", "AL", "FL"}, new String[] {"Williams", "ALMS", "FLMS"}, new String[] {"Williston", "ALST", "FLST"}, new String[] {"Wilson", "ALSN", "FLSN"}, new String[] {"Wimes", "AMS", "FMS"}, new String[] {"Winch", "ANX", "FNK"}, new String[] {"Winegar", "ANKR", "FNKR"}, new String[] {"Wing", "ANK", "FNK"}, new String[] {"Winsley", "ANSL", "FNSL"}, new String[] {"Winslow", "ANSL", "FNSL"}, new String[] {"Winthrop", "AN0R", "FNTR"}, new String[] {"Wise", "AS", "FS"}, new String[] {"Wood", "AT", "FT"}, new String[] {"Woodbridge", "ATPR", "FTPR"}, new String[] {"Woodward", "ATRT", "FTRT"}, new String[] {"Wooley", "AL", "FL"}, new String[] {"Woolley", "AL", "FL"}, new String[] {"Worth", "AR0", "FRT"}, new String[] {"Worthen", "AR0N", "FRTN"}, new String[] {"Worthley", "AR0L", "FRTL"}, new String[] {"Wright", "RT", "RT"}, new String[] {"Wyer", "AR", "FR"}, new String[] {"Wyere", "AR", "FR"}, new String[] {"Wynkoop", "ANKP", "FNKP"}, new String[] {"Yarnall", "ARNL", "ARNL"}, new String[] {"Yeoman", "AMN", "AMN"}, new String[] {"Yorke", "ARK", "ARK"}, new String[] {"Young", "ANK", "ANK"}, new String[] {"ab Wennonwen","APNN", "APNN"}, new String[] {"ap Llewellyn","APLL", "APLL"}, new String[] {"ap Lorwerth", "APLR", "APLR"}, new String[] {"d'Angouleme", "TNKL", "TNKL"}, new String[] {"de Audeham", "TTHM", "TTHM"}, new String[] {"de Bavant", "TPFN", "TPFN"}, new String[] {"de Beauchamp","TPXM", "TPKM"}, new String[] {"de Beaumont", "TPMN", "TPMN"}, new String[] {"de Bolbec", "TPLP", "TPLP"}, new String[] {"de Braiose", "TPRS", "TPRS"}, new String[] {"de Braose", "TPRS", "TPRS"}, new String[] {"de Briwere", "TPRR", "TPRR"}, new String[] {"de Cantelou", "TKNT", "TKNT"}, new String[] {"de Cherelton","TXRL", "TKRL"}, new String[] {"de Cherleton","TXRL", "TKRL"}, new String[] {"de Clare", "TKLR", "TKLR"}, new String[] {"de Claremont","TKLR", "TKLR"}, new String[] {"de Clifford", "TKLF", "TKLF"}, new String[] {"de Colville", "TKLF", "TKLF"}, new String[] {"de Courtenay","TKRT", "TKRT"}, new String[] {"de Fauconberg","TFKN", "TFKN"}, new String[] {"de Forest", "TFRS", "TFRS"}, new String[] {"de Gai", "TK", "TK"}, new String[] {"de Grey", "TKR", "TKR"}, new String[] {"de Guernons", "TKRN", "TKRN"}, new String[] {"de Haia", "T", "T"}, new String[] {"de Harcourt", "TRKR", "TRKR"}, new String[] {"de Hastings", "TSTN", "TSTN"}, new String[] {"de Hoke", "TK", "TK"}, new String[] {"de Hooch", "TK", "TK"}, new String[] {"de Hugelville","TJLF", "TKLF"}, new String[] {"de Huntingdon","TNTN", "TNTN"}, new String[] {"de Insula", "TNSL", "TNSL"}, new String[] {"de Keynes", "TKNS", "TKNS"}, new String[] {"de Lacy", "TLS", "TLS"}, new String[] {"de Lexington","TLKS", "TLKS"}, new String[] {"de Lusignan", "TLSN", "TLSK"}, new String[] {"de Manvers", "TMNF", "TMNF"}, new String[] {"de Montagu", "TMNT", "TMNT"}, new String[] {"de Montault", "TMNT", "TMNT"}, new String[] {"de Montfort", "TMNT", "TMNT"}, new String[] {"de Mortimer", "TMRT", "TMRT"}, new String[] {"de Morville", "TMRF", "TMRF"}, new String[] {"de Morvois", "TMRF", "TMRF"}, new String[] {"de Neufmarche","TNFM", "TNFM"}, new String[] {"de Odingsells","TTNK", "TTNK"}, new String[] {"de Odyngsells","TTNK", "TTNK"}, new String[] {"de Percy", "TPRS", "TPRS"}, new String[] {"de Pierrepont","TPRP", "TPRP"}, new String[] {"de Plessetis","TPLS", "TPLS"}, new String[] {"de Porhoet", "TPRT", "TPRT"}, new String[] {"de Prouz", "TPRS", "TPRS"}, new String[] {"de Quincy", "TKNS", "TKNS"}, new String[] {"de Ripellis", "TRPL", "TRPL"}, new String[] {"de Ros", "TRS", "TRS"}, new String[] {"de Salisbury","TSLS", "TSLS"}, new String[] {"de Sanford", "TSNF", "TSNF"}, new String[] {"de Somery", "TSMR", "TSMR"}, new String[] {"de St. Hilary","TSTL", "TSTL"}, new String[] {"de St. Liz", "TSTL", "TSTL"}, new String[] {"de Sutton", "TSTN", "TSTN"}, new String[] {"de Toeni", "TTN", "TTN"}, new String[] {"de Tony", "TTN", "TTN"}, new String[] {"de Umfreville","TMFR", "TMFR"}, new String[] {"de Valognes", "TFLN", "TFLK"}, new String[] {"de Vaux", "TF", "TF"}, new String[] {"de Vere", "TFR", "TFR"}, new String[] {"de Vermandois","TFRM", "TFRM"}, new String[] {"de Vernon", "TFRN", "TFRN"}, new String[] {"de Vexin", "TFKS", "TFKS"}, new String[] {"de Vitre", "TFTR", "TFTR"}, new String[] {"de Wandesford","TNTS", "TNTS"}, new String[] {"de Warenne", "TRN", "TRN"}, new String[] {"de Westbury", "TSTP", "TSTP"}, new String[] {"di Saluzzo", "TSLS", "TSLT"}, new String[] {"fitz Alan", "FTSL", "FTSL"}, new String[] {"fitz Geoffrey","FTSJ", "FTSK"}, new String[] {"fitz Herbert","FTSR", "FTSR"}, new String[] {"fitz John", "FTSJ", "FTSJ"}, new String[] {"fitz Patrick","FTSP", "FTSP"}, new String[] {"fitz Payn", "FTSP", "FTSP"}, new String[] {"fitz Piers", "FTSP", "FTSP"}, new String[] {"fitz Randolph","FTSR", "FTSR"}, new String[] {"fitz Richard","FTSR", "FTSR"}, new String[] {"fitz Robert", "FTSR", "FTSR"}, new String[] {"fitz Roy", "FTSR", "FTSR"}, new String[] {"fitz Scrob", "FTSS", "FTSS"}, new String[] {"fitz Walter", "FTSL", "FTSL"}, new String[] {"fitz Warin", "FTSR", "FTSR"}, new String[] {"fitz Williams","FTSL", "FTSL"}, new String[] {"la Zouche", "LSX", "LSK"}, new String[] {"le Botiller", "LPTL", "LPTL"}, new String[] {"le Despenser","LTSP", "LTSP"}, new String[] {"le deSpencer","LTSP", "LTSP"}, new String[] {"of Allendale","AFLN", "AFLN"}, new String[] {"of Angouleme","AFNK", "AFNK"}, new String[] {"of Anjou", "AFNJ", "AFNJ"}, new String[] {"of Aquitaine","AFKT", "AFKT"}, new String[] {"of Aumale", "AFML", "AFML"}, new String[] {"of Bavaria", "AFPF", "AFPF"}, new String[] {"of Boulogne", "AFPL", "AFPL"}, new String[] {"of Brittany", "AFPR", "AFPR"}, new String[] {"of Brittary", "AFPR", "AFPR"}, new String[] {"of Castile", "AFKS", "AFKS"}, new String[] {"of Chester", "AFXS", "AFKS"}, new String[] {"of Clermont", "AFKL", "AFKL"}, new String[] {"of Cologne", "AFKL", "AFKL"}, new String[] {"of Dinan", "AFTN", "AFTN"}, new String[] {"of Dunbar", "AFTN", "AFTN"}, new String[] {"of England", "AFNK", "AFNK"}, new String[] {"of Essex", "AFSK", "AFSK"}, new String[] {"of Falaise", "AFFL", "AFFL"}, new String[] {"of Flanders", "AFFL", "AFFL"}, new String[] {"of Galloway", "AFKL", "AFKL"}, new String[] {"of Germany", "AFKR", "AFJR"}, new String[] {"of Gloucester","AFKL", "AFKL"}, new String[] {"of Heristal", "AFRS", "AFRS"}, new String[] {"of Hungary", "AFNK", "AFNK"}, new String[] {"of Huntington","AFNT", "AFNT"}, new String[] {"of Kiev", "AFKF", "AFKF"}, new String[] {"of Kuno", "AFKN", "AFKN"}, new String[] {"of Landen", "AFLN", "AFLN"}, new String[] {"of Laon", "AFLN", "AFLN"}, new String[] {"of Leinster", "AFLN", "AFLN"}, new String[] {"of Lens", "AFLN", "AFLN"}, new String[] {"of Lorraine", "AFLR", "AFLR"}, new String[] {"of Louvain", "AFLF", "AFLF"}, new String[] {"of Mercia", "AFMR", "AFMR"}, new String[] {"of Metz", "AFMT", "AFMT"}, new String[] {"of Meulan", "AFML", "AFML"}, new String[] {"of Nass", "AFNS", "AFNS"}, new String[] {"of Normandy", "AFNR", "AFNR"}, new String[] {"of Ohningen", "AFNN", "AFNN"}, new String[] {"of Orleans", "AFRL", "AFRL"}, new String[] {"of Poitou", "AFPT", "AFPT"}, new String[] {"of Polotzk", "AFPL", "AFPL"}, new String[] {"of Provence", "AFPR", "AFPR"}, new String[] {"of Ringelheim","AFRN", "AFRN"}, new String[] {"of Salisbury","AFSL", "AFSL"}, new String[] {"of Saxony", "AFSK", "AFSK"}, new String[] {"of Scotland", "AFSK", "AFSK"}, new String[] {"of Senlis", "AFSN", "AFSN"}, new String[] {"of Stafford", "AFST", "AFST"}, new String[] {"of Swabia", "AFSP", "AFSP"}, new String[] {"of Tongres", "AFTN", "AFTN"}, new String[] {"of the Tributes","AF0T", "AFTT"}, new String[] {"unknown", "ANKN", "ANKN"}, new String[] {"van der Gouda","FNTR", "FNTR"}, new String[] {"von Adenbaugh","FNTN", "FNTN"}, new String[] {"ARCHITure", "ARKT", "ARKT"}, new String[] {"Arnoff", "ARNF", "ARNF"}, new String[] {"Arnow", "ARN", "ARNF"}, new String[] {"DANGER", "TNJR", "TNKR"}, new String[] {"Jankelowicz", "JNKL", "ANKL"}, new String[] {"MANGER", "MNJR", "MNKR"}, new String[] {"McClellan", "MKLL", "MKLL"}, new String[] {"McHugh", "MK", "MK"}, new String[] {"McLaughlin", "MKLF", "MKLF"}, new String[] {"ORCHEStra", "ARKS", "ARKS"}, new String[] {"ORCHID", "ARKT", "ARKT"}, new String[] {"Pierce", "PRS", "PRS"}, new String[] {"RANGER", "RNJR", "RNKR"}, new String[] {"Schlesinger", "XLSN", "SLSN"}, new String[] {"Uomo", "AM", "AM"}, new String[] {"Vasserman", "FSRM", "FSRM"}, new String[] {"Wasserman", "ASRM", "FSRM"}, new String[] {"Womo", "AM", "FM"}, new String[] {"Yankelovich", "ANKL", "ANKL"}, new String[] {"accede", "AKST", "AKST"}, new String[] {"accident", "AKST", "AKST"}, new String[] {"adelsheim", "ATLS", "ATLS"}, new String[] {"aged", "AJT", "AKT"}, new String[] {"ageless", "AJLS", "AKLS"}, new String[] {"agency", "AJNS", "AKNS"}, new String[] {"aghast", "AKST", "AKST"}, new String[] {"agio", "AJ", "AK"}, new String[] {"agrimony", "AKRM", "AKRM"}, new String[] {"album", "ALPM", "ALPM"}, new String[] {"alcmene", "ALKM", "ALKM"}, new String[] {"alehouse", "ALHS", "ALHS"}, new String[] {"antique", "ANTK", "ANTK"}, new String[] {"artois", "ART", "ARTS"}, new String[] {"automation", "ATMX", "ATMX"}, new String[] {"bacchus", "PKS", "PKS"}, new String[] {"bacci", "PX", "PX"}, new String[] {"bajador", "PJTR", "PHTR"}, new String[] {"bellocchio", "PLX", "PLX"}, new String[] {"bertucci", "PRTX", "PRTX"}, new String[] {"biaggi", "PJ", "PK"}, new String[] {"bough", "P", "P"}, new String[] {"breaux", "PR", "PR"}, new String[] {"broughton", "PRTN", "PRTN"}, new String[] {"cabrillo", "KPRL", "KPR"}, new String[] {"caesar", "SSR", "SSR"}, new String[] {"cagney", "KKN", "KKN"}, new String[] {"campbell", "KMPL", "KMPL"}, new String[] {"carlisle", "KRLL", "KRLL"}, new String[] {"carlysle", "KRLL", "KRLL"}, new String[] {"chemistry", "KMST", "KMST"}, new String[] {"chianti", "KNT", "KNT"}, new String[] {"chorus", "KRS", "KRS"}, new String[] {"cough", "KF", "KF"}, new String[] {"czerny", "SRN", "XRN"}, new String[] {"deffenbacher","TFNP", "TFNP"}, new String[] {"dumb", "TM", "TM"}, new String[] {"edgar", "ATKR", "ATKR"}, new String[] {"edge", "AJ", "AJ"}, new String[] {"filipowicz", "FLPT", "FLPF"}, new String[] {"focaccia", "FKX", "FKX"}, new String[] {"gallegos", "KLKS", "KKS"}, new String[] {"gambrelli", "KMPR", "KMPR"}, new String[] {"geithain", "K0N", "JTN"}, new String[] {"ghiradelli", "JRTL", "JRTL"}, new String[] {"ghislane", "JLN", "JLN"}, new String[] {"gough", "KF", "KF"}, new String[] {"hartheim", "HR0M", "HRTM"}, new String[] {"heimsheim", "HMSM", "HMSM"}, new String[] {"hochmeier", "HKMR", "HKMR"}, new String[] {"hugh", "H", "H"}, new String[] {"hunger", "HNKR", "HNJR"}, new String[] {"hungry", "HNKR", "HNKR"}, new String[] {"island", "ALNT", "ALNT"}, new String[] {"isle", "AL", "AL"}, new String[] {"jose", "HS", "HS"}, new String[] {"laugh", "LF", "LF"}, new String[] {"mac caffrey", "MKFR", "MKFR"}, new String[] {"mac gregor", "MKRK", "MKRK"}, new String[] {"pegnitz", "PNTS", "PKNT"}, new String[] {"piskowitz", "PSKT", "PSKF"}, new String[] {"queen", "KN", "KN"}, new String[] {"raspberry", "RSPR", "RSPR"}, new String[] {"resnais", "RSN", "RSNS"}, new String[] {"rogier", "RJ", "RJR"}, new String[] {"rough", "RF", "RF"}, new String[] {"san jacinto", "SNHS", "SNHS"}, new String[] {"schenker", "XNKR", "SKNK"}, new String[] {"schermerhorn","XRMR", "SKRM"}, new String[] {"schmidt", "XMT", "SMT"}, new String[] {"schneider", "XNTR", "SNTR"}, new String[] {"school", "SKL", "SKL"}, new String[] {"schooner", "SKNR", "SKNR"}, new String[] {"schrozberg", "XRSP", "SRSP"}, new String[] {"schulman", "XLMN", "XLMN"}, new String[] {"schwabach", "XPK", "XFPK"}, new String[] {"schwarzach", "XRSK", "XFRT"}, new String[] {"smith", "SM0", "XMT"}, new String[] {"snider", "SNTR", "XNTR"}, new String[] {"succeed", "SKST", "SKST"}, new String[] {"sugarcane", "XKRK", "SKRK"}, new String[] {"svobodka", "SFPT", "SFPT"}, new String[] {"tagliaro", "TKLR", "TLR"}, new String[] {"thames", "TMS", "TMS"}, new String[] {"theilheim", "0LM", "TLM"}, new String[] {"thomas", "TMS", "TMS"}, new String[] {"thumb", "0M", "TM"}, new String[] {"tichner", "TXNR", "TKNR"}, new String[] {"tough", "TF", "TF"}, new String[] {"umbrella", "AMPR", "AMPR"}, new String[] {"vilshofen", "FLXF", "FLXF"}, new String[] {"von schuller","FNXL", "FNXL"}, new String[] {"wachtler", "AKTL", "FKTL"}, new String[] {"wechsler", "AKSL", "FKSL"}, new String[] {"weikersheim", "AKRS", "FKRS"}, new String[] {"zhao", "J", "J"} }; }
// You are a professional Java test case writer, please create a test case named `testDoubleMetaphoneAlternate` for the issue `Codec-CODEC-84`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-84 // // ## Issue-Title: // Double Metaphone bugs in alternative encoding // // ## Issue-Description: // // The new test case ([~~CODEC-83~~](https://issues.apache.org/jira/browse/CODEC-83 "Improve Double Metaphone test coverage")) has highlighted a number of issues with the "alternative" encoding in the Double Metaphone implementation // // // 1) Bug in the handleG method when "G" is followed by "IER" // // // * The alternative encoding of "Angier" results in "ANKR" rather than "ANJR" // * The alternative encoding of "rogier" results in "RKR" rather than "RJR" // // // The problem is in the handleG() method and is caused by the wrong length (4 instead of 3) being used in the contains() method: // // // // // ``` // } else if (contains(value, index + 1, 4, "IER")) { // // ``` // // // ...this should be // // // // // ``` // } else if (contains(value, index + 1, 3, "IER")) { // // ``` // // // 2) Bug in the handleL method // // // * The alternative encoding of "cabrillo" results in "KPRL " rather than "KPR" // // // The problem is that the first thing this method does is append an "L" to both primary & alternative encoding. When the conditionL0() method returns true then the "L" should not be appended for the alternative encoding // // // // // ``` // result.append('L'); // if (charAt(value, index + 1) == 'L') { // if (conditionL0(value, index)) { // result.appendAlternate(' '); // } // index += 2; // } else { // index++; // } // return index; // // ``` // // // Suggest refeactoring this to // // // // // ``` // if (charAt(value, index + 1) == 'L') { // if (conditionL0(value, index)) { // result.appendPrimary('L'); // } else { // result.append('L'); // } // index += 2; // } else { // result.append('L'); // index++; // } // return index; // // ``` // // // 3) Bug in the conditionL0() method for words ending in "AS" and "OS" // // // * The alternative encoding of "gallegos" results in "KLKS" rather than "KKS" // // // The problem is caused by the wrong start position being used in the contains() method, which means its not checking the last two characters of the word but checks the previous & current position instead: // // // // // ``` // } else if ((contains(value, index - 1, 2, "AS", "OS") || // // ``` // // // ...this should be // // // // // ``` // } else if ((contains(value, value.length() - 2, 2, "AS", "OS") || // // ``` // // // I'll attach a patch for review // // // // // public void testDoubleMetaphoneAlternate() {
85
/** * Test alternative encoding. */
3
79
src/test/org/apache/commons/codec/language/DoubleMetaphone2Test.java
src/test
```markdown ## Issue-ID: Codec-CODEC-84 ## Issue-Title: Double Metaphone bugs in alternative encoding ## Issue-Description: The new test case ([~~CODEC-83~~](https://issues.apache.org/jira/browse/CODEC-83 "Improve Double Metaphone test coverage")) has highlighted a number of issues with the "alternative" encoding in the Double Metaphone implementation 1) Bug in the handleG method when "G" is followed by "IER" * The alternative encoding of "Angier" results in "ANKR" rather than "ANJR" * The alternative encoding of "rogier" results in "RKR" rather than "RJR" The problem is in the handleG() method and is caused by the wrong length (4 instead of 3) being used in the contains() method: ``` } else if (contains(value, index + 1, 4, "IER")) { ``` ...this should be ``` } else if (contains(value, index + 1, 3, "IER")) { ``` 2) Bug in the handleL method * The alternative encoding of "cabrillo" results in "KPRL " rather than "KPR" The problem is that the first thing this method does is append an "L" to both primary & alternative encoding. When the conditionL0() method returns true then the "L" should not be appended for the alternative encoding ``` result.append('L'); if (charAt(value, index + 1) == 'L') { if (conditionL0(value, index)) { result.appendAlternate(' '); } index += 2; } else { index++; } return index; ``` Suggest refeactoring this to ``` if (charAt(value, index + 1) == 'L') { if (conditionL0(value, index)) { result.appendPrimary('L'); } else { result.append('L'); } index += 2; } else { result.append('L'); index++; } return index; ``` 3) Bug in the conditionL0() method for words ending in "AS" and "OS" * The alternative encoding of "gallegos" results in "KLKS" rather than "KKS" The problem is caused by the wrong start position being used in the contains() method, which means its not checking the last two characters of the word but checks the previous & current position instead: ``` } else if ((contains(value, index - 1, 2, "AS", "OS") || ``` ...this should be ``` } else if ((contains(value, value.length() - 2, 2, "AS", "OS") || ``` I'll attach a patch for review ``` You are a professional Java test case writer, please create a test case named `testDoubleMetaphoneAlternate` for the issue `Codec-CODEC-84`, utilizing the provided issue report information and the following function signature. ```java public void testDoubleMetaphoneAlternate() { ```
79
[ "org.apache.commons.codec.language.DoubleMetaphone" ]
ea110531fb67fb2b886a3c9e29ea440aaeee5b7c6af5604db4b8527274cbbf94
public void testDoubleMetaphoneAlternate()
// You are a professional Java test case writer, please create a test case named `testDoubleMetaphoneAlternate` for the issue `Codec-CODEC-84`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-84 // // ## Issue-Title: // Double Metaphone bugs in alternative encoding // // ## Issue-Description: // // The new test case ([~~CODEC-83~~](https://issues.apache.org/jira/browse/CODEC-83 "Improve Double Metaphone test coverage")) has highlighted a number of issues with the "alternative" encoding in the Double Metaphone implementation // // // 1) Bug in the handleG method when "G" is followed by "IER" // // // * The alternative encoding of "Angier" results in "ANKR" rather than "ANJR" // * The alternative encoding of "rogier" results in "RKR" rather than "RJR" // // // The problem is in the handleG() method and is caused by the wrong length (4 instead of 3) being used in the contains() method: // // // // // ``` // } else if (contains(value, index + 1, 4, "IER")) { // // ``` // // // ...this should be // // // // // ``` // } else if (contains(value, index + 1, 3, "IER")) { // // ``` // // // 2) Bug in the handleL method // // // * The alternative encoding of "cabrillo" results in "KPRL " rather than "KPR" // // // The problem is that the first thing this method does is append an "L" to both primary & alternative encoding. When the conditionL0() method returns true then the "L" should not be appended for the alternative encoding // // // // // ``` // result.append('L'); // if (charAt(value, index + 1) == 'L') { // if (conditionL0(value, index)) { // result.appendAlternate(' '); // } // index += 2; // } else { // index++; // } // return index; // // ``` // // // Suggest refeactoring this to // // // // // ``` // if (charAt(value, index + 1) == 'L') { // if (conditionL0(value, index)) { // result.appendPrimary('L'); // } else { // result.append('L'); // } // index += 2; // } else { // result.append('L'); // index++; // } // return index; // // ``` // // // 3) Bug in the conditionL0() method for words ending in "AS" and "OS" // // // * The alternative encoding of "gallegos" results in "KLKS" rather than "KKS" // // // The problem is caused by the wrong start position being used in the contains() method, which means its not checking the last two characters of the word but checks the previous & current position instead: // // // // // ``` // } else if ((contains(value, index - 1, 2, "AS", "OS") || // // ``` // // // ...this should be // // // // // ``` // } else if ((contains(value, value.length() - 2, 2, "AS", "OS") || // // ``` // // // I'll attach a patch for review // // // // //
Codec
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.language; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests {@link DoubleMetaphone}. * <p> * The test data was extracted from Stephen Woodbridge's * <a href="http://swoodbridge.com/DoubleMetaPhone/surnames.txt">php test program</a>. * * @see http://swoodbridge.com/DoubleMetaPhone/surnames.txt * @version $Id$ */ public class DoubleMetaphone2Test extends TestCase { public static Test suite() { return new TestSuite(DoubleMetaphone2Test.class); } private DoubleMetaphone doubleMetaphone = null; /** * Construct a new test case. * * @param name The name of the test */ public DoubleMetaphone2Test(String name) { super(name); } /** * Set up. */ public void setUp() throws Exception { super.setUp(); this.doubleMetaphone = new DoubleMetaphone(); } /** * Tear Down. */ public void tearDown() throws Exception { super.tearDown(); this.doubleMetaphone = null; } /** * Test primary encoding. */ public void testDoubleMetaphonePrimary() { String value = null; for (int i = 0; i < TEST_DATA.length; i++) { value = TEST_DATA[i][0]; assertEquals("Test [" + i + "]=" + value, TEST_DATA[i][1], doubleMetaphone.doubleMetaphone(value, false)); } } /** * Test alternative encoding. */ public void testDoubleMetaphoneAlternate() { String value = null; for (int i = 0; i < TEST_DATA.length; i++) { value = TEST_DATA[i][0]; assertEquals("Test [" + i + "]=" + value, TEST_DATA[i][2], doubleMetaphone.doubleMetaphone(value, true)); } } /** Test values and their expected primary & alternate Double Metaphone encodings */ private static final String[][] TEST_DATA = new String[][] { new String[] {"ALLERTON", "ALRT", "ALRT"}, new String[] {"Acton", "AKTN", "AKTN"}, new String[] {"Adams", "ATMS", "ATMS"}, new String[] {"Aggar", "AKR", "AKR"}, new String[] {"Ahl", "AL", "AL"}, new String[] {"Aiken", "AKN", "AKN"}, new String[] {"Alan", "ALN", "ALN"}, new String[] {"Alcock", "ALKK", "ALKK"}, new String[] {"Alden", "ALTN", "ALTN"}, new String[] {"Aldham", "ALTM", "ALTM"}, new String[] {"Allen", "ALN", "ALN"}, new String[] {"Allerton", "ALRT", "ALRT"}, new String[] {"Alsop", "ALSP", "ALSP"}, new String[] {"Alwein", "ALN", "ALN"}, new String[] {"Ambler", "AMPL", "AMPL"}, new String[] {"Andevill", "ANTF", "ANTF"}, new String[] {"Andrews", "ANTR", "ANTR"}, new String[] {"Andreyco", "ANTR", "ANTR"}, new String[] {"Andriesse", "ANTR", "ANTR"}, new String[] {"Angier", "ANJ", "ANJR"}, new String[] {"Annabel", "ANPL", "ANPL"}, new String[] {"Anne", "AN", "AN"}, new String[] {"Anstye", "ANST", "ANST"}, new String[] {"Appling", "APLN", "APLN"}, new String[] {"Apuke", "APK", "APK"}, new String[] {"Arnold", "ARNL", "ARNL"}, new String[] {"Ashby", "AXP", "AXP"}, new String[] {"Astwood", "ASTT", "ASTT"}, new String[] {"Atkinson", "ATKN", "ATKN"}, new String[] {"Audley", "ATL", "ATL"}, new String[] {"Austin", "ASTN", "ASTN"}, new String[] {"Avenal", "AFNL", "AFNL"}, new String[] {"Ayer", "AR", "AR"}, new String[] {"Ayot", "AT", "AT"}, new String[] {"Babbitt", "PPT", "PPT"}, new String[] {"Bachelor", "PXLR", "PKLR"}, new String[] {"Bachelour", "PXLR", "PKLR"}, new String[] {"Bailey", "PL", "PL"}, new String[] {"Baivel", "PFL", "PFL"}, new String[] {"Baker", "PKR", "PKR"}, new String[] {"Baldwin", "PLTN", "PLTN"}, new String[] {"Balsley", "PLSL", "PLSL"}, new String[] {"Barber", "PRPR", "PRPR"}, new String[] {"Barker", "PRKR", "PRKR"}, new String[] {"Barlow", "PRL", "PRLF"}, new String[] {"Barnard", "PRNR", "PRNR"}, new String[] {"Barnes", "PRNS", "PRNS"}, new String[] {"Barnsley", "PRNS", "PRNS"}, new String[] {"Barouxis", "PRKS", "PRKS"}, new String[] {"Bartlet", "PRTL", "PRTL"}, new String[] {"Basley", "PSL", "PSL"}, new String[] {"Basset", "PST", "PST"}, new String[] {"Bassett", "PST", "PST"}, new String[] {"Batchlor", "PXLR", "PXLR"}, new String[] {"Bates", "PTS", "PTS"}, new String[] {"Batson", "PTSN", "PTSN"}, new String[] {"Bayes", "PS", "PS"}, new String[] {"Bayley", "PL", "PL"}, new String[] {"Beale", "PL", "PL"}, new String[] {"Beauchamp", "PXMP", "PKMP"}, new String[] {"Beauclerc", "PKLR", "PKLR"}, new String[] {"Beech", "PK", "PK"}, new String[] {"Beers", "PRS", "PRS"}, new String[] {"Beke", "PK", "PK"}, new String[] {"Belcher", "PLXR", "PLKR"}, new String[] {"Benjamin", "PNJM", "PNJM"}, new String[] {"Benningham", "PNNK", "PNNK"}, new String[] {"Bereford", "PRFR", "PRFR"}, new String[] {"Bergen", "PRJN", "PRKN"}, new String[] {"Berkeley", "PRKL", "PRKL"}, new String[] {"Berry", "PR", "PR"}, new String[] {"Besse", "PS", "PS"}, new String[] {"Bessey", "PS", "PS"}, new String[] {"Bessiles", "PSLS", "PSLS"}, new String[] {"Bigelow", "PJL", "PKLF"}, new String[] {"Bigg", "PK", "PK"}, new String[] {"Bigod", "PKT", "PKT"}, new String[] {"Billings", "PLNK", "PLNK"}, new String[] {"Bimper", "PMPR", "PMPR"}, new String[] {"Binker", "PNKR", "PNKR"}, new String[] {"Birdsill", "PRTS", "PRTS"}, new String[] {"Bishop", "PXP", "PXP"}, new String[] {"Black", "PLK", "PLK"}, new String[] {"Blagge", "PLK", "PLK"}, new String[] {"Blake", "PLK", "PLK"}, new String[] {"Blanck", "PLNK", "PLNK"}, new String[] {"Bledsoe", "PLTS", "PLTS"}, new String[] {"Blennerhasset","PLNR", "PLNR"}, new String[] {"Blessing", "PLSN", "PLSN"}, new String[] {"Blewett", "PLT", "PLT"}, new String[] {"Bloctgoed", "PLKT", "PLKT"}, new String[] {"Bloetgoet", "PLTK", "PLTK"}, new String[] {"Bloodgood", "PLTK", "PLTK"}, new String[] {"Blossom", "PLSM", "PLSM"}, new String[] {"Blount", "PLNT", "PLNT"}, new String[] {"Bodine", "PTN", "PTN"}, new String[] {"Bodman", "PTMN", "PTMN"}, new String[] {"BonCoeur", "PNKR", "PNKR"}, new String[] {"Bond", "PNT", "PNT"}, new String[] {"Boscawen", "PSKN", "PSKN"}, new String[] {"Bosworth", "PSR0", "PSRT"}, new String[] {"Bouchier", "PX", "PKR"}, new String[] {"Bowne", "PN", "PN"}, new String[] {"Bradbury", "PRTP", "PRTP"}, new String[] {"Bradder", "PRTR", "PRTR"}, new String[] {"Bradford", "PRTF", "PRTF"}, new String[] {"Bradstreet", "PRTS", "PRTS"}, new String[] {"Braham", "PRHM", "PRHM"}, new String[] {"Brailsford", "PRLS", "PRLS"}, new String[] {"Brainard", "PRNR", "PRNR"}, new String[] {"Brandish", "PRNT", "PRNT"}, new String[] {"Braun", "PRN", "PRN"}, new String[] {"Brecc", "PRK", "PRK"}, new String[] {"Brent", "PRNT", "PRNT"}, new String[] {"Brenton", "PRNT", "PRNT"}, new String[] {"Briggs", "PRKS", "PRKS"}, new String[] {"Brigham", "PRM", "PRM"}, new String[] {"Brobst", "PRPS", "PRPS"}, new String[] {"Brome", "PRM", "PRM"}, new String[] {"Bronson", "PRNS", "PRNS"}, new String[] {"Brooks", "PRKS", "PRKS"}, new String[] {"Brouillard", "PRLR", "PRLR"}, new String[] {"Brown", "PRN", "PRN"}, new String[] {"Browne", "PRN", "PRN"}, new String[] {"Brownell", "PRNL", "PRNL"}, new String[] {"Bruley", "PRL", "PRL"}, new String[] {"Bryant", "PRNT", "PRNT"}, new String[] {"Brzozowski", "PRSS", "PRTS"}, new String[] {"Buide", "PT", "PT"}, new String[] {"Bulmer", "PLMR", "PLMR"}, new String[] {"Bunker", "PNKR", "PNKR"}, new String[] {"Burden", "PRTN", "PRTN"}, new String[] {"Burge", "PRJ", "PRK"}, new String[] {"Burgoyne", "PRKN", "PRKN"}, new String[] {"Burke", "PRK", "PRK"}, new String[] {"Burnett", "PRNT", "PRNT"}, new String[] {"Burpee", "PRP", "PRP"}, new String[] {"Bursley", "PRSL", "PRSL"}, new String[] {"Burton", "PRTN", "PRTN"}, new String[] {"Bushnell", "PXNL", "PXNL"}, new String[] {"Buss", "PS", "PS"}, new String[] {"Buswell", "PSL", "PSL"}, new String[] {"Butler", "PTLR", "PTLR"}, new String[] {"Calkin", "KLKN", "KLKN"}, new String[] {"Canada", "KNT", "KNT"}, new String[] {"Canmore", "KNMR", "KNMR"}, new String[] {"Canney", "KN", "KN"}, new String[] {"Capet", "KPT", "KPT"}, new String[] {"Card", "KRT", "KRT"}, new String[] {"Carman", "KRMN", "KRMN"}, new String[] {"Carpenter", "KRPN", "KRPN"}, new String[] {"Cartwright", "KRTR", "KRTR"}, new String[] {"Casey", "KS", "KS"}, new String[] {"Catterfield", "KTRF", "KTRF"}, new String[] {"Ceeley", "SL", "SL"}, new String[] {"Chambers", "XMPR", "XMPR"}, new String[] {"Champion", "XMPN", "XMPN"}, new String[] {"Chapman", "XPMN", "XPMN"}, new String[] {"Chase", "XS", "XS"}, new String[] {"Cheney", "XN", "XN"}, new String[] {"Chetwynd", "XTNT", "XTNT"}, new String[] {"Chevalier", "XFL", "XFLR"}, new String[] {"Chillingsworth","XLNK", "XLNK"}, new String[] {"Christie", "KRST", "KRST"}, new String[] {"Chubbuck", "XPK", "XPK"}, new String[] {"Church", "XRX", "XRK"}, new String[] {"Clark", "KLRK", "KLRK"}, new String[] {"Clarke", "KLRK", "KLRK"}, new String[] {"Cleare", "KLR", "KLR"}, new String[] {"Clement", "KLMN", "KLMN"}, new String[] {"Clerke", "KLRK", "KLRK"}, new String[] {"Clibben", "KLPN", "KLPN"}, new String[] {"Clifford", "KLFR", "KLFR"}, new String[] {"Clivedon", "KLFT", "KLFT"}, new String[] {"Close", "KLS", "KLS"}, new String[] {"Clothilde", "KL0L", "KLTL"}, new String[] {"Cobb", "KP", "KP"}, new String[] {"Coburn", "KPRN", "KPRN"}, new String[] {"Coburne", "KPRN", "KPRN"}, new String[] {"Cocke", "KK", "KK"}, new String[] {"Coffin", "KFN", "KFN"}, new String[] {"Coffyn", "KFN", "KFN"}, new String[] {"Colborne", "KLPR", "KLPR"}, new String[] {"Colby", "KLP", "KLP"}, new String[] {"Cole", "KL", "KL"}, new String[] {"Coleman", "KLMN", "KLMN"}, new String[] {"Collier", "KL", "KLR"}, new String[] {"Compton", "KMPT", "KMPT"}, new String[] {"Cone", "KN", "KN"}, new String[] {"Cook", "KK", "KK"}, new String[] {"Cooke", "KK", "KK"}, new String[] {"Cooper", "KPR", "KPR"}, new String[] {"Copperthwaite","KPR0", "KPRT"}, new String[] {"Corbet", "KRPT", "KRPT"}, new String[] {"Corell", "KRL", "KRL"}, new String[] {"Corey", "KR", "KR"}, new String[] {"Corlies", "KRLS", "KRLS"}, new String[] {"Corneliszen", "KRNL", "KRNL"}, new String[] {"Cornelius", "KRNL", "KRNL"}, new String[] {"Cornwallis", "KRNL", "KRNL"}, new String[] {"Cosgrove", "KSKR", "KSKR"}, new String[] {"Count of Brionne","KNTF", "KNTF"}, new String[] {"Covill", "KFL", "KFL"}, new String[] {"Cowperthwaite","KPR0", "KPRT"}, new String[] {"Cowperwaite", "KPRT", "KPRT"}, new String[] {"Crane", "KRN", "KRN"}, new String[] {"Creagmile", "KRKM", "KRKM"}, new String[] {"Crew", "KR", "KRF"}, new String[] {"Crispin", "KRSP", "KRSP"}, new String[] {"Crocker", "KRKR", "KRKR"}, new String[] {"Crockett", "KRKT", "KRKT"}, new String[] {"Crosby", "KRSP", "KRSP"}, new String[] {"Crump", "KRMP", "KRMP"}, new String[] {"Cunningham", "KNNK", "KNNK"}, new String[] {"Curtis", "KRTS", "KRTS"}, new String[] {"Cutha", "K0", "KT"}, new String[] {"Cutter", "KTR", "KTR"}, new String[] {"D'Aubigny", "TPN", "TPKN"}, new String[] {"DAVIS", "TFS", "TFS"}, new String[] {"Dabinott", "TPNT", "TPNT"}, new String[] {"Dacre", "TKR", "TKR"}, new String[] {"Daggett", "TKT", "TKT"}, new String[] {"Danvers", "TNFR", "TNFR"}, new String[] {"Darcy", "TRS", "TRS"}, new String[] {"Davis", "TFS", "TFS"}, new String[] {"Dawn", "TN", "TN"}, new String[] {"Dawson", "TSN", "TSN"}, new String[] {"Day", "T", "T"}, new String[] {"Daye", "T", "T"}, new String[] {"DeGrenier", "TKRN", "TKRN"}, new String[] {"Dean", "TN", "TN"}, new String[] {"Deekindaugh", "TKNT", "TKNT"}, new String[] {"Dennis", "TNS", "TNS"}, new String[] {"Denny", "TN", "TN"}, new String[] {"Denton", "TNTN", "TNTN"}, new String[] {"Desborough", "TSPR", "TSPR"}, new String[] {"Despenser", "TSPN", "TSPN"}, new String[] {"Deverill", "TFRL", "TFRL"}, new String[] {"Devine", "TFN", "TFN"}, new String[] {"Dexter", "TKST", "TKST"}, new String[] {"Dillaway", "TL", "TL"}, new String[] {"Dimmick", "TMK", "TMK"}, new String[] {"Dinan", "TNN", "TNN"}, new String[] {"Dix", "TKS", "TKS"}, new String[] {"Doggett", "TKT", "TKT"}, new String[] {"Donahue", "TNH", "TNH"}, new String[] {"Dorfman", "TRFM", "TRFM"}, new String[] {"Dorris", "TRS", "TRS"}, new String[] {"Dow", "T", "TF"}, new String[] {"Downey", "TN", "TN"}, new String[] {"Downing", "TNNK", "TNNK"}, new String[] {"Dowsett", "TST", "TST"}, new String[] {"Duck?", "TK", "TK"}, new String[] {"Dudley", "TTL", "TTL"}, new String[] {"Duffy", "TF", "TF"}, new String[] {"Dunn", "TN", "TN"}, new String[] {"Dunsterville","TNST", "TNST"}, new String[] {"Durrant", "TRNT", "TRNT"}, new String[] {"Durrin", "TRN", "TRN"}, new String[] {"Dustin", "TSTN", "TSTN"}, new String[] {"Duston", "TSTN", "TSTN"}, new String[] {"Eames", "AMS", "AMS"}, new String[] {"Early", "ARL", "ARL"}, new String[] {"Easty", "AST", "AST"}, new String[] {"Ebbett", "APT", "APT"}, new String[] {"Eberbach", "APRP", "APRP"}, new String[] {"Eberhard", "APRR", "APRR"}, new String[] {"Eddy", "AT", "AT"}, new String[] {"Edenden", "ATNT", "ATNT"}, new String[] {"Edwards", "ATRT", "ATRT"}, new String[] {"Eglinton", "AKLN", "ALNT"}, new String[] {"Eliot", "ALT", "ALT"}, new String[] {"Elizabeth", "ALSP", "ALSP"}, new String[] {"Ellis", "ALS", "ALS"}, new String[] {"Ellison", "ALSN", "ALSN"}, new String[] {"Ellot", "ALT", "ALT"}, new String[] {"Elny", "ALN", "ALN"}, new String[] {"Elsner", "ALSN", "ALSN"}, new String[] {"Emerson", "AMRS", "AMRS"}, new String[] {"Empson", "AMPS", "AMPS"}, new String[] {"Est", "AST", "AST"}, new String[] {"Estabrook", "ASTP", "ASTP"}, new String[] {"Estes", "ASTS", "ASTS"}, new String[] {"Estey", "AST", "AST"}, new String[] {"Evans", "AFNS", "AFNS"}, new String[] {"Fallowell", "FLL", "FLL"}, new String[] {"Farnsworth", "FRNS", "FRNS"}, new String[] {"Feake", "FK", "FK"}, new String[] {"Feke", "FK", "FK"}, new String[] {"Fellows", "FLS", "FLS"}, new String[] {"Fettiplace", "FTPL", "FTPL"}, new String[] {"Finney", "FN", "FN"}, new String[] {"Fischer", "FXR", "FSKR"}, new String[] {"Fisher", "FXR", "FXR"}, new String[] {"Fisk", "FSK", "FSK"}, new String[] {"Fiske", "FSK", "FSK"}, new String[] {"Fletcher", "FLXR", "FLXR"}, new String[] {"Folger", "FLKR", "FLJR"}, new String[] {"Foliot", "FLT", "FLT"}, new String[] {"Folyot", "FLT", "FLT"}, new String[] {"Fones", "FNS", "FNS"}, new String[] {"Fordham", "FRTM", "FRTM"}, new String[] {"Forstner", "FRST", "FRST"}, new String[] {"Fosten", "FSTN", "FSTN"}, new String[] {"Foster", "FSTR", "FSTR"}, new String[] {"Foulke", "FLK", "FLK"}, new String[] {"Fowler", "FLR", "FLR"}, new String[] {"Foxwell", "FKSL", "FKSL"}, new String[] {"Fraley", "FRL", "FRL"}, new String[] {"Franceys", "FRNS", "FRNS"}, new String[] {"Franke", "FRNK", "FRNK"}, new String[] {"Frascella", "FRSL", "FRSL"}, new String[] {"Frazer", "FRSR", "FRSR"}, new String[] {"Fredd", "FRT", "FRT"}, new String[] {"Freeman", "FRMN", "FRMN"}, new String[] {"French", "FRNX", "FRNK"}, new String[] {"Freville", "FRFL", "FRFL"}, new String[] {"Frey", "FR", "FR"}, new String[] {"Frick", "FRK", "FRK"}, new String[] {"Frier", "FR", "FRR"}, new String[] {"Froe", "FR", "FR"}, new String[] {"Frorer", "FRRR", "FRRR"}, new String[] {"Frost", "FRST", "FRST"}, new String[] {"Frothingham", "FR0N", "FRTN"}, new String[] {"Fry", "FR", "FR"}, new String[] {"Gaffney", "KFN", "KFN"}, new String[] {"Gage", "KJ", "KK"}, new String[] {"Gallion", "KLN", "KLN"}, new String[] {"Gallishan", "KLXN", "KLXN"}, new String[] {"Gamble", "KMPL", "KMPL"}, new String[] {"Garbrand", "KRPR", "KRPR"}, new String[] {"Gardner", "KRTN", "KRTN"}, new String[] {"Garrett", "KRT", "KRT"}, new String[] {"Gassner", "KSNR", "KSNR"}, new String[] {"Gater", "KTR", "KTR"}, new String[] {"Gaunt", "KNT", "KNT"}, new String[] {"Gayer", "KR", "KR"}, new String[] {"Gerken", "KRKN", "JRKN"}, new String[] {"Gerritsen", "KRTS", "JRTS"}, new String[] {"Gibbs", "KPS", "JPS"}, new String[] {"Giffard", "JFRT", "KFRT"}, new String[] {"Gilbert", "KLPR", "JLPR"}, new String[] {"Gill", "KL", "JL"}, new String[] {"Gilman", "KLMN", "JLMN"}, new String[] {"Glass", "KLS", "KLS"}, new String[] {"Goddard\\Gifford","KTRT", "KTRT"}, new String[] {"Godfrey", "KTFR", "KTFR"}, new String[] {"Godwin", "KTN", "KTN"}, new String[] {"Goodale", "KTL", "KTL"}, new String[] {"Goodnow", "KTN", "KTNF"}, new String[] {"Gorham", "KRM", "KRM"}, new String[] {"Goseline", "KSLN", "KSLN"}, new String[] {"Gott", "KT", "KT"}, new String[] {"Gould", "KLT", "KLT"}, new String[] {"Grafton", "KRFT", "KRFT"}, new String[] {"Grant", "KRNT", "KRNT"}, new String[] {"Gray", "KR", "KR"}, new String[] {"Green", "KRN", "KRN"}, new String[] {"Griffin", "KRFN", "KRFN"}, new String[] {"Grill", "KRL", "KRL"}, new String[] {"Grim", "KRM", "KRM"}, new String[] {"Grisgonelle", "KRSK", "KRSK"}, new String[] {"Gross", "KRS", "KRS"}, new String[] {"Guba", "KP", "KP"}, new String[] {"Gybbes", "KPS", "JPS"}, new String[] {"Haburne", "HPRN", "HPRN"}, new String[] {"Hackburne", "HKPR", "HKPR"}, new String[] {"Haddon?", "HTN", "HTN"}, new String[] {"Haines", "HNS", "HNS"}, new String[] {"Hale", "HL", "HL"}, new String[] {"Hall", "HL", "HL"}, new String[] {"Hallet", "HLT", "HLT"}, new String[] {"Hallock", "HLK", "HLK"}, new String[] {"Halstead", "HLST", "HLST"}, new String[] {"Hammond", "HMNT", "HMNT"}, new String[] {"Hance", "HNS", "HNS"}, new String[] {"Handy", "HNT", "HNT"}, new String[] {"Hanson", "HNSN", "HNSN"}, new String[] {"Harasek", "HRSK", "HRSK"}, new String[] {"Harcourt", "HRKR", "HRKR"}, new String[] {"Hardy", "HRT", "HRT"}, new String[] {"Harlock", "HRLK", "HRLK"}, new String[] {"Harris", "HRS", "HRS"}, new String[] {"Hartley", "HRTL", "HRTL"}, new String[] {"Harvey", "HRF", "HRF"}, new String[] {"Harvie", "HRF", "HRF"}, new String[] {"Harwood", "HRT", "HRT"}, new String[] {"Hathaway", "H0", "HT"}, new String[] {"Haukeness", "HKNS", "HKNS"}, new String[] {"Hawkes", "HKS", "HKS"}, new String[] {"Hawkhurst", "HKRS", "HKRS"}, new String[] {"Hawkins", "HKNS", "HKNS"}, new String[] {"Hawley", "HL", "HL"}, new String[] {"Heald", "HLT", "HLT"}, new String[] {"Helsdon", "HLST", "HLST"}, new String[] {"Hemenway", "HMN", "HMN"}, new String[] {"Hemmenway", "HMN", "HMN"}, new String[] {"Henck", "HNK", "HNK"}, new String[] {"Henderson", "HNTR", "HNTR"}, new String[] {"Hendricks", "HNTR", "HNTR"}, new String[] {"Hersey", "HRS", "HRS"}, new String[] {"Hewes", "HS", "HS"}, new String[] {"Heyman", "HMN", "HMN"}, new String[] {"Hicks", "HKS", "HKS"}, new String[] {"Hidden", "HTN", "HTN"}, new String[] {"Higgs", "HKS", "HKS"}, new String[] {"Hill", "HL", "HL"}, new String[] {"Hills", "HLS", "HLS"}, new String[] {"Hinckley", "HNKL", "HNKL"}, new String[] {"Hipwell", "HPL", "HPL"}, new String[] {"Hobart", "HPRT", "HPRT"}, new String[] {"Hoben", "HPN", "HPN"}, new String[] {"Hoffmann", "HFMN", "HFMN"}, new String[] {"Hogan", "HKN", "HKN"}, new String[] {"Holmes", "HLMS", "HLMS"}, new String[] {"Hoo", "H", "H"}, new String[] {"Hooker", "HKR", "HKR"}, new String[] {"Hopcott", "HPKT", "HPKT"}, new String[] {"Hopkins", "HPKN", "HPKN"}, new String[] {"Hopkinson", "HPKN", "HPKN"}, new String[] {"Hornsey", "HRNS", "HRNS"}, new String[] {"Houckgeest", "HKJS", "HKKS"}, new String[] {"Hough", "H", "H"}, new String[] {"Houstin", "HSTN", "HSTN"}, new String[] {"How", "H", "HF"}, new String[] {"Howe", "H", "H"}, new String[] {"Howland", "HLNT", "HLNT"}, new String[] {"Hubner", "HPNR", "HPNR"}, new String[] {"Hudnut", "HTNT", "HTNT"}, new String[] {"Hughes", "HS", "HS"}, new String[] {"Hull", "HL", "HL"}, new String[] {"Hulme", "HLM", "HLM"}, new String[] {"Hume", "HM", "HM"}, new String[] {"Hundertumark","HNTR", "HNTR"}, new String[] {"Hundley", "HNTL", "HNTL"}, new String[] {"Hungerford", "HNKR", "HNJR"}, new String[] {"Hunt", "HNT", "HNT"}, new String[] {"Hurst", "HRST", "HRST"}, new String[] {"Husbands", "HSPN", "HSPN"}, new String[] {"Hussey", "HS", "HS"}, new String[] {"Husted", "HSTT", "HSTT"}, new String[] {"Hutchins", "HXNS", "HXNS"}, new String[] {"Hutchinson", "HXNS", "HXNS"}, new String[] {"Huttinger", "HTNK", "HTNJ"}, new String[] {"Huybertsen", "HPRT", "HPRT"}, new String[] {"Iddenden", "ATNT", "ATNT"}, new String[] {"Ingraham", "ANKR", "ANKR"}, new String[] {"Ives", "AFS", "AFS"}, new String[] {"Jackson", "JKSN", "AKSN"}, new String[] {"Jacob", "JKP", "AKP"}, new String[] {"Jans", "JNS", "ANS"}, new String[] {"Jenkins", "JNKN", "ANKN"}, new String[] {"Jewett", "JT", "AT"}, new String[] {"Jewitt", "JT", "AT"}, new String[] {"Johnson", "JNSN", "ANSN"}, new String[] {"Jones", "JNS", "ANS"}, new String[] {"Josephine", "JSFN", "HSFN"}, new String[] {"Judd", "JT", "AT"}, new String[] {"June", "JN", "AN"}, new String[] {"Kamarowska", "KMRS", "KMRS"}, new String[] {"Kay", "K", "K"}, new String[] {"Kelley", "KL", "KL"}, new String[] {"Kelly", "KL", "KL"}, new String[] {"Keymber", "KMPR", "KMPR"}, new String[] {"Keynes", "KNS", "KNS"}, new String[] {"Kilham", "KLM", "KLM"}, new String[] {"Kim", "KM", "KM"}, new String[] {"Kimball", "KMPL", "KMPL"}, new String[] {"King", "KNK", "KNK"}, new String[] {"Kinsey", "KNS", "KNS"}, new String[] {"Kirk", "KRK", "KRK"}, new String[] {"Kirton", "KRTN", "KRTN"}, new String[] {"Kistler", "KSTL", "KSTL"}, new String[] {"Kitchen", "KXN", "KXN"}, new String[] {"Kitson", "KTSN", "KTSN"}, new String[] {"Klett", "KLT", "KLT"}, new String[] {"Kline", "KLN", "KLN"}, new String[] {"Knapp", "NP", "NP"}, new String[] {"Knight", "NT", "NT"}, new String[] {"Knote", "NT", "NT"}, new String[] {"Knott", "NT", "NT"}, new String[] {"Knox", "NKS", "NKS"}, new String[] {"Koeller", "KLR", "KLR"}, new String[] {"La Pointe", "LPNT", "LPNT"}, new String[] {"LaPlante", "LPLN", "LPLN"}, new String[] {"Laimbeer", "LMPR", "LMPR"}, new String[] {"Lamb", "LMP", "LMP"}, new String[] {"Lambertson", "LMPR", "LMPR"}, new String[] {"Lancto", "LNKT", "LNKT"}, new String[] {"Landry", "LNTR", "LNTR"}, new String[] {"Lane", "LN", "LN"}, new String[] {"Langendyck", "LNJN", "LNKN"}, new String[] {"Langer", "LNKR", "LNJR"}, new String[] {"Langford", "LNKF", "LNKF"}, new String[] {"Lantersee", "LNTR", "LNTR"}, new String[] {"Laquer", "LKR", "LKR"}, new String[] {"Larkin", "LRKN", "LRKN"}, new String[] {"Latham", "LTM", "LTM"}, new String[] {"Lathrop", "L0RP", "LTRP"}, new String[] {"Lauter", "LTR", "LTR"}, new String[] {"Lawrence", "LRNS", "LRNS"}, new String[] {"Leach", "LK", "LK"}, new String[] {"Leager", "LKR", "LJR"}, new String[] {"Learned", "LRNT", "LRNT"}, new String[] {"Leavitt", "LFT", "LFT"}, new String[] {"Lee", "L", "L"}, new String[] {"Leete", "LT", "LT"}, new String[] {"Leggett", "LKT", "LKT"}, new String[] {"Leland", "LLNT", "LLNT"}, new String[] {"Leonard", "LNRT", "LNRT"}, new String[] {"Lester", "LSTR", "LSTR"}, new String[] {"Lestrange", "LSTR", "LSTR"}, new String[] {"Lethem", "L0M", "LTM"}, new String[] {"Levine", "LFN", "LFN"}, new String[] {"Lewes", "LS", "LS"}, new String[] {"Lewis", "LS", "LS"}, new String[] {"Lincoln", "LNKL", "LNKL"}, new String[] {"Lindsey", "LNTS", "LNTS"}, new String[] {"Linher", "LNR", "LNR"}, new String[] {"Lippet", "LPT", "LPT"}, new String[] {"Lippincott", "LPNK", "LPNK"}, new String[] {"Lockwood", "LKT", "LKT"}, new String[] {"Loines", "LNS", "LNS"}, new String[] {"Lombard", "LMPR", "LMPR"}, new String[] {"Long", "LNK", "LNK"}, new String[] {"Longespee", "LNJS", "LNKS"}, new String[] {"Look", "LK", "LK"}, new String[] {"Lounsberry", "LNSP", "LNSP"}, new String[] {"Lounsbury", "LNSP", "LNSP"}, new String[] {"Louthe", "L0", "LT"}, new String[] {"Loveyne", "LFN", "LFN"}, new String[] {"Lowe", "L", "L"}, new String[] {"Ludlam", "LTLM", "LTLM"}, new String[] {"Lumbard", "LMPR", "LMPR"}, new String[] {"Lund", "LNT", "LNT"}, new String[] {"Luno", "LN", "LN"}, new String[] {"Lutz", "LTS", "LTS"}, new String[] {"Lydia", "LT", "LT"}, new String[] {"Lynne", "LN", "LN"}, new String[] {"Lyon", "LN", "LN"}, new String[] {"MacAlpin", "MKLP", "MKLP"}, new String[] {"MacBricc", "MKPR", "MKPR"}, new String[] {"MacCrinan", "MKRN", "MKRN"}, new String[] {"MacKenneth", "MKN0", "MKNT"}, new String[] {"MacMael nam Bo","MKML", "MKML"}, new String[] {"MacMurchada", "MKMR", "MKMR"}, new String[] {"Macomber", "MKMP", "MKMP"}, new String[] {"Macy", "MS", "MS"}, new String[] {"Magnus", "MNS", "MKNS"}, new String[] {"Mahien", "MHN", "MHN"}, new String[] {"Malmains", "MLMN", "MLMN"}, new String[] {"Malory", "MLR", "MLR"}, new String[] {"Mancinelli", "MNSN", "MNSN"}, new String[] {"Mancini", "MNSN", "MNSN"}, new String[] {"Mann", "MN", "MN"}, new String[] {"Manning", "MNNK", "MNNK"}, new String[] {"Manter", "MNTR", "MNTR"}, new String[] {"Marion", "MRN", "MRN"}, new String[] {"Marley", "MRL", "MRL"}, new String[] {"Marmion", "MRMN", "MRMN"}, new String[] {"Marquart", "MRKR", "MRKR"}, new String[] {"Marsh", "MRX", "MRX"}, new String[] {"Marshal", "MRXL", "MRXL"}, new String[] {"Marshall", "MRXL", "MRXL"}, new String[] {"Martel", "MRTL", "MRTL"}, new String[] {"Martha", "MR0", "MRT"}, new String[] {"Martin", "MRTN", "MRTN"}, new String[] {"Marturano", "MRTR", "MRTR"}, new String[] {"Marvin", "MRFN", "MRFN"}, new String[] {"Mary", "MR", "MR"}, new String[] {"Mason", "MSN", "MSN"}, new String[] {"Maxwell", "MKSL", "MKSL"}, new String[] {"Mayhew", "MH", "MHF"}, new String[] {"McAllaster", "MKLS", "MKLS"}, new String[] {"McAllister", "MKLS", "MKLS"}, new String[] {"McConnell", "MKNL", "MKNL"}, new String[] {"McFarland", "MKFR", "MKFR"}, new String[] {"McIlroy", "MSLR", "MSLR"}, new String[] {"McNair", "MKNR", "MKNR"}, new String[] {"McNair-Landry","MKNR", "MKNR"}, new String[] {"McRaven", "MKRF", "MKRF"}, new String[] {"Mead", "MT", "MT"}, new String[] {"Meade", "MT", "MT"}, new String[] {"Meck", "MK", "MK"}, new String[] {"Melton", "MLTN", "MLTN"}, new String[] {"Mendenhall", "MNTN", "MNTN"}, new String[] {"Mering", "MRNK", "MRNK"}, new String[] {"Merrick", "MRK", "MRK"}, new String[] {"Merry", "MR", "MR"}, new String[] {"Mighill", "ML", "ML"}, new String[] {"Miller", "MLR", "MLR"}, new String[] {"Milton", "MLTN", "MLTN"}, new String[] {"Mohun", "MHN", "MHN"}, new String[] {"Montague", "MNTK", "MNTK"}, new String[] {"Montboucher", "MNTP", "MNTP"}, new String[] {"Moore", "MR", "MR"}, new String[] {"Morrel", "MRL", "MRL"}, new String[] {"Morrill", "MRL", "MRL"}, new String[] {"Morris", "MRS", "MRS"}, new String[] {"Morton", "MRTN", "MRTN"}, new String[] {"Moton", "MTN", "MTN"}, new String[] {"Muir", "MR", "MR"}, new String[] {"Mulferd", "MLFR", "MLFR"}, new String[] {"Mullins", "MLNS", "MLNS"}, new String[] {"Mulso", "MLS", "MLS"}, new String[] {"Munger", "MNKR", "MNJR"}, new String[] {"Munt", "MNT", "MNT"}, new String[] {"Murchad", "MRXT", "MRKT"}, new String[] {"Murdock", "MRTK", "MRTK"}, new String[] {"Murray", "MR", "MR"}, new String[] {"Muskett", "MSKT", "MSKT"}, new String[] {"Myers", "MRS", "MRS"}, new String[] {"Myrick", "MRK", "MRK"}, new String[] {"NORRIS", "NRS", "NRS"}, new String[] {"Nayle", "NL", "NL"}, new String[] {"Newcomb", "NKMP", "NKMP"}, new String[] {"Newcomb(e)", "NKMP", "NKMP"}, new String[] {"Newkirk", "NKRK", "NKRK"}, new String[] {"Newton", "NTN", "NTN"}, new String[] {"Niles", "NLS", "NLS"}, new String[] {"Noble", "NPL", "NPL"}, new String[] {"Noel", "NL", "NL"}, new String[] {"Northend", "NR0N", "NRTN"}, new String[] {"Norton", "NRTN", "NRTN"}, new String[] {"Nutter", "NTR", "NTR"}, new String[] {"Odding", "ATNK", "ATNK"}, new String[] {"Odenbaugh", "ATNP", "ATNP"}, new String[] {"Ogborn", "AKPR", "AKPR"}, new String[] {"Oppenheimer", "APNM", "APNM"}, new String[] {"Otis", "ATS", "ATS"}, new String[] {"Oviatt", "AFT", "AFT"}, new String[] {"PRUST?", "PRST", "PRST"}, new String[] {"Paddock", "PTK", "PTK"}, new String[] {"Page", "PJ", "PK"}, new String[] {"Paine", "PN", "PN"}, new String[] {"Paist", "PST", "PST"}, new String[] {"Palmer", "PLMR", "PLMR"}, new String[] {"Park", "PRK", "PRK"}, new String[] {"Parker", "PRKR", "PRKR"}, new String[] {"Parkhurst", "PRKR", "PRKR"}, new String[] {"Parrat", "PRT", "PRT"}, new String[] {"Parsons", "PRSN", "PRSN"}, new String[] {"Partridge", "PRTR", "PRTR"}, new String[] {"Pashley", "PXL", "PXL"}, new String[] {"Pasley", "PSL", "PSL"}, new String[] {"Patrick", "PTRK", "PTRK"}, new String[] {"Pattee", "PT", "PT"}, new String[] {"Patten", "PTN", "PTN"}, new String[] {"Pawley", "PL", "PL"}, new String[] {"Payne", "PN", "PN"}, new String[] {"Peabody", "PPT", "PPT"}, new String[] {"Peake", "PK", "PK"}, new String[] {"Pearson", "PRSN", "PRSN"}, new String[] {"Peat", "PT", "PT"}, new String[] {"Pedersen", "PTRS", "PTRS"}, new String[] {"Percy", "PRS", "PRS"}, new String[] {"Perkins", "PRKN", "PRKN"}, new String[] {"Perrine", "PRN", "PRN"}, new String[] {"Perry", "PR", "PR"}, new String[] {"Peson", "PSN", "PSN"}, new String[] {"Peterson", "PTRS", "PTRS"}, new String[] {"Peyton", "PTN", "PTN"}, new String[] {"Phinney", "FN", "FN"}, new String[] {"Pickard", "PKRT", "PKRT"}, new String[] {"Pierce", "PRS", "PRS"}, new String[] {"Pierrepont", "PRPN", "PRPN"}, new String[] {"Pike", "PK", "PK"}, new String[] {"Pinkham", "PNKM", "PNKM"}, new String[] {"Pitman", "PTMN", "PTMN"}, new String[] {"Pitt", "PT", "PT"}, new String[] {"Pitts", "PTS", "PTS"}, new String[] {"Plantagenet", "PLNT", "PLNT"}, new String[] {"Platt", "PLT", "PLT"}, new String[] {"Platts", "PLTS", "PLTS"}, new String[] {"Pleis", "PLS", "PLS"}, new String[] {"Pleiss", "PLS", "PLS"}, new String[] {"Plisko", "PLSK", "PLSK"}, new String[] {"Pliskovitch", "PLSK", "PLSK"}, new String[] {"Plum", "PLM", "PLM"}, new String[] {"Plume", "PLM", "PLM"}, new String[] {"Poitou", "PT", "PT"}, new String[] {"Pomeroy", "PMR", "PMR"}, new String[] {"Poretiers", "PRTR", "PRTR"}, new String[] {"Pote", "PT", "PT"}, new String[] {"Potter", "PTR", "PTR"}, new String[] {"Potts", "PTS", "PTS"}, new String[] {"Powell", "PL", "PL"}, new String[] {"Pratt", "PRT", "PRT"}, new String[] {"Presbury", "PRSP", "PRSP"}, new String[] {"Priest", "PRST", "PRST"}, new String[] {"Prindle", "PRNT", "PRNT"}, new String[] {"Prior", "PRR", "PRR"}, new String[] {"Profumo", "PRFM", "PRFM"}, new String[] {"Purdy", "PRT", "PRT"}, new String[] {"Purefoy", "PRF", "PRF"}, new String[] {"Pury", "PR", "PR"}, new String[] {"Quinter", "KNTR", "KNTR"}, new String[] {"Rachel", "RXL", "RKL"}, new String[] {"Rand", "RNT", "RNT"}, new String[] {"Rankin", "RNKN", "RNKN"}, new String[] {"Ravenscroft", "RFNS", "RFNS"}, new String[] {"Raynsford", "RNSF", "RNSF"}, new String[] {"Reakirt", "RKRT", "RKRT"}, new String[] {"Reaves", "RFS", "RFS"}, new String[] {"Reeves", "RFS", "RFS"}, new String[] {"Reichert", "RXRT", "RKRT"}, new String[] {"Remmele", "RML", "RML"}, new String[] {"Reynolds", "RNLT", "RNLT"}, new String[] {"Rhodes", "RTS", "RTS"}, new String[] {"Richards", "RXRT", "RKRT"}, new String[] {"Richardson", "RXRT", "RKRT"}, new String[] {"Ring", "RNK", "RNK"}, new String[] {"Roberts", "RPRT", "RPRT"}, new String[] {"Robertson", "RPRT", "RPRT"}, new String[] {"Robson", "RPSN", "RPSN"}, new String[] {"Rodie", "RT", "RT"}, new String[] {"Rody", "RT", "RT"}, new String[] {"Rogers", "RKRS", "RJRS"}, new String[] {"Ross", "RS", "RS"}, new String[] {"Rosslevin", "RSLF", "RSLF"}, new String[] {"Rowland", "RLNT", "RLNT"}, new String[] {"Ruehl", "RL", "RL"}, new String[] {"Russell", "RSL", "RSL"}, new String[] {"Ruth", "R0", "RT"}, new String[] {"Ryan", "RN", "RN"}, new String[] {"Rysse", "RS", "RS"}, new String[] {"Sadler", "STLR", "STLR"}, new String[] {"Salmon", "SLMN", "SLMN"}, new String[] {"Salter", "SLTR", "SLTR"}, new String[] {"Salvatore", "SLFT", "SLFT"}, new String[] {"Sanders", "SNTR", "SNTR"}, new String[] {"Sands", "SNTS", "SNTS"}, new String[] {"Sanford", "SNFR", "SNFR"}, new String[] {"Sanger", "SNKR", "SNJR"}, new String[] {"Sargent", "SRJN", "SRKN"}, new String[] {"Saunders", "SNTR", "SNTR"}, new String[] {"Schilling", "XLNK", "XLNK"}, new String[] {"Schlegel", "XLKL", "SLKL"}, new String[] {"Scott", "SKT", "SKT"}, new String[] {"Sears", "SRS", "SRS"}, new String[] {"Segersall", "SJRS", "SKRS"}, new String[] {"Senecal", "SNKL", "SNKL"}, new String[] {"Sergeaux", "SRJ", "SRK"}, new String[] {"Severance", "SFRN", "SFRN"}, new String[] {"Sharp", "XRP", "XRP"}, new String[] {"Sharpe", "XRP", "XRP"}, new String[] {"Sharply", "XRPL", "XRPL"}, new String[] {"Shatswell", "XTSL", "XTSL"}, new String[] {"Shattack", "XTK", "XTK"}, new String[] {"Shattock", "XTK", "XTK"}, new String[] {"Shattuck", "XTK", "XTK"}, new String[] {"Shaw", "X", "XF"}, new String[] {"Sheldon", "XLTN", "XLTN"}, new String[] {"Sherman", "XRMN", "XRMN"}, new String[] {"Shinn", "XN", "XN"}, new String[] {"Shirford", "XRFR", "XRFR"}, new String[] {"Shirley", "XRL", "XRL"}, new String[] {"Shively", "XFL", "XFL"}, new String[] {"Shoemaker", "XMKR", "XMKR"}, new String[] {"Short", "XRT", "XRT"}, new String[] {"Shotwell", "XTL", "XTL"}, new String[] {"Shute", "XT", "XT"}, new String[] {"Sibley", "SPL", "SPL"}, new String[] {"Silver", "SLFR", "SLFR"}, new String[] {"Simes", "SMS", "SMS"}, new String[] {"Sinken", "SNKN", "SNKN"}, new String[] {"Sinn", "SN", "SN"}, new String[] {"Skelton", "SKLT", "SKLT"}, new String[] {"Skiffe", "SKF", "SKF"}, new String[] {"Skotkonung", "SKTK", "SKTK"}, new String[] {"Slade", "SLT", "XLT"}, new String[] {"Slye", "SL", "XL"}, new String[] {"Smedley", "SMTL", "XMTL"}, new String[] {"Smith", "SM0", "XMT"}, new String[] {"Snow", "SN", "XNF"}, new String[] {"Soole", "SL", "SL"}, new String[] {"Soule", "SL", "SL"}, new String[] {"Southworth", "S0R0", "STRT"}, new String[] {"Sowles", "SLS", "SLS"}, new String[] {"Spalding", "SPLT", "SPLT"}, new String[] {"Spark", "SPRK", "SPRK"}, new String[] {"Spencer", "SPNS", "SPNS"}, new String[] {"Sperry", "SPR", "SPR"}, new String[] {"Spofford", "SPFR", "SPFR"}, new String[] {"Spooner", "SPNR", "SPNR"}, new String[] {"Sprague", "SPRK", "SPRK"}, new String[] {"Springer", "SPRN", "SPRN"}, new String[] {"St. Clair", "STKL", "STKL"}, new String[] {"St. Claire", "STKL", "STKL"}, new String[] {"St. Leger", "STLJ", "STLK"}, new String[] {"St. Omer", "STMR", "STMR"}, new String[] {"Stafferton", "STFR", "STFR"}, new String[] {"Stafford", "STFR", "STFR"}, new String[] {"Stalham", "STLM", "STLM"}, new String[] {"Stanford", "STNF", "STNF"}, new String[] {"Stanton", "STNT", "STNT"}, new String[] {"Star", "STR", "STR"}, new String[] {"Starbuck", "STRP", "STRP"}, new String[] {"Starkey", "STRK", "STRK"}, new String[] {"Starkweather","STRK", "STRK"}, new String[] {"Stearns", "STRN", "STRN"}, new String[] {"Stebbins", "STPN", "STPN"}, new String[] {"Steele", "STL", "STL"}, new String[] {"Stephenson", "STFN", "STFN"}, new String[] {"Stevens", "STFN", "STFN"}, new String[] {"Stoddard", "STTR", "STTR"}, new String[] {"Stodder", "STTR", "STTR"}, new String[] {"Stone", "STN", "STN"}, new String[] {"Storey", "STR", "STR"}, new String[] {"Storrada", "STRT", "STRT"}, new String[] {"Story", "STR", "STR"}, new String[] {"Stoughton", "STFT", "STFT"}, new String[] {"Stout", "STT", "STT"}, new String[] {"Stow", "ST", "STF"}, new String[] {"Strong", "STRN", "STRN"}, new String[] {"Strutt", "STRT", "STRT"}, new String[] {"Stryker", "STRK", "STRK"}, new String[] {"Stuckeley", "STKL", "STKL"}, new String[] {"Sturges", "STRJ", "STRK"}, new String[] {"Sturgess", "STRJ", "STRK"}, new String[] {"Sturgis", "STRJ", "STRK"}, new String[] {"Suevain", "SFN", "SFN"}, new String[] {"Sulyard", "SLRT", "SLRT"}, new String[] {"Sutton", "STN", "STN"}, new String[] {"Swain", "SN", "XN"}, new String[] {"Swayne", "SN", "XN"}, new String[] {"Swayze", "SS", "XTS"}, new String[] {"Swift", "SFT", "XFT"}, new String[] {"Taber", "TPR", "TPR"}, new String[] {"Talcott", "TLKT", "TLKT"}, new String[] {"Tarne", "TRN", "TRN"}, new String[] {"Tatum", "TTM", "TTM"}, new String[] {"Taverner", "TFRN", "TFRN"}, new String[] {"Taylor", "TLR", "TLR"}, new String[] {"Tenney", "TN", "TN"}, new String[] {"Thayer", "0R", "TR"}, new String[] {"Thember", "0MPR", "TMPR"}, new String[] {"Thomas", "TMS", "TMS"}, new String[] {"Thompson", "TMPS", "TMPS"}, new String[] {"Thorne", "0RN", "TRN"}, new String[] {"Thornycraft", "0RNK", "TRNK"}, new String[] {"Threlkeld", "0RLK", "TRLK"}, new String[] {"Throckmorton","0RKM", "TRKM"}, new String[] {"Thwaits", "0TS", "TTS"}, new String[] {"Tibbetts", "TPTS", "TPTS"}, new String[] {"Tidd", "TT", "TT"}, new String[] {"Tierney", "TRN", "TRN"}, new String[] {"Tilley", "TL", "TL"}, new String[] {"Tillieres", "TLRS", "TLRS"}, new String[] {"Tilly", "TL", "TL"}, new String[] {"Tisdale", "TSTL", "TSTL"}, new String[] {"Titus", "TTS", "TTS"}, new String[] {"Tobey", "TP", "TP"}, new String[] {"Tooker", "TKR", "TKR"}, new String[] {"Towle", "TL", "TL"}, new String[] {"Towne", "TN", "TN"}, new String[] {"Townsend", "TNSN", "TNSN"}, new String[] {"Treadway", "TRT", "TRT"}, new String[] {"Trelawney", "TRLN", "TRLN"}, new String[] {"Trinder", "TRNT", "TRNT"}, new String[] {"Tripp", "TRP", "TRP"}, new String[] {"Trippe", "TRP", "TRP"}, new String[] {"Trott", "TRT", "TRT"}, new String[] {"True", "TR", "TR"}, new String[] {"Trussebut", "TRSP", "TRSP"}, new String[] {"Tucker", "TKR", "TKR"}, new String[] {"Turgeon", "TRJN", "TRKN"}, new String[] {"Turner", "TRNR", "TRNR"}, new String[] {"Tuttle", "TTL", "TTL"}, new String[] {"Tyler", "TLR", "TLR"}, new String[] {"Tylle", "TL", "TL"}, new String[] {"Tyrrel", "TRL", "TRL"}, new String[] {"Ua Tuathail", "AT0L", "ATTL"}, new String[] {"Ulrich", "ALRX", "ALRK"}, new String[] {"Underhill", "ANTR", "ANTR"}, new String[] {"Underwood", "ANTR", "ANTR"}, new String[] {"Unknown", "ANKN", "ANKN"}, new String[] {"Valentine", "FLNT", "FLNT"}, new String[] {"Van Egmond", "FNKM", "FNKM"}, new String[] {"Van der Beek","FNTR", "FNTR"}, new String[] {"Vaughan", "FKN", "FKN"}, new String[] {"Vermenlen", "FRMN", "FRMN"}, new String[] {"Vincent", "FNSN", "FNSN"}, new String[] {"Volentine", "FLNT", "FLNT"}, new String[] {"Wagner", "AKNR", "FKNR"}, new String[] {"Waite", "AT", "FT"}, new String[] {"Walker", "ALKR", "FLKR"}, new String[] {"Walter", "ALTR", "FLTR"}, new String[] {"Wandell", "ANTL", "FNTL"}, new String[] {"Wandesford", "ANTS", "FNTS"}, new String[] {"Warbleton", "ARPL", "FRPL"}, new String[] {"Ward", "ART", "FRT"}, new String[] {"Warde", "ART", "FRT"}, new String[] {"Ware", "AR", "FR"}, new String[] {"Wareham", "ARHM", "FRHM"}, new String[] {"Warner", "ARNR", "FRNR"}, new String[] {"Warren", "ARN", "FRN"}, new String[] {"Washburne", "AXPR", "FXPR"}, new String[] {"Waterbury", "ATRP", "FTRP"}, new String[] {"Watson", "ATSN", "FTSN"}, new String[] {"WatsonEllithorpe","ATSN", "FTSN"}, new String[] {"Watts", "ATS", "FTS"}, new String[] {"Wayne", "AN", "FN"}, new String[] {"Webb", "AP", "FP"}, new String[] {"Weber", "APR", "FPR"}, new String[] {"Webster", "APST", "FPST"}, new String[] {"Weed", "AT", "FT"}, new String[] {"Weeks", "AKS", "FKS"}, new String[] {"Wells", "ALS", "FLS"}, new String[] {"Wenzell", "ANSL", "FNTS"}, new String[] {"West", "AST", "FST"}, new String[] {"Westbury", "ASTP", "FSTP"}, new String[] {"Whatlocke", "ATLK", "ATLK"}, new String[] {"Wheeler", "ALR", "ALR"}, new String[] {"Whiston", "ASTN", "ASTN"}, new String[] {"White", "AT", "AT"}, new String[] {"Whitman", "ATMN", "ATMN"}, new String[] {"Whiton", "ATN", "ATN"}, new String[] {"Whitson", "ATSN", "ATSN"}, new String[] {"Wickes", "AKS", "FKS"}, new String[] {"Wilbur", "ALPR", "FLPR"}, new String[] {"Wilcotes", "ALKT", "FLKT"}, new String[] {"Wilkinson", "ALKN", "FLKN"}, new String[] {"Willets", "ALTS", "FLTS"}, new String[] {"Willett", "ALT", "FLT"}, new String[] {"Willey", "AL", "FL"}, new String[] {"Williams", "ALMS", "FLMS"}, new String[] {"Williston", "ALST", "FLST"}, new String[] {"Wilson", "ALSN", "FLSN"}, new String[] {"Wimes", "AMS", "FMS"}, new String[] {"Winch", "ANX", "FNK"}, new String[] {"Winegar", "ANKR", "FNKR"}, new String[] {"Wing", "ANK", "FNK"}, new String[] {"Winsley", "ANSL", "FNSL"}, new String[] {"Winslow", "ANSL", "FNSL"}, new String[] {"Winthrop", "AN0R", "FNTR"}, new String[] {"Wise", "AS", "FS"}, new String[] {"Wood", "AT", "FT"}, new String[] {"Woodbridge", "ATPR", "FTPR"}, new String[] {"Woodward", "ATRT", "FTRT"}, new String[] {"Wooley", "AL", "FL"}, new String[] {"Woolley", "AL", "FL"}, new String[] {"Worth", "AR0", "FRT"}, new String[] {"Worthen", "AR0N", "FRTN"}, new String[] {"Worthley", "AR0L", "FRTL"}, new String[] {"Wright", "RT", "RT"}, new String[] {"Wyer", "AR", "FR"}, new String[] {"Wyere", "AR", "FR"}, new String[] {"Wynkoop", "ANKP", "FNKP"}, new String[] {"Yarnall", "ARNL", "ARNL"}, new String[] {"Yeoman", "AMN", "AMN"}, new String[] {"Yorke", "ARK", "ARK"}, new String[] {"Young", "ANK", "ANK"}, new String[] {"ab Wennonwen","APNN", "APNN"}, new String[] {"ap Llewellyn","APLL", "APLL"}, new String[] {"ap Lorwerth", "APLR", "APLR"}, new String[] {"d'Angouleme", "TNKL", "TNKL"}, new String[] {"de Audeham", "TTHM", "TTHM"}, new String[] {"de Bavant", "TPFN", "TPFN"}, new String[] {"de Beauchamp","TPXM", "TPKM"}, new String[] {"de Beaumont", "TPMN", "TPMN"}, new String[] {"de Bolbec", "TPLP", "TPLP"}, new String[] {"de Braiose", "TPRS", "TPRS"}, new String[] {"de Braose", "TPRS", "TPRS"}, new String[] {"de Briwere", "TPRR", "TPRR"}, new String[] {"de Cantelou", "TKNT", "TKNT"}, new String[] {"de Cherelton","TXRL", "TKRL"}, new String[] {"de Cherleton","TXRL", "TKRL"}, new String[] {"de Clare", "TKLR", "TKLR"}, new String[] {"de Claremont","TKLR", "TKLR"}, new String[] {"de Clifford", "TKLF", "TKLF"}, new String[] {"de Colville", "TKLF", "TKLF"}, new String[] {"de Courtenay","TKRT", "TKRT"}, new String[] {"de Fauconberg","TFKN", "TFKN"}, new String[] {"de Forest", "TFRS", "TFRS"}, new String[] {"de Gai", "TK", "TK"}, new String[] {"de Grey", "TKR", "TKR"}, new String[] {"de Guernons", "TKRN", "TKRN"}, new String[] {"de Haia", "T", "T"}, new String[] {"de Harcourt", "TRKR", "TRKR"}, new String[] {"de Hastings", "TSTN", "TSTN"}, new String[] {"de Hoke", "TK", "TK"}, new String[] {"de Hooch", "TK", "TK"}, new String[] {"de Hugelville","TJLF", "TKLF"}, new String[] {"de Huntingdon","TNTN", "TNTN"}, new String[] {"de Insula", "TNSL", "TNSL"}, new String[] {"de Keynes", "TKNS", "TKNS"}, new String[] {"de Lacy", "TLS", "TLS"}, new String[] {"de Lexington","TLKS", "TLKS"}, new String[] {"de Lusignan", "TLSN", "TLSK"}, new String[] {"de Manvers", "TMNF", "TMNF"}, new String[] {"de Montagu", "TMNT", "TMNT"}, new String[] {"de Montault", "TMNT", "TMNT"}, new String[] {"de Montfort", "TMNT", "TMNT"}, new String[] {"de Mortimer", "TMRT", "TMRT"}, new String[] {"de Morville", "TMRF", "TMRF"}, new String[] {"de Morvois", "TMRF", "TMRF"}, new String[] {"de Neufmarche","TNFM", "TNFM"}, new String[] {"de Odingsells","TTNK", "TTNK"}, new String[] {"de Odyngsells","TTNK", "TTNK"}, new String[] {"de Percy", "TPRS", "TPRS"}, new String[] {"de Pierrepont","TPRP", "TPRP"}, new String[] {"de Plessetis","TPLS", "TPLS"}, new String[] {"de Porhoet", "TPRT", "TPRT"}, new String[] {"de Prouz", "TPRS", "TPRS"}, new String[] {"de Quincy", "TKNS", "TKNS"}, new String[] {"de Ripellis", "TRPL", "TRPL"}, new String[] {"de Ros", "TRS", "TRS"}, new String[] {"de Salisbury","TSLS", "TSLS"}, new String[] {"de Sanford", "TSNF", "TSNF"}, new String[] {"de Somery", "TSMR", "TSMR"}, new String[] {"de St. Hilary","TSTL", "TSTL"}, new String[] {"de St. Liz", "TSTL", "TSTL"}, new String[] {"de Sutton", "TSTN", "TSTN"}, new String[] {"de Toeni", "TTN", "TTN"}, new String[] {"de Tony", "TTN", "TTN"}, new String[] {"de Umfreville","TMFR", "TMFR"}, new String[] {"de Valognes", "TFLN", "TFLK"}, new String[] {"de Vaux", "TF", "TF"}, new String[] {"de Vere", "TFR", "TFR"}, new String[] {"de Vermandois","TFRM", "TFRM"}, new String[] {"de Vernon", "TFRN", "TFRN"}, new String[] {"de Vexin", "TFKS", "TFKS"}, new String[] {"de Vitre", "TFTR", "TFTR"}, new String[] {"de Wandesford","TNTS", "TNTS"}, new String[] {"de Warenne", "TRN", "TRN"}, new String[] {"de Westbury", "TSTP", "TSTP"}, new String[] {"di Saluzzo", "TSLS", "TSLT"}, new String[] {"fitz Alan", "FTSL", "FTSL"}, new String[] {"fitz Geoffrey","FTSJ", "FTSK"}, new String[] {"fitz Herbert","FTSR", "FTSR"}, new String[] {"fitz John", "FTSJ", "FTSJ"}, new String[] {"fitz Patrick","FTSP", "FTSP"}, new String[] {"fitz Payn", "FTSP", "FTSP"}, new String[] {"fitz Piers", "FTSP", "FTSP"}, new String[] {"fitz Randolph","FTSR", "FTSR"}, new String[] {"fitz Richard","FTSR", "FTSR"}, new String[] {"fitz Robert", "FTSR", "FTSR"}, new String[] {"fitz Roy", "FTSR", "FTSR"}, new String[] {"fitz Scrob", "FTSS", "FTSS"}, new String[] {"fitz Walter", "FTSL", "FTSL"}, new String[] {"fitz Warin", "FTSR", "FTSR"}, new String[] {"fitz Williams","FTSL", "FTSL"}, new String[] {"la Zouche", "LSX", "LSK"}, new String[] {"le Botiller", "LPTL", "LPTL"}, new String[] {"le Despenser","LTSP", "LTSP"}, new String[] {"le deSpencer","LTSP", "LTSP"}, new String[] {"of Allendale","AFLN", "AFLN"}, new String[] {"of Angouleme","AFNK", "AFNK"}, new String[] {"of Anjou", "AFNJ", "AFNJ"}, new String[] {"of Aquitaine","AFKT", "AFKT"}, new String[] {"of Aumale", "AFML", "AFML"}, new String[] {"of Bavaria", "AFPF", "AFPF"}, new String[] {"of Boulogne", "AFPL", "AFPL"}, new String[] {"of Brittany", "AFPR", "AFPR"}, new String[] {"of Brittary", "AFPR", "AFPR"}, new String[] {"of Castile", "AFKS", "AFKS"}, new String[] {"of Chester", "AFXS", "AFKS"}, new String[] {"of Clermont", "AFKL", "AFKL"}, new String[] {"of Cologne", "AFKL", "AFKL"}, new String[] {"of Dinan", "AFTN", "AFTN"}, new String[] {"of Dunbar", "AFTN", "AFTN"}, new String[] {"of England", "AFNK", "AFNK"}, new String[] {"of Essex", "AFSK", "AFSK"}, new String[] {"of Falaise", "AFFL", "AFFL"}, new String[] {"of Flanders", "AFFL", "AFFL"}, new String[] {"of Galloway", "AFKL", "AFKL"}, new String[] {"of Germany", "AFKR", "AFJR"}, new String[] {"of Gloucester","AFKL", "AFKL"}, new String[] {"of Heristal", "AFRS", "AFRS"}, new String[] {"of Hungary", "AFNK", "AFNK"}, new String[] {"of Huntington","AFNT", "AFNT"}, new String[] {"of Kiev", "AFKF", "AFKF"}, new String[] {"of Kuno", "AFKN", "AFKN"}, new String[] {"of Landen", "AFLN", "AFLN"}, new String[] {"of Laon", "AFLN", "AFLN"}, new String[] {"of Leinster", "AFLN", "AFLN"}, new String[] {"of Lens", "AFLN", "AFLN"}, new String[] {"of Lorraine", "AFLR", "AFLR"}, new String[] {"of Louvain", "AFLF", "AFLF"}, new String[] {"of Mercia", "AFMR", "AFMR"}, new String[] {"of Metz", "AFMT", "AFMT"}, new String[] {"of Meulan", "AFML", "AFML"}, new String[] {"of Nass", "AFNS", "AFNS"}, new String[] {"of Normandy", "AFNR", "AFNR"}, new String[] {"of Ohningen", "AFNN", "AFNN"}, new String[] {"of Orleans", "AFRL", "AFRL"}, new String[] {"of Poitou", "AFPT", "AFPT"}, new String[] {"of Polotzk", "AFPL", "AFPL"}, new String[] {"of Provence", "AFPR", "AFPR"}, new String[] {"of Ringelheim","AFRN", "AFRN"}, new String[] {"of Salisbury","AFSL", "AFSL"}, new String[] {"of Saxony", "AFSK", "AFSK"}, new String[] {"of Scotland", "AFSK", "AFSK"}, new String[] {"of Senlis", "AFSN", "AFSN"}, new String[] {"of Stafford", "AFST", "AFST"}, new String[] {"of Swabia", "AFSP", "AFSP"}, new String[] {"of Tongres", "AFTN", "AFTN"}, new String[] {"of the Tributes","AF0T", "AFTT"}, new String[] {"unknown", "ANKN", "ANKN"}, new String[] {"van der Gouda","FNTR", "FNTR"}, new String[] {"von Adenbaugh","FNTN", "FNTN"}, new String[] {"ARCHITure", "ARKT", "ARKT"}, new String[] {"Arnoff", "ARNF", "ARNF"}, new String[] {"Arnow", "ARN", "ARNF"}, new String[] {"DANGER", "TNJR", "TNKR"}, new String[] {"Jankelowicz", "JNKL", "ANKL"}, new String[] {"MANGER", "MNJR", "MNKR"}, new String[] {"McClellan", "MKLL", "MKLL"}, new String[] {"McHugh", "MK", "MK"}, new String[] {"McLaughlin", "MKLF", "MKLF"}, new String[] {"ORCHEStra", "ARKS", "ARKS"}, new String[] {"ORCHID", "ARKT", "ARKT"}, new String[] {"Pierce", "PRS", "PRS"}, new String[] {"RANGER", "RNJR", "RNKR"}, new String[] {"Schlesinger", "XLSN", "SLSN"}, new String[] {"Uomo", "AM", "AM"}, new String[] {"Vasserman", "FSRM", "FSRM"}, new String[] {"Wasserman", "ASRM", "FSRM"}, new String[] {"Womo", "AM", "FM"}, new String[] {"Yankelovich", "ANKL", "ANKL"}, new String[] {"accede", "AKST", "AKST"}, new String[] {"accident", "AKST", "AKST"}, new String[] {"adelsheim", "ATLS", "ATLS"}, new String[] {"aged", "AJT", "AKT"}, new String[] {"ageless", "AJLS", "AKLS"}, new String[] {"agency", "AJNS", "AKNS"}, new String[] {"aghast", "AKST", "AKST"}, new String[] {"agio", "AJ", "AK"}, new String[] {"agrimony", "AKRM", "AKRM"}, new String[] {"album", "ALPM", "ALPM"}, new String[] {"alcmene", "ALKM", "ALKM"}, new String[] {"alehouse", "ALHS", "ALHS"}, new String[] {"antique", "ANTK", "ANTK"}, new String[] {"artois", "ART", "ARTS"}, new String[] {"automation", "ATMX", "ATMX"}, new String[] {"bacchus", "PKS", "PKS"}, new String[] {"bacci", "PX", "PX"}, new String[] {"bajador", "PJTR", "PHTR"}, new String[] {"bellocchio", "PLX", "PLX"}, new String[] {"bertucci", "PRTX", "PRTX"}, new String[] {"biaggi", "PJ", "PK"}, new String[] {"bough", "P", "P"}, new String[] {"breaux", "PR", "PR"}, new String[] {"broughton", "PRTN", "PRTN"}, new String[] {"cabrillo", "KPRL", "KPR"}, new String[] {"caesar", "SSR", "SSR"}, new String[] {"cagney", "KKN", "KKN"}, new String[] {"campbell", "KMPL", "KMPL"}, new String[] {"carlisle", "KRLL", "KRLL"}, new String[] {"carlysle", "KRLL", "KRLL"}, new String[] {"chemistry", "KMST", "KMST"}, new String[] {"chianti", "KNT", "KNT"}, new String[] {"chorus", "KRS", "KRS"}, new String[] {"cough", "KF", "KF"}, new String[] {"czerny", "SRN", "XRN"}, new String[] {"deffenbacher","TFNP", "TFNP"}, new String[] {"dumb", "TM", "TM"}, new String[] {"edgar", "ATKR", "ATKR"}, new String[] {"edge", "AJ", "AJ"}, new String[] {"filipowicz", "FLPT", "FLPF"}, new String[] {"focaccia", "FKX", "FKX"}, new String[] {"gallegos", "KLKS", "KKS"}, new String[] {"gambrelli", "KMPR", "KMPR"}, new String[] {"geithain", "K0N", "JTN"}, new String[] {"ghiradelli", "JRTL", "JRTL"}, new String[] {"ghislane", "JLN", "JLN"}, new String[] {"gough", "KF", "KF"}, new String[] {"hartheim", "HR0M", "HRTM"}, new String[] {"heimsheim", "HMSM", "HMSM"}, new String[] {"hochmeier", "HKMR", "HKMR"}, new String[] {"hugh", "H", "H"}, new String[] {"hunger", "HNKR", "HNJR"}, new String[] {"hungry", "HNKR", "HNKR"}, new String[] {"island", "ALNT", "ALNT"}, new String[] {"isle", "AL", "AL"}, new String[] {"jose", "HS", "HS"}, new String[] {"laugh", "LF", "LF"}, new String[] {"mac caffrey", "MKFR", "MKFR"}, new String[] {"mac gregor", "MKRK", "MKRK"}, new String[] {"pegnitz", "PNTS", "PKNT"}, new String[] {"piskowitz", "PSKT", "PSKF"}, new String[] {"queen", "KN", "KN"}, new String[] {"raspberry", "RSPR", "RSPR"}, new String[] {"resnais", "RSN", "RSNS"}, new String[] {"rogier", "RJ", "RJR"}, new String[] {"rough", "RF", "RF"}, new String[] {"san jacinto", "SNHS", "SNHS"}, new String[] {"schenker", "XNKR", "SKNK"}, new String[] {"schermerhorn","XRMR", "SKRM"}, new String[] {"schmidt", "XMT", "SMT"}, new String[] {"schneider", "XNTR", "SNTR"}, new String[] {"school", "SKL", "SKL"}, new String[] {"schooner", "SKNR", "SKNR"}, new String[] {"schrozberg", "XRSP", "SRSP"}, new String[] {"schulman", "XLMN", "XLMN"}, new String[] {"schwabach", "XPK", "XFPK"}, new String[] {"schwarzach", "XRSK", "XFRT"}, new String[] {"smith", "SM0", "XMT"}, new String[] {"snider", "SNTR", "XNTR"}, new String[] {"succeed", "SKST", "SKST"}, new String[] {"sugarcane", "XKRK", "SKRK"}, new String[] {"svobodka", "SFPT", "SFPT"}, new String[] {"tagliaro", "TKLR", "TLR"}, new String[] {"thames", "TMS", "TMS"}, new String[] {"theilheim", "0LM", "TLM"}, new String[] {"thomas", "TMS", "TMS"}, new String[] {"thumb", "0M", "TM"}, new String[] {"tichner", "TXNR", "TKNR"}, new String[] {"tough", "TF", "TF"}, new String[] {"umbrella", "AMPR", "AMPR"}, new String[] {"vilshofen", "FLXF", "FLXF"}, new String[] {"von schuller","FNXL", "FNXL"}, new String[] {"wachtler", "AKTL", "FKTL"}, new String[] {"wechsler", "AKSL", "FKSL"}, new String[] {"weikersheim", "AKRS", "FKRS"}, new String[] {"zhao", "J", "J"} }; }
@Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToSame() { mock.objectArgMethod("not null"); verify(mock).objectArgMethod(same(null)); }
org.mockitousage.bugs.NPEWithCertainMatchersTest::shouldNotThrowNPEWhenNullPassedToSame
test/org/mockitousage/bugs/NPEWithCertainMatchersTest.java
65
test/org/mockitousage/bugs/NPEWithCertainMatchersTest.java
shouldNotThrowNPEWhenNullPassedToSame
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.bugs; import org.junit.After; import org.junit.Test; import org.mockito.Mock; import org.mockitousage.IMethods; import org.mockitoutil.TestBase; import static org.mockito.Matchers.*; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class NPEWithCertainMatchersTest extends TestBase { @Mock IMethods mock; @After public void clearState() { this.resetState(); } @Test public void shouldNotThrowNPEWhenIntegerPassed() { mock.intArgumentMethod(100); verify(mock).intArgumentMethod(isA(Integer.class)); } @Test public void shouldNotThrowNPEWhenIntPassed() { mock.intArgumentMethod(100); verify(mock).intArgumentMethod(isA(Integer.class)); } @Test public void shouldNotThrowNPEWhenIntegerPassedToEq() { mock.intArgumentMethod(100); verify(mock).intArgumentMethod(eq(new Integer(100))); } @Test public void shouldNotThrowNPEWhenIntegerPassedToSame() { mock.intArgumentMethod(100); verify(mock, never()).intArgumentMethod(same(new Integer(100))); } @Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToEq() { mock.objectArgMethod("not null"); verify(mock).objectArgMethod(eq(null)); } @Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToSame() { mock.objectArgMethod("not null"); verify(mock).objectArgMethod(same(null)); } }
// You are a professional Java test case writer, please create a test case named `shouldNotThrowNPEWhenNullPassedToSame` for the issue `Mockito-229`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-229 // // ## Issue-Title: // Fixes #228: fixed a verify() call example in @Captor javadoc // // ## Issue-Description: // Thanks for the fix :) // // // // @Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToSame() {
65
29
60
test/org/mockitousage/bugs/NPEWithCertainMatchersTest.java
test
```markdown ## Issue-ID: Mockito-229 ## Issue-Title: Fixes #228: fixed a verify() call example in @Captor javadoc ## Issue-Description: Thanks for the fix :) ``` You are a professional Java test case writer, please create a test case named `shouldNotThrowNPEWhenNullPassedToSame` for the issue `Mockito-229`, utilizing the provided issue report information and the following function signature. ```java @Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToSame() { ```
60
[ "org.mockito.internal.matchers.Same" ]
ea546db1d5c2be48d811671a413d8d67a24293a6a57e22370855c6245afe3327
@Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToSame()
// You are a professional Java test case writer, please create a test case named `shouldNotThrowNPEWhenNullPassedToSame` for the issue `Mockito-229`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-229 // // ## Issue-Title: // Fixes #228: fixed a verify() call example in @Captor javadoc // // ## Issue-Description: // Thanks for the fix :) // // // //
Mockito
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.bugs; import org.junit.After; import org.junit.Test; import org.mockito.Mock; import org.mockitousage.IMethods; import org.mockitoutil.TestBase; import static org.mockito.Matchers.*; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class NPEWithCertainMatchersTest extends TestBase { @Mock IMethods mock; @After public void clearState() { this.resetState(); } @Test public void shouldNotThrowNPEWhenIntegerPassed() { mock.intArgumentMethod(100); verify(mock).intArgumentMethod(isA(Integer.class)); } @Test public void shouldNotThrowNPEWhenIntPassed() { mock.intArgumentMethod(100); verify(mock).intArgumentMethod(isA(Integer.class)); } @Test public void shouldNotThrowNPEWhenIntegerPassedToEq() { mock.intArgumentMethod(100); verify(mock).intArgumentMethod(eq(new Integer(100))); } @Test public void shouldNotThrowNPEWhenIntegerPassedToSame() { mock.intArgumentMethod(100); verify(mock, never()).intArgumentMethod(same(new Integer(100))); } @Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToEq() { mock.objectArgMethod("not null"); verify(mock).objectArgMethod(eq(null)); } @Test(expected = AssertionError.class) public void shouldNotThrowNPEWhenNullPassedToSame() { mock.objectArgMethod("not null"); verify(mock).objectArgMethod(same(null)); } }
public void testNonAliasLocal() { testScopedFailure("var x = 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog.dom + 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog['dom']", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog.dom, y = 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("function f() {}", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); }
com.google.javascript.jscomp.ScopedAliasesTest::testNonAliasLocal
test/com/google/javascript/jscomp/ScopedAliasesTest.java
414
test/com/google/javascript/jscomp/ScopedAliasesTest.java
testNonAliasLocal
/* * Copyright 2010 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.javascript.jscomp.CompilerOptions.AliasTransformation; import com.google.javascript.jscomp.CompilerOptions.AliasTransformationHandler; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SourcePosition; import java.util.Collection; import java.util.List; import java.util.Map; /** * Tests for {@link ScopedAliases} * * @author robbyw@google.com (Robby Walker) */ public class ScopedAliasesTest extends CompilerTestCase { private static final String GOOG_SCOPE_START_BLOCK = "goog.scope(function() {"; private static final String GOOG_SCOPE_END_BLOCK = "});"; private static String EXTERNS = "var window;"; AliasTransformationHandler transformationHandler = CompilerOptions.NULL_ALIAS_TRANSFORMATION_HANDLER; public ScopedAliasesTest() { super(EXTERNS); } private void testScoped(String code, String expected) { test(GOOG_SCOPE_START_BLOCK + code + GOOG_SCOPE_END_BLOCK, expected); } private void testScopedNoChanges(String aliases, String code) { testScoped(aliases + code, code); } public void testOneLevel() { testScoped("var g = goog;g.dom.createElement(g.dom.TagName.DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testTwoLevel() { testScoped("var d = goog.dom;d.createElement(d.TagName.DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testTransitive() { testScoped("var d = goog.dom;var DIV = d.TagName.DIV;d.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testTransitiveInSameVar() { testScoped("var d = goog.dom, DIV = d.TagName.DIV;d.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testMultipleTransitive() { testScoped( "var g=goog;var d=g.dom;var t=d.TagName;var DIV=t.DIV;" + "d.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testFourLevel() { testScoped("var DIV = goog.dom.TagName.DIV;goog.dom.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testWorksInClosures() { testScoped( "var DIV = goog.dom.TagName.DIV;" + "goog.x = function() {goog.dom.createElement(DIV);};", "goog.x = function() {goog.dom.createElement(goog.dom.TagName.DIV);};"); } public void testOverridden() { // Test that the alias doesn't get unaliased when it's overridden by a // parameter. testScopedNoChanges( "var g = goog;", "goog.x = function(g) {g.z()};"); // Same for a local. testScopedNoChanges( "var g = goog;", "goog.x = function() {var g = {}; g.z()};"); } public void testTwoScopes() { test( "goog.scope(function() {var g = goog;g.method()});" + "goog.scope(function() {g.method();});", "goog.method();g.method();"); } public void testTwoSymbolsInTwoScopes() { test( "var goog = {};" + "goog.scope(function() { var g = goog; g.Foo = function() {}; });" + "goog.scope(function() { " + " var Foo = goog.Foo; goog.bar = function() { return new Foo(); };" + "});", "var goog = {};" + "goog.Foo = function() {};" + "goog.bar = function() { return new goog.Foo(); };"); } public void testAliasOfSymbolInGoogScope() { test( "var goog = {};" + "goog.scope(function() {" + " var g = goog;" + " g.Foo = function() {};" + " var Foo = g.Foo;" + " Foo.prototype.bar = function() {};" + "});", "var goog = {}; goog.Foo = function() {};" + "goog.Foo.prototype.bar = function() {};"); } public void testScopedFunctionReturnThis() { test("goog.scope(function() { " + " var g = goog; g.f = function() { return this; };" + "});", "goog.f = function() { return this; };"); } public void testScopedFunctionAssignsToVar() { test("goog.scope(function() { " + " var g = goog; g.f = function(x) { x = 3; return x; };" + "});", "goog.f = function(x) { x = 3; return x; };"); } public void testScopedFunctionThrows() { test("goog.scope(function() { " + " var g = goog; g.f = function() { throw 'error'; };" + "});", "goog.f = function() { throw 'error'; };"); } public void testPropertiesNotChanged() { testScopedNoChanges("var x = goog.dom;", "y.x();"); } public void testShadowedVar() { test("var Popup = {};" + "var OtherPopup = {};" + "goog.scope(function() {" + " var Popup = OtherPopup;" + " Popup.newMethod = function() { return new Popup(); };" + "});", "var Popup = {};" + "var OtherPopup = {};" + "OtherPopup.newMethod = function() { return new OtherPopup(); };"); } private void testTypes(String aliases, String code) { testScopedNoChanges(aliases, code); verifyTypes(); } private void verifyTypes() { Compiler lastCompiler = getLastCompiler(); new TypeVerifyingPass(lastCompiler).process(lastCompiler.externsRoot, lastCompiler.jsRoot); } public void testJsDocType() { testTypes( "var x = goog.Timer;", "" + "/** @type {x} */ types.actual;" + "/** @type {goog.Timer} */ types.expected;"); } public void testJsDocParameter() { testTypes( "var x = goog.Timer;", "" + "/** @param {x} a */ types.actual;" + "/** @param {goog.Timer} a */ types.expected;"); } public void testJsDocExtends() { testTypes( "var x = goog.Timer;", "" + "/** @extends {x} */ types.actual;" + "/** @extends {goog.Timer} */ types.expected;"); } public void testJsDocImplements() { testTypes( "var x = goog.Timer;", "" + "/** @implements {x} */ types.actual;" + "/** @implements {goog.Timer} */ types.expected;"); } public void testJsDocEnum() { testTypes( "var x = goog.Timer;", "" + "/** @enum {x} */ types.actual;" + "/** @enum {goog.Timer} */ types.expected;"); } public void testJsDocReturn() { testTypes( "var x = goog.Timer;", "" + "/** @return {x} */ types.actual;" + "/** @return {goog.Timer} */ types.expected;"); } public void testJsDocThis() { testTypes( "var x = goog.Timer;", "" + "/** @this {x} */ types.actual;" + "/** @this {goog.Timer} */ types.expected;"); } public void testJsDocThrows() { testTypes( "var x = goog.Timer;", "" + "/** @throws {x} */ types.actual;" + "/** @throws {goog.Timer} */ types.expected;"); } public void testJsDocSubType() { testTypes( "var x = goog.Timer;", "" + "/** @type {x.Enum} */ types.actual;" + "/** @type {goog.Timer.Enum} */ types.expected;"); } public void testJsDocTypedef() { testTypes( "var x = goog.Timer;", "" + "/** @typedef {x} */ types.actual;" + "/** @typedef {goog.Timer} */ types.expected;"); } public void testArrayJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {Array.<x>} */ types.actual;" + "/** @type {Array.<goog.Timer>} */ types.expected;"); } public void testObjectJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {{someKey: x}} */ types.actual;" + "/** @type {{someKey: goog.Timer}} */ types.expected;"); testTypes( "var x = goog.Timer;", "" + "/** @type {{x: number}} */ types.actual;" + "/** @type {{x: number}} */ types.expected;"); } public void testUnionJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {x|Object} */ types.actual;" + "/** @type {goog.Timer|Object} */ types.expected;"); } public void testFunctionJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {function(x) : void} */ types.actual;" + "/** @type {function(goog.Timer) : void} */ types.expected;"); testTypes( "var x = goog.Timer;", "" + "/** @type {function() : x} */ types.actual;" + "/** @type {function() : goog.Timer} */ types.expected;"); } public void testForwardJsDoc() { testScoped( "/**\n" + " * @constructor\n" + " */\n" + "foo.Foo = function() {};" + "/** @param {Foo.Bar} x */ foo.Foo.actual = function(x) {3};" + "var Foo = foo.Foo;" + "/** @constructor */ Foo.Bar = function() {};" + "/** @param {foo.Foo.Bar} x */ foo.Foo.expected = function(x) {};", "/**\n" + " * @constructor\n" + " */\n" + "foo.Foo = function() {};" + "/** @param {foo.Foo.Bar} x */ foo.Foo.actual = function(x) {3};" + "/** @constructor */ foo.Foo.Bar = function() {};" + "/** @param {foo.Foo.Bar} x */ foo.Foo.expected = function(x) {};"); verifyTypes(); } public void testTestTypes() { try { testTypes( "var x = goog.Timer;", "" + "/** @type {function() : x} */ types.actual;" + "/** @type {function() : wrong.wrong} */ types.expected;"); fail("Test types should fail here."); } catch (AssertionError e) { } } public void testNullType() { testTypes( "var x = goog.Timer;", "/** @param draggable */ types.actual;" + "/** @param draggable */ types.expected;"); } // TODO(robbyw): What if it's recursive? var goog = goog.dom; // FAILURE CASES private void testFailure(String code, DiagnosticType expectedError) { test(code, null, expectedError); } private void testScopedFailure(String code, DiagnosticType expectedError) { test("goog.scope(function() {" + code + "});", null, expectedError); } public void testScopedThis() { testScopedFailure("this.y = 10;", ScopedAliases.GOOG_SCOPE_REFERENCES_THIS); testScopedFailure("var x = this;", ScopedAliases.GOOG_SCOPE_REFERENCES_THIS); testScopedFailure("fn(this);", ScopedAliases.GOOG_SCOPE_REFERENCES_THIS); } public void testAliasRedefinition() { testScopedFailure("var x = goog.dom; x = goog.events;", ScopedAliases.GOOG_SCOPE_ALIAS_REDEFINED); } public void testAliasNonRedefinition() { test("var y = {}; goog.scope(function() { goog.dom = y; });", "var y = {}; goog.dom = y;"); } public void testScopedReturn() { testScopedFailure("return;", ScopedAliases.GOOG_SCOPE_USES_RETURN); testScopedFailure("var x = goog.dom; return;", ScopedAliases.GOOG_SCOPE_USES_RETURN); } public void testScopedThrow() { testScopedFailure("throw 'error';", ScopedAliases.GOOG_SCOPE_USES_THROW); } public void testUsedImproperly() { testFailure("var x = goog.scope(function() {});", ScopedAliases.GOOG_SCOPE_USED_IMPROPERLY); } public void testBadParameters() { testFailure("goog.scope()", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(10)", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(function() {}, 10)", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(function z() {})", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(function(a, b, c) {})", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); } public void testNonAliasLocal() { testScopedFailure("var x = 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog.dom + 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog['dom']", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog.dom, y = 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("function f() {}", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); } // Alias Recording Tests // TODO(tylerg) : update these to EasyMock style tests once available public void testNoGoogScope() { String fullJsCode = "var g = goog;\n g.dom.createElement(g.dom.TagName.DIV);"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, fullJsCode); assertTrue(spy.observedPositions.isEmpty()); } public void testRecordOneAlias() { String fullJsCode = GOOG_SCOPE_START_BLOCK + "var g = goog;\n g.dom.createElement(g.dom.TagName.DIV);\n" + GOOG_SCOPE_END_BLOCK; String expectedJsCode = "goog.dom.createElement(goog.dom.TagName.DIV);\n"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, expectedJsCode); assertTrue(spy.observedPositions.containsKey("testcode")); List<SourcePosition<AliasTransformation>> positions = spy.observedPositions.get("testcode"); assertEquals(1, positions.size()); verifyAliasTransformationPosition(1, 0, 2, 1, positions.get(0)); assertEquals(1, spy.constructedAliases.size()); AliasSpy aliasSpy = (AliasSpy) spy.constructedAliases.get(0); assertEquals("goog", aliasSpy.observedDefinitions.get("g")); } public void testRecordMultipleAliases() { String fullJsCode = GOOG_SCOPE_START_BLOCK + "var g = goog;\n var b= g.bar;\n var f = goog.something.foo;" + "g.dom.createElement(g.dom.TagName.DIV);\n b.foo();" + GOOG_SCOPE_END_BLOCK; String expectedJsCode = "goog.dom.createElement(goog.dom.TagName.DIV);\n goog.bar.foo();"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, expectedJsCode); assertTrue(spy.observedPositions.containsKey("testcode")); List<SourcePosition<AliasTransformation>> positions = spy.observedPositions.get("testcode"); assertEquals(1, positions.size()); verifyAliasTransformationPosition(1, 0, 3, 1, positions.get(0)); assertEquals(1, spy.constructedAliases.size()); AliasSpy aliasSpy = (AliasSpy) spy.constructedAliases.get(0); assertEquals("goog", aliasSpy.observedDefinitions.get("g")); assertEquals("g.bar", aliasSpy.observedDefinitions.get("b")); assertEquals("goog.something.foo", aliasSpy.observedDefinitions.get("f")); } public void testRecordAliasFromMultipleGoogScope() { String firstGoogScopeBlock = GOOG_SCOPE_START_BLOCK + "\n var g = goog;\n g.dom.createElement(g.dom.TagName.DIV);\n" + GOOG_SCOPE_END_BLOCK; String fullJsCode = firstGoogScopeBlock + "\n\nvar l = abc.def;\n\n" + GOOG_SCOPE_START_BLOCK + "\n var z = namespace.Zoo;\n z.getAnimals(l);\n" + GOOG_SCOPE_END_BLOCK; String expectedJsCode = "goog.dom.createElement(goog.dom.TagName.DIV);\n" + "\n\nvar l = abc.def;\n\n" + "\n namespace.Zoo.getAnimals(l);\n"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, expectedJsCode); assertTrue(spy.observedPositions.containsKey("testcode")); List<SourcePosition<AliasTransformation>> positions = spy.observedPositions.get("testcode"); assertEquals(2, positions.size()); verifyAliasTransformationPosition(1, 0, 6, 0, positions.get(0)); verifyAliasTransformationPosition(8, 0, 11, 4, positions.get(1)); assertEquals(2, spy.constructedAliases.size()); AliasSpy aliasSpy = (AliasSpy) spy.constructedAliases.get(0); assertEquals("goog", aliasSpy.observedDefinitions.get("g")); aliasSpy = (AliasSpy) spy.constructedAliases.get(1); assertEquals("namespace.Zoo", aliasSpy.observedDefinitions.get("z")); } private void verifyAliasTransformationPosition(int startLine, int startChar, int endLine, int endChar, SourcePosition<AliasTransformation> pos) { assertEquals(startLine, pos.getStartLine()); assertEquals(startChar, pos.getPositionOnStartLine()); assertTrue( "expected endline >= " + endLine + ". Found " + pos.getEndLine(), pos.getEndLine() >= endLine); assertTrue("expected endChar >= " + endChar + ". Found " + pos.getPositionOnEndLine(), pos.getPositionOnEndLine() >= endChar); } @Override protected ScopedAliases getProcessor(Compiler compiler) { return new ScopedAliases(compiler, null, transformationHandler); } private static class TransformationHandlerSpy implements AliasTransformationHandler { private final Map<String, List<SourcePosition<AliasTransformation>>> observedPositions = Maps.newHashMap(); public final List<AliasTransformation> constructedAliases = Lists.newArrayList(); @Override public AliasTransformation logAliasTransformation( String sourceFile, SourcePosition<AliasTransformation> position) { if(!observedPositions.containsKey(sourceFile)) { observedPositions.put(sourceFile, Lists.<SourcePosition<AliasTransformation>> newArrayList()); } observedPositions.get(sourceFile).add(position); AliasTransformation spy = new AliasSpy(); constructedAliases.add(spy); return spy; } } private static class AliasSpy implements AliasTransformation { public final Map<String, String> observedDefinitions = Maps.newHashMap(); @Override public void addAlias(String alias, String definition) { observedDefinitions.put(alias, definition); } } private static class TypeVerifyingPass implements CompilerPass, NodeTraversal.Callback { private final Compiler compiler; private List<Node> actualTypes = null; public TypeVerifyingPass(Compiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); } @Override public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) { return true; } @Override public void visit(NodeTraversal t, Node n, Node parent) { JSDocInfo info = n.getJSDocInfo(); if (info != null) { Collection<Node> typeNodes = info.getTypeNodes(); if (typeNodes.size() > 0) { if (actualTypes != null) { List<Node> expectedTypes = Lists.newArrayList(); for (Node typeNode : info.getTypeNodes()) { expectedTypes.add(typeNode); } assertEquals("Wrong number of JsDoc types", expectedTypes.size(), actualTypes.size()); for (int i = 0; i < expectedTypes.size(); i++) { assertNull( expectedTypes.get(i).checkTreeEquals(actualTypes.get(i))); } } else { actualTypes = Lists.newArrayList(); for (Node typeNode : info.getTypeNodes()) { actualTypes.add(typeNode); } } } } } } }
// You are a professional Java test case writer, please create a test case named `testNonAliasLocal` for the issue `Closure-737`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-737 // // ## Issue-Title: // goog.scope doesn't properly check declared functions // // ## Issue-Description: // The following code is a compiler error: // // goog.scope(function() { // var x = function(){}; // }); // // but the following code is not: // // goog.scope(function() { // function x() {} // }); // // Both code snippets should be a compiler error, because they prevent the goog.scope from being unboxed. // // public void testNonAliasLocal() {
414
24
404
test/com/google/javascript/jscomp/ScopedAliasesTest.java
test
```markdown ## Issue-ID: Closure-737 ## Issue-Title: goog.scope doesn't properly check declared functions ## Issue-Description: The following code is a compiler error: goog.scope(function() { var x = function(){}; }); but the following code is not: goog.scope(function() { function x() {} }); Both code snippets should be a compiler error, because they prevent the goog.scope from being unboxed. ``` You are a professional Java test case writer, please create a test case named `testNonAliasLocal` for the issue `Closure-737`, utilizing the provided issue report information and the following function signature. ```java public void testNonAliasLocal() { ```
404
[ "com.google.javascript.jscomp.ScopedAliases" ]
ea6c8479d3ab77df450f99b7bcf89cff67946a2fb9ab26443cab9e0165305b69
public void testNonAliasLocal()
// You are a professional Java test case writer, please create a test case named `testNonAliasLocal` for the issue `Closure-737`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-737 // // ## Issue-Title: // goog.scope doesn't properly check declared functions // // ## Issue-Description: // The following code is a compiler error: // // goog.scope(function() { // var x = function(){}; // }); // // but the following code is not: // // goog.scope(function() { // function x() {} // }); // // Both code snippets should be a compiler error, because they prevent the goog.scope from being unboxed. // //
Closure
/* * Copyright 2010 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.javascript.jscomp.CompilerOptions.AliasTransformation; import com.google.javascript.jscomp.CompilerOptions.AliasTransformationHandler; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SourcePosition; import java.util.Collection; import java.util.List; import java.util.Map; /** * Tests for {@link ScopedAliases} * * @author robbyw@google.com (Robby Walker) */ public class ScopedAliasesTest extends CompilerTestCase { private static final String GOOG_SCOPE_START_BLOCK = "goog.scope(function() {"; private static final String GOOG_SCOPE_END_BLOCK = "});"; private static String EXTERNS = "var window;"; AliasTransformationHandler transformationHandler = CompilerOptions.NULL_ALIAS_TRANSFORMATION_HANDLER; public ScopedAliasesTest() { super(EXTERNS); } private void testScoped(String code, String expected) { test(GOOG_SCOPE_START_BLOCK + code + GOOG_SCOPE_END_BLOCK, expected); } private void testScopedNoChanges(String aliases, String code) { testScoped(aliases + code, code); } public void testOneLevel() { testScoped("var g = goog;g.dom.createElement(g.dom.TagName.DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testTwoLevel() { testScoped("var d = goog.dom;d.createElement(d.TagName.DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testTransitive() { testScoped("var d = goog.dom;var DIV = d.TagName.DIV;d.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testTransitiveInSameVar() { testScoped("var d = goog.dom, DIV = d.TagName.DIV;d.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testMultipleTransitive() { testScoped( "var g=goog;var d=g.dom;var t=d.TagName;var DIV=t.DIV;" + "d.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testFourLevel() { testScoped("var DIV = goog.dom.TagName.DIV;goog.dom.createElement(DIV);", "goog.dom.createElement(goog.dom.TagName.DIV);"); } public void testWorksInClosures() { testScoped( "var DIV = goog.dom.TagName.DIV;" + "goog.x = function() {goog.dom.createElement(DIV);};", "goog.x = function() {goog.dom.createElement(goog.dom.TagName.DIV);};"); } public void testOverridden() { // Test that the alias doesn't get unaliased when it's overridden by a // parameter. testScopedNoChanges( "var g = goog;", "goog.x = function(g) {g.z()};"); // Same for a local. testScopedNoChanges( "var g = goog;", "goog.x = function() {var g = {}; g.z()};"); } public void testTwoScopes() { test( "goog.scope(function() {var g = goog;g.method()});" + "goog.scope(function() {g.method();});", "goog.method();g.method();"); } public void testTwoSymbolsInTwoScopes() { test( "var goog = {};" + "goog.scope(function() { var g = goog; g.Foo = function() {}; });" + "goog.scope(function() { " + " var Foo = goog.Foo; goog.bar = function() { return new Foo(); };" + "});", "var goog = {};" + "goog.Foo = function() {};" + "goog.bar = function() { return new goog.Foo(); };"); } public void testAliasOfSymbolInGoogScope() { test( "var goog = {};" + "goog.scope(function() {" + " var g = goog;" + " g.Foo = function() {};" + " var Foo = g.Foo;" + " Foo.prototype.bar = function() {};" + "});", "var goog = {}; goog.Foo = function() {};" + "goog.Foo.prototype.bar = function() {};"); } public void testScopedFunctionReturnThis() { test("goog.scope(function() { " + " var g = goog; g.f = function() { return this; };" + "});", "goog.f = function() { return this; };"); } public void testScopedFunctionAssignsToVar() { test("goog.scope(function() { " + " var g = goog; g.f = function(x) { x = 3; return x; };" + "});", "goog.f = function(x) { x = 3; return x; };"); } public void testScopedFunctionThrows() { test("goog.scope(function() { " + " var g = goog; g.f = function() { throw 'error'; };" + "});", "goog.f = function() { throw 'error'; };"); } public void testPropertiesNotChanged() { testScopedNoChanges("var x = goog.dom;", "y.x();"); } public void testShadowedVar() { test("var Popup = {};" + "var OtherPopup = {};" + "goog.scope(function() {" + " var Popup = OtherPopup;" + " Popup.newMethod = function() { return new Popup(); };" + "});", "var Popup = {};" + "var OtherPopup = {};" + "OtherPopup.newMethod = function() { return new OtherPopup(); };"); } private void testTypes(String aliases, String code) { testScopedNoChanges(aliases, code); verifyTypes(); } private void verifyTypes() { Compiler lastCompiler = getLastCompiler(); new TypeVerifyingPass(lastCompiler).process(lastCompiler.externsRoot, lastCompiler.jsRoot); } public void testJsDocType() { testTypes( "var x = goog.Timer;", "" + "/** @type {x} */ types.actual;" + "/** @type {goog.Timer} */ types.expected;"); } public void testJsDocParameter() { testTypes( "var x = goog.Timer;", "" + "/** @param {x} a */ types.actual;" + "/** @param {goog.Timer} a */ types.expected;"); } public void testJsDocExtends() { testTypes( "var x = goog.Timer;", "" + "/** @extends {x} */ types.actual;" + "/** @extends {goog.Timer} */ types.expected;"); } public void testJsDocImplements() { testTypes( "var x = goog.Timer;", "" + "/** @implements {x} */ types.actual;" + "/** @implements {goog.Timer} */ types.expected;"); } public void testJsDocEnum() { testTypes( "var x = goog.Timer;", "" + "/** @enum {x} */ types.actual;" + "/** @enum {goog.Timer} */ types.expected;"); } public void testJsDocReturn() { testTypes( "var x = goog.Timer;", "" + "/** @return {x} */ types.actual;" + "/** @return {goog.Timer} */ types.expected;"); } public void testJsDocThis() { testTypes( "var x = goog.Timer;", "" + "/** @this {x} */ types.actual;" + "/** @this {goog.Timer} */ types.expected;"); } public void testJsDocThrows() { testTypes( "var x = goog.Timer;", "" + "/** @throws {x} */ types.actual;" + "/** @throws {goog.Timer} */ types.expected;"); } public void testJsDocSubType() { testTypes( "var x = goog.Timer;", "" + "/** @type {x.Enum} */ types.actual;" + "/** @type {goog.Timer.Enum} */ types.expected;"); } public void testJsDocTypedef() { testTypes( "var x = goog.Timer;", "" + "/** @typedef {x} */ types.actual;" + "/** @typedef {goog.Timer} */ types.expected;"); } public void testArrayJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {Array.<x>} */ types.actual;" + "/** @type {Array.<goog.Timer>} */ types.expected;"); } public void testObjectJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {{someKey: x}} */ types.actual;" + "/** @type {{someKey: goog.Timer}} */ types.expected;"); testTypes( "var x = goog.Timer;", "" + "/** @type {{x: number}} */ types.actual;" + "/** @type {{x: number}} */ types.expected;"); } public void testUnionJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {x|Object} */ types.actual;" + "/** @type {goog.Timer|Object} */ types.expected;"); } public void testFunctionJsDoc() { testTypes( "var x = goog.Timer;", "" + "/** @type {function(x) : void} */ types.actual;" + "/** @type {function(goog.Timer) : void} */ types.expected;"); testTypes( "var x = goog.Timer;", "" + "/** @type {function() : x} */ types.actual;" + "/** @type {function() : goog.Timer} */ types.expected;"); } public void testForwardJsDoc() { testScoped( "/**\n" + " * @constructor\n" + " */\n" + "foo.Foo = function() {};" + "/** @param {Foo.Bar} x */ foo.Foo.actual = function(x) {3};" + "var Foo = foo.Foo;" + "/** @constructor */ Foo.Bar = function() {};" + "/** @param {foo.Foo.Bar} x */ foo.Foo.expected = function(x) {};", "/**\n" + " * @constructor\n" + " */\n" + "foo.Foo = function() {};" + "/** @param {foo.Foo.Bar} x */ foo.Foo.actual = function(x) {3};" + "/** @constructor */ foo.Foo.Bar = function() {};" + "/** @param {foo.Foo.Bar} x */ foo.Foo.expected = function(x) {};"); verifyTypes(); } public void testTestTypes() { try { testTypes( "var x = goog.Timer;", "" + "/** @type {function() : x} */ types.actual;" + "/** @type {function() : wrong.wrong} */ types.expected;"); fail("Test types should fail here."); } catch (AssertionError e) { } } public void testNullType() { testTypes( "var x = goog.Timer;", "/** @param draggable */ types.actual;" + "/** @param draggable */ types.expected;"); } // TODO(robbyw): What if it's recursive? var goog = goog.dom; // FAILURE CASES private void testFailure(String code, DiagnosticType expectedError) { test(code, null, expectedError); } private void testScopedFailure(String code, DiagnosticType expectedError) { test("goog.scope(function() {" + code + "});", null, expectedError); } public void testScopedThis() { testScopedFailure("this.y = 10;", ScopedAliases.GOOG_SCOPE_REFERENCES_THIS); testScopedFailure("var x = this;", ScopedAliases.GOOG_SCOPE_REFERENCES_THIS); testScopedFailure("fn(this);", ScopedAliases.GOOG_SCOPE_REFERENCES_THIS); } public void testAliasRedefinition() { testScopedFailure("var x = goog.dom; x = goog.events;", ScopedAliases.GOOG_SCOPE_ALIAS_REDEFINED); } public void testAliasNonRedefinition() { test("var y = {}; goog.scope(function() { goog.dom = y; });", "var y = {}; goog.dom = y;"); } public void testScopedReturn() { testScopedFailure("return;", ScopedAliases.GOOG_SCOPE_USES_RETURN); testScopedFailure("var x = goog.dom; return;", ScopedAliases.GOOG_SCOPE_USES_RETURN); } public void testScopedThrow() { testScopedFailure("throw 'error';", ScopedAliases.GOOG_SCOPE_USES_THROW); } public void testUsedImproperly() { testFailure("var x = goog.scope(function() {});", ScopedAliases.GOOG_SCOPE_USED_IMPROPERLY); } public void testBadParameters() { testFailure("goog.scope()", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(10)", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(function() {}, 10)", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(function z() {})", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); testFailure("goog.scope(function(a, b, c) {})", ScopedAliases.GOOG_SCOPE_HAS_BAD_PARAMETERS); } public void testNonAliasLocal() { testScopedFailure("var x = 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog.dom + 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog['dom']", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("var x = goog.dom, y = 10", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); testScopedFailure("function f() {}", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL); } // Alias Recording Tests // TODO(tylerg) : update these to EasyMock style tests once available public void testNoGoogScope() { String fullJsCode = "var g = goog;\n g.dom.createElement(g.dom.TagName.DIV);"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, fullJsCode); assertTrue(spy.observedPositions.isEmpty()); } public void testRecordOneAlias() { String fullJsCode = GOOG_SCOPE_START_BLOCK + "var g = goog;\n g.dom.createElement(g.dom.TagName.DIV);\n" + GOOG_SCOPE_END_BLOCK; String expectedJsCode = "goog.dom.createElement(goog.dom.TagName.DIV);\n"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, expectedJsCode); assertTrue(spy.observedPositions.containsKey("testcode")); List<SourcePosition<AliasTransformation>> positions = spy.observedPositions.get("testcode"); assertEquals(1, positions.size()); verifyAliasTransformationPosition(1, 0, 2, 1, positions.get(0)); assertEquals(1, spy.constructedAliases.size()); AliasSpy aliasSpy = (AliasSpy) spy.constructedAliases.get(0); assertEquals("goog", aliasSpy.observedDefinitions.get("g")); } public void testRecordMultipleAliases() { String fullJsCode = GOOG_SCOPE_START_BLOCK + "var g = goog;\n var b= g.bar;\n var f = goog.something.foo;" + "g.dom.createElement(g.dom.TagName.DIV);\n b.foo();" + GOOG_SCOPE_END_BLOCK; String expectedJsCode = "goog.dom.createElement(goog.dom.TagName.DIV);\n goog.bar.foo();"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, expectedJsCode); assertTrue(spy.observedPositions.containsKey("testcode")); List<SourcePosition<AliasTransformation>> positions = spy.observedPositions.get("testcode"); assertEquals(1, positions.size()); verifyAliasTransformationPosition(1, 0, 3, 1, positions.get(0)); assertEquals(1, spy.constructedAliases.size()); AliasSpy aliasSpy = (AliasSpy) spy.constructedAliases.get(0); assertEquals("goog", aliasSpy.observedDefinitions.get("g")); assertEquals("g.bar", aliasSpy.observedDefinitions.get("b")); assertEquals("goog.something.foo", aliasSpy.observedDefinitions.get("f")); } public void testRecordAliasFromMultipleGoogScope() { String firstGoogScopeBlock = GOOG_SCOPE_START_BLOCK + "\n var g = goog;\n g.dom.createElement(g.dom.TagName.DIV);\n" + GOOG_SCOPE_END_BLOCK; String fullJsCode = firstGoogScopeBlock + "\n\nvar l = abc.def;\n\n" + GOOG_SCOPE_START_BLOCK + "\n var z = namespace.Zoo;\n z.getAnimals(l);\n" + GOOG_SCOPE_END_BLOCK; String expectedJsCode = "goog.dom.createElement(goog.dom.TagName.DIV);\n" + "\n\nvar l = abc.def;\n\n" + "\n namespace.Zoo.getAnimals(l);\n"; TransformationHandlerSpy spy = new TransformationHandlerSpy(); transformationHandler = spy; test(fullJsCode, expectedJsCode); assertTrue(spy.observedPositions.containsKey("testcode")); List<SourcePosition<AliasTransformation>> positions = spy.observedPositions.get("testcode"); assertEquals(2, positions.size()); verifyAliasTransformationPosition(1, 0, 6, 0, positions.get(0)); verifyAliasTransformationPosition(8, 0, 11, 4, positions.get(1)); assertEquals(2, spy.constructedAliases.size()); AliasSpy aliasSpy = (AliasSpy) spy.constructedAliases.get(0); assertEquals("goog", aliasSpy.observedDefinitions.get("g")); aliasSpy = (AliasSpy) spy.constructedAliases.get(1); assertEquals("namespace.Zoo", aliasSpy.observedDefinitions.get("z")); } private void verifyAliasTransformationPosition(int startLine, int startChar, int endLine, int endChar, SourcePosition<AliasTransformation> pos) { assertEquals(startLine, pos.getStartLine()); assertEquals(startChar, pos.getPositionOnStartLine()); assertTrue( "expected endline >= " + endLine + ". Found " + pos.getEndLine(), pos.getEndLine() >= endLine); assertTrue("expected endChar >= " + endChar + ". Found " + pos.getPositionOnEndLine(), pos.getPositionOnEndLine() >= endChar); } @Override protected ScopedAliases getProcessor(Compiler compiler) { return new ScopedAliases(compiler, null, transformationHandler); } private static class TransformationHandlerSpy implements AliasTransformationHandler { private final Map<String, List<SourcePosition<AliasTransformation>>> observedPositions = Maps.newHashMap(); public final List<AliasTransformation> constructedAliases = Lists.newArrayList(); @Override public AliasTransformation logAliasTransformation( String sourceFile, SourcePosition<AliasTransformation> position) { if(!observedPositions.containsKey(sourceFile)) { observedPositions.put(sourceFile, Lists.<SourcePosition<AliasTransformation>> newArrayList()); } observedPositions.get(sourceFile).add(position); AliasTransformation spy = new AliasSpy(); constructedAliases.add(spy); return spy; } } private static class AliasSpy implements AliasTransformation { public final Map<String, String> observedDefinitions = Maps.newHashMap(); @Override public void addAlias(String alias, String definition) { observedDefinitions.put(alias, definition); } } private static class TypeVerifyingPass implements CompilerPass, NodeTraversal.Callback { private final Compiler compiler; private List<Node> actualTypes = null; public TypeVerifyingPass(Compiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); } @Override public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) { return true; } @Override public void visit(NodeTraversal t, Node n, Node parent) { JSDocInfo info = n.getJSDocInfo(); if (info != null) { Collection<Node> typeNodes = info.getTypeNodes(); if (typeNodes.size() > 0) { if (actualTypes != null) { List<Node> expectedTypes = Lists.newArrayList(); for (Node typeNode : info.getTypeNodes()) { expectedTypes.add(typeNode); } assertEquals("Wrong number of JsDoc types", expectedTypes.size(), actualTypes.size()); for (int i = 0; i < expectedTypes.size(); i++) { assertNull( expectedTypes.get(i).checkTreeEquals(actualTypes.get(i))); } } else { actualTypes = Lists.newArrayList(); for (Node typeNode : info.getTypeNodes()) { actualTypes.add(typeNode); } } } } } } }
public void testUselessCode() { test("function f(x) { if(x) return; }", ok); test("function f(x) { if(x); }", "function f(x) { if(x); }", e); test("if(x) x = y;", ok); test("if(x) x == bar();", "if(x) JSCOMPILER_PRESERVE(x == bar());", e); test("x = 3;", ok); test("x == 3;", "JSCOMPILER_PRESERVE(x == 3);", e); test("var x = 'test'", ok); test("var x = 'test'\n'str'", "var x = 'test'\nJSCOMPILER_PRESERVE('str')", e); test("", ok); test("foo();;;;bar();;;;", ok); test("var a, b; a = 5, b = 6", ok); test("var a, b; a = 5, b == 6", "var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)", e); test("var a, b; a = (5, 6)", "var a, b; a = (JSCOMPILER_PRESERVE(5), 6)", e); test("var a, b; a = (bar(), 6, 7)", "var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)", e); test("var a, b; a = (bar(), bar(), 7, 8)", "var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)", e); test("var a, b; a = (b = 7, 6)", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(2, 3));", "function x(){}\nfunction f(a, b){}\n" + "f(1,(JSCOMPILER_PRESERVE(2), 3));", e); }
com.google.javascript.jscomp.CheckSideEffectsTest::testUselessCode
test/com/google/javascript/jscomp/CheckSideEffectsTest.java
79
test/com/google/javascript/jscomp/CheckSideEffectsTest.java
testUselessCode
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; public class CheckSideEffectsTest extends CompilerTestCase { public CheckSideEffectsTest() { this.parseTypeInfo = true; allowExternsChanges(true); } @Override protected int getNumRepetitions() { return 1; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new CheckSideEffects(compiler, CheckLevel.WARNING, true); } @Override public void test(String js, String expected, DiagnosticType warning) { test(js, expected, null, warning); } public void test(String js, DiagnosticType warning) { test(js, js, null, warning); } final DiagnosticType e = CheckSideEffects.USELESS_CODE_ERROR; final DiagnosticType ok = null; // no warning public void testUselessCode() { test("function f(x) { if(x) return; }", ok); test("function f(x) { if(x); }", "function f(x) { if(x); }", e); test("if(x) x = y;", ok); test("if(x) x == bar();", "if(x) JSCOMPILER_PRESERVE(x == bar());", e); test("x = 3;", ok); test("x == 3;", "JSCOMPILER_PRESERVE(x == 3);", e); test("var x = 'test'", ok); test("var x = 'test'\n'str'", "var x = 'test'\nJSCOMPILER_PRESERVE('str')", e); test("", ok); test("foo();;;;bar();;;;", ok); test("var a, b; a = 5, b = 6", ok); test("var a, b; a = 5, b == 6", "var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)", e); test("var a, b; a = (5, 6)", "var a, b; a = (JSCOMPILER_PRESERVE(5), 6)", e); test("var a, b; a = (bar(), 6, 7)", "var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)", e); test("var a, b; a = (bar(), bar(), 7, 8)", "var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)", e); test("var a, b; a = (b = 7, 6)", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(2, 3));", "function x(){}\nfunction f(a, b){}\n" + "f(1,(JSCOMPILER_PRESERVE(2), 3));", e); } public void testUselessCodeInFor() { test("for(var x = 0; x < 100; x++) { foo(x) }", ok); test("for(; true; ) { bar() }", ok); test("for(foo(); true; foo()) { bar() }", ok); test("for(void 0; true; foo()) { bar() }", "for(JSCOMPILER_PRESERVE(void 0); true; foo()) { bar() }", e); test("for(foo(); true; void 0) { bar() }", "for(foo(); true; JSCOMPILER_PRESERVE(void 0)) { bar() }", e); test("for(foo(); true; (1, bar())) { bar() }", "for(foo(); true; (JSCOMPILER_PRESERVE(1), bar())) { bar() }", e); test("for(foo in bar) { foo() }", ok); test("for (i = 0; el = el.previousSibling; i++) {}", ok); test("for (i = 0; el = el.previousSibling; i++);", ok); } public void testTypeAnnotations() { test("x;", "JSCOMPILER_PRESERVE(x);", e); test("a.b.c.d;", "JSCOMPILER_PRESERVE(a.b.c.d);", e); test("/** @type Number */ a.b.c.d;", ok); test("if (true) { /** @type Number */ a.b.c.d; }", ok); test("function A() { this.foo; }", "function A() { JSCOMPILER_PRESERVE(this.foo); }", e); test("function A() { /** @type Number */ this.foo; }", ok); } public void testJSDocComments() { test("function A() { /** This is a JsDoc comment */ this.foo; }", ok); test("function A() { /* This is a normal comment */ this.foo; }", "function A() { " + " /* This is a normal comment */ JSCOMPILER_PRESERVE(this.foo); }", e); } public void testIssue80() { test("(0, eval)('alert');", ok); test("(0, foo)('alert');", "(JSCOMPILER_PRESERVE(0), foo)('alert');", e); } public void testIsue504() { test("void f();", "JSCOMPILER_PRESERVE(void f());", null, e, "Suspicious code. The result of the 'void' operator is not being used."); } }
// You are a professional Java test case writer, please create a test case named `testUselessCode` for the issue `Closure-753`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-753 // // ## Issue-Title: // Classify non-rightmost expressions as problematic // // ## Issue-Description: // **Purpose of code changes:** // When it comes to an expression involving the comma operator, only the // first element of such a sequence is checked for being free of side // effects. If the element is free of side effects, it is classified as // problematic and a warning is issued. // // As other non-rightmost elements are not checked for being free of side // effects and therefore cannot be classified as problematic, this leads // to unexpected behavior: // // 1. foo((1, 2, 42)) is transformed into foo((1, 3)) and a warning is // issued only with regard to the first element. // 2. foo((bar(), 2, 42)) is transformed into foo((bar(), 3)) and no // warning is issued. // 3. foo(((1, 2, 3), (4, 5, 42))) is transformed into foo((1, 4, 42)) and // warnings are issued with regard to the first elements of inner // sequences only. // // public void testUselessCode() {
79
final DiagnosticType ok = null; // no warning
21
48
test/com/google/javascript/jscomp/CheckSideEffectsTest.java
test
```markdown ## Issue-ID: Closure-753 ## Issue-Title: Classify non-rightmost expressions as problematic ## Issue-Description: **Purpose of code changes:** When it comes to an expression involving the comma operator, only the first element of such a sequence is checked for being free of side effects. If the element is free of side effects, it is classified as problematic and a warning is issued. As other non-rightmost elements are not checked for being free of side effects and therefore cannot be classified as problematic, this leads to unexpected behavior: 1. foo((1, 2, 42)) is transformed into foo((1, 3)) and a warning is issued only with regard to the first element. 2. foo((bar(), 2, 42)) is transformed into foo((bar(), 3)) and no warning is issued. 3. foo(((1, 2, 3), (4, 5, 42))) is transformed into foo((1, 4, 42)) and warnings are issued with regard to the first elements of inner sequences only. ``` You are a professional Java test case writer, please create a test case named `testUselessCode` for the issue `Closure-753`, utilizing the provided issue report information and the following function signature. ```java public void testUselessCode() { ```
48
[ "com.google.javascript.jscomp.CheckSideEffects" ]
eadf41bf0836bae2cc8528e908f57b4ddf5866d08583ed46cdcf0d613d307fde
public void testUselessCode()
// You are a professional Java test case writer, please create a test case named `testUselessCode` for the issue `Closure-753`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-753 // // ## Issue-Title: // Classify non-rightmost expressions as problematic // // ## Issue-Description: // **Purpose of code changes:** // When it comes to an expression involving the comma operator, only the // first element of such a sequence is checked for being free of side // effects. If the element is free of side effects, it is classified as // problematic and a warning is issued. // // As other non-rightmost elements are not checked for being free of side // effects and therefore cannot be classified as problematic, this leads // to unexpected behavior: // // 1. foo((1, 2, 42)) is transformed into foo((1, 3)) and a warning is // issued only with regard to the first element. // 2. foo((bar(), 2, 42)) is transformed into foo((bar(), 3)) and no // warning is issued. // 3. foo(((1, 2, 3), (4, 5, 42))) is transformed into foo((1, 4, 42)) and // warnings are issued with regard to the first elements of inner // sequences only. // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; public class CheckSideEffectsTest extends CompilerTestCase { public CheckSideEffectsTest() { this.parseTypeInfo = true; allowExternsChanges(true); } @Override protected int getNumRepetitions() { return 1; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new CheckSideEffects(compiler, CheckLevel.WARNING, true); } @Override public void test(String js, String expected, DiagnosticType warning) { test(js, expected, null, warning); } public void test(String js, DiagnosticType warning) { test(js, js, null, warning); } final DiagnosticType e = CheckSideEffects.USELESS_CODE_ERROR; final DiagnosticType ok = null; // no warning public void testUselessCode() { test("function f(x) { if(x) return; }", ok); test("function f(x) { if(x); }", "function f(x) { if(x); }", e); test("if(x) x = y;", ok); test("if(x) x == bar();", "if(x) JSCOMPILER_PRESERVE(x == bar());", e); test("x = 3;", ok); test("x == 3;", "JSCOMPILER_PRESERVE(x == 3);", e); test("var x = 'test'", ok); test("var x = 'test'\n'str'", "var x = 'test'\nJSCOMPILER_PRESERVE('str')", e); test("", ok); test("foo();;;;bar();;;;", ok); test("var a, b; a = 5, b = 6", ok); test("var a, b; a = 5, b == 6", "var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)", e); test("var a, b; a = (5, 6)", "var a, b; a = (JSCOMPILER_PRESERVE(5), 6)", e); test("var a, b; a = (bar(), 6, 7)", "var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)", e); test("var a, b; a = (bar(), bar(), 7, 8)", "var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)", e); test("var a, b; a = (b = 7, 6)", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));", ok); test("function x(){}\nfunction f(a, b){}\nf(1,(2, 3));", "function x(){}\nfunction f(a, b){}\n" + "f(1,(JSCOMPILER_PRESERVE(2), 3));", e); } public void testUselessCodeInFor() { test("for(var x = 0; x < 100; x++) { foo(x) }", ok); test("for(; true; ) { bar() }", ok); test("for(foo(); true; foo()) { bar() }", ok); test("for(void 0; true; foo()) { bar() }", "for(JSCOMPILER_PRESERVE(void 0); true; foo()) { bar() }", e); test("for(foo(); true; void 0) { bar() }", "for(foo(); true; JSCOMPILER_PRESERVE(void 0)) { bar() }", e); test("for(foo(); true; (1, bar())) { bar() }", "for(foo(); true; (JSCOMPILER_PRESERVE(1), bar())) { bar() }", e); test("for(foo in bar) { foo() }", ok); test("for (i = 0; el = el.previousSibling; i++) {}", ok); test("for (i = 0; el = el.previousSibling; i++);", ok); } public void testTypeAnnotations() { test("x;", "JSCOMPILER_PRESERVE(x);", e); test("a.b.c.d;", "JSCOMPILER_PRESERVE(a.b.c.d);", e); test("/** @type Number */ a.b.c.d;", ok); test("if (true) { /** @type Number */ a.b.c.d; }", ok); test("function A() { this.foo; }", "function A() { JSCOMPILER_PRESERVE(this.foo); }", e); test("function A() { /** @type Number */ this.foo; }", ok); } public void testJSDocComments() { test("function A() { /** This is a JsDoc comment */ this.foo; }", ok); test("function A() { /* This is a normal comment */ this.foo; }", "function A() { " + " /* This is a normal comment */ JSCOMPILER_PRESERVE(this.foo); }", e); } public void testIssue80() { test("(0, eval)('alert');", ok); test("(0, foo)('alert');", "(JSCOMPILER_PRESERVE(0), foo)('alert');", e); } public void testIsue504() { test("void f();", "JSCOMPILER_PRESERVE(void f());", null, e, "Suspicious code. The result of the 'void' operator is not being used."); } }
@Test public void testIssue639(){ Vector3D u1 = new Vector3D(-1321008684645961.0 / 268435456.0, -5774608829631843.0 / 268435456.0, -3822921525525679.0 / 4294967296.0); Vector3D u2 =new Vector3D( -5712344449280879.0 / 2097152.0, -2275058564560979.0 / 1048576.0, 4423475992255071.0 / 65536.0); Rotation rot = new Rotation(u1, u2, Vector3D.PLUS_I,Vector3D.PLUS_K); Assert.assertEquals( 0.6228370359608200639829222, rot.getQ0(), 1.0e-15); Assert.assertEquals( 0.0257707621456498790029987, rot.getQ1(), 1.0e-15); Assert.assertEquals(-0.0000000002503012255839931, rot.getQ2(), 1.0e-15); Assert.assertEquals(-0.7819270390861109450724902, rot.getQ3(), 1.0e-15); }
org.apache.commons.math.geometry.euclidean.threed.RotationTest::testIssue639
src/test/java/org/apache/commons/math/geometry/euclidean/threed/RotationTest.java
491
src/test/java/org/apache/commons/math/geometry/euclidean/threed/RotationTest.java
testIssue639
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.geometry.euclidean.threed; import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.MathUtils; import org.junit.Assert; import org.junit.Test; public class RotationTest { @Test public void testIdentity() { Rotation r = Rotation.IDENTITY; checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_K); checkAngle(r.getAngle(), 0); r = new Rotation(-1, 0, 0, 0, false); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_K); checkAngle(r.getAngle(), 0); r = new Rotation(42, 0, 0, 0, true); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_K); checkAngle(r.getAngle(), 0); } @Test public void testAxisAngle() { Rotation r = new Rotation(new Vector3D(10, 10, 10), 2 * FastMath.PI / 3); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_K); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_I); double s = 1 / FastMath.sqrt(3); checkVector(r.getAxis(), new Vector3D(s, s, s)); checkAngle(r.getAngle(), 2 * FastMath.PI / 3); try { new Rotation(new Vector3D(0, 0, 0), 2 * FastMath.PI / 3); Assert.fail("an exception should have been thrown"); } catch (ArithmeticException e) { } r = new Rotation(Vector3D.PLUS_K, 1.5 * FastMath.PI); checkVector(r.getAxis(), new Vector3D(0, 0, -1)); checkAngle(r.getAngle(), 0.5 * FastMath.PI); r = new Rotation(Vector3D.PLUS_J, FastMath.PI); checkVector(r.getAxis(), Vector3D.PLUS_J); checkAngle(r.getAngle(), FastMath.PI); checkVector(Rotation.IDENTITY.getAxis(), Vector3D.PLUS_I); } @Test public void testRevert() { Rotation r = new Rotation(0.001, 0.36, 0.48, 0.8, true); Rotation reverted = r.revert(); checkRotation(r.applyTo(reverted), 1, 0, 0, 0); checkRotation(reverted.applyTo(r), 1, 0, 0, 0); Assert.assertEquals(r.getAngle(), reverted.getAngle(), 1.0e-12); Assert.assertEquals(-1, Vector3D.dotProduct(r.getAxis(), reverted.getAxis()), 1.0e-12); } @Test public void testVectorOnePair() { Vector3D u = new Vector3D(3, 2, 1); Vector3D v = new Vector3D(-4, 2, 2); Rotation r = new Rotation(u, v); checkVector(r.applyTo(u.scalarMultiply(v.getNorm())), v.scalarMultiply(u.getNorm())); checkAngle(new Rotation(u, u.negate()).getAngle(), FastMath.PI); try { new Rotation(u, Vector3D.ZERO); Assert.fail("an exception should have been thrown"); } catch (IllegalArgumentException e) { // expected behavior } } @Test public void testVectorTwoPairs() { Vector3D u1 = new Vector3D(3, 0, 0); Vector3D u2 = new Vector3D(0, 5, 0); Vector3D v1 = new Vector3D(0, 0, 2); Vector3D v2 = new Vector3D(-2, 0, 2); Rotation r = new Rotation(u1, u2, v1, v2); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_K); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.MINUS_I); r = new Rotation(u1, u2, u1.negate(), u2.negate()); Vector3D axis = r.getAxis(); if (Vector3D.dotProduct(axis, Vector3D.PLUS_K) > 0) { checkVector(axis, Vector3D.PLUS_K); } else { checkVector(axis, Vector3D.MINUS_K); } checkAngle(r.getAngle(), FastMath.PI); double sqrt = FastMath.sqrt(2) / 2; r = new Rotation(Vector3D.PLUS_I, Vector3D.PLUS_J, new Vector3D(0.5, 0.5, sqrt), new Vector3D(0.5, 0.5, -sqrt)); checkRotation(r, sqrt, 0.5, 0.5, 0); r = new Rotation(u1, u2, u1, Vector3D.crossProduct(u1, u2)); checkRotation(r, sqrt, -sqrt, 0, 0); checkRotation(new Rotation(u1, u2, u1, u2), 1, 0, 0, 0); try { new Rotation(u1, u2, Vector3D.ZERO, v2); Assert.fail("an exception should have been thrown"); } catch (IllegalArgumentException e) { // expected behavior } } @Test public void testMatrix() throws NotARotationMatrixException { try { new Rotation(new double[][] { { 0.0, 1.0, 0.0 }, { 1.0, 0.0, 0.0 } }, 1.0e-7); Assert.fail("Expecting NotARotationMatrixException"); } catch (NotARotationMatrixException nrme) { // expected behavior } try { new Rotation(new double[][] { { 0.445888, 0.797184, -0.407040 }, { 0.821760, -0.184320, 0.539200 }, { -0.354816, 0.574912, 0.737280 } }, 1.0e-7); Assert.fail("Expecting NotARotationMatrixException"); } catch (NotARotationMatrixException nrme) { // expected behavior } try { new Rotation(new double[][] { { 0.4, 0.8, -0.4 }, { -0.4, 0.6, 0.7 }, { 0.8, -0.2, 0.5 } }, 1.0e-15); Assert.fail("Expecting NotARotationMatrixException"); } catch (NotARotationMatrixException nrme) { // expected behavior } checkRotation(new Rotation(new double[][] { { 0.445888, 0.797184, -0.407040 }, { -0.354816, 0.574912, 0.737280 }, { 0.821760, -0.184320, 0.539200 } }, 1.0e-10), 0.8, 0.288, 0.384, 0.36); checkRotation(new Rotation(new double[][] { { 0.539200, 0.737280, 0.407040 }, { 0.184320, -0.574912, 0.797184 }, { 0.821760, -0.354816, -0.445888 } }, 1.0e-10), 0.36, 0.8, 0.288, 0.384); checkRotation(new Rotation(new double[][] { { -0.445888, 0.797184, -0.407040 }, { 0.354816, 0.574912, 0.737280 }, { 0.821760, 0.184320, -0.539200 } }, 1.0e-10), 0.384, 0.36, 0.8, 0.288); checkRotation(new Rotation(new double[][] { { -0.539200, 0.737280, 0.407040 }, { -0.184320, -0.574912, 0.797184 }, { 0.821760, 0.354816, 0.445888 } }, 1.0e-10), 0.288, 0.384, 0.36, 0.8); double[][] m1 = { { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 1.0, 0.0, 0.0 } }; Rotation r = new Rotation(m1, 1.0e-7); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_K); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_J); double[][] m2 = { { 0.83203, -0.55012, -0.07139 }, { 0.48293, 0.78164, -0.39474 }, { 0.27296, 0.29396, 0.91602 } }; r = new Rotation(m2, 1.0e-12); double[][] m3 = r.getMatrix(); double d00 = m2[0][0] - m3[0][0]; double d01 = m2[0][1] - m3[0][1]; double d02 = m2[0][2] - m3[0][2]; double d10 = m2[1][0] - m3[1][0]; double d11 = m2[1][1] - m3[1][1]; double d12 = m2[1][2] - m3[1][2]; double d20 = m2[2][0] - m3[2][0]; double d21 = m2[2][1] - m3[2][1]; double d22 = m2[2][2] - m3[2][2]; Assert.assertTrue(FastMath.abs(d00) < 6.0e-6); Assert.assertTrue(FastMath.abs(d01) < 6.0e-6); Assert.assertTrue(FastMath.abs(d02) < 6.0e-6); Assert.assertTrue(FastMath.abs(d10) < 6.0e-6); Assert.assertTrue(FastMath.abs(d11) < 6.0e-6); Assert.assertTrue(FastMath.abs(d12) < 6.0e-6); Assert.assertTrue(FastMath.abs(d20) < 6.0e-6); Assert.assertTrue(FastMath.abs(d21) < 6.0e-6); Assert.assertTrue(FastMath.abs(d22) < 6.0e-6); Assert.assertTrue(FastMath.abs(d00) > 4.0e-7); Assert.assertTrue(FastMath.abs(d01) > 4.0e-7); Assert.assertTrue(FastMath.abs(d02) > 4.0e-7); Assert.assertTrue(FastMath.abs(d10) > 4.0e-7); Assert.assertTrue(FastMath.abs(d11) > 4.0e-7); Assert.assertTrue(FastMath.abs(d12) > 4.0e-7); Assert.assertTrue(FastMath.abs(d20) > 4.0e-7); Assert.assertTrue(FastMath.abs(d21) > 4.0e-7); Assert.assertTrue(FastMath.abs(d22) > 4.0e-7); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { double m3tm3 = m3[i][0] * m3[j][0] + m3[i][1] * m3[j][1] + m3[i][2] * m3[j][2]; if (i == j) { Assert.assertTrue(FastMath.abs(m3tm3 - 1.0) < 1.0e-10); } else { Assert.assertTrue(FastMath.abs(m3tm3) < 1.0e-10); } } } checkVector(r.applyTo(Vector3D.PLUS_I), new Vector3D(m3[0][0], m3[1][0], m3[2][0])); checkVector(r.applyTo(Vector3D.PLUS_J), new Vector3D(m3[0][1], m3[1][1], m3[2][1])); checkVector(r.applyTo(Vector3D.PLUS_K), new Vector3D(m3[0][2], m3[1][2], m3[2][2])); double[][] m4 = { { 1.0, 0.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, 0.0, -1.0 } }; r = new Rotation(m4, 1.0e-7); checkAngle(r.getAngle(), FastMath.PI); try { double[][] m5 = { { 0.0, 0.0, 1.0 }, { 0.0, 1.0, 0.0 }, { 1.0, 0.0, 0.0 } }; r = new Rotation(m5, 1.0e-7); Assert.fail("got " + r + ", should have caught an exception"); } catch (NotARotationMatrixException e) { // expected } } @Test public void testAngles() throws CardanEulerSingularityException { RotationOrder[] CardanOrders = { RotationOrder.XYZ, RotationOrder.XZY, RotationOrder.YXZ, RotationOrder.YZX, RotationOrder.ZXY, RotationOrder.ZYX }; for (int i = 0; i < CardanOrders.length; ++i) { for (double alpha1 = 0.1; alpha1 < 6.2; alpha1 += 0.3) { for (double alpha2 = -1.55; alpha2 < 1.55; alpha2 += 0.3) { for (double alpha3 = 0.1; alpha3 < 6.2; alpha3 += 0.3) { Rotation r = new Rotation(CardanOrders[i], alpha1, alpha2, alpha3); double[] angles = r.getAngles(CardanOrders[i]); checkAngle(angles[0], alpha1); checkAngle(angles[1], alpha2); checkAngle(angles[2], alpha3); } } } } RotationOrder[] EulerOrders = { RotationOrder.XYX, RotationOrder.XZX, RotationOrder.YXY, RotationOrder.YZY, RotationOrder.ZXZ, RotationOrder.ZYZ }; for (int i = 0; i < EulerOrders.length; ++i) { for (double alpha1 = 0.1; alpha1 < 6.2; alpha1 += 0.3) { for (double alpha2 = 0.05; alpha2 < 3.1; alpha2 += 0.3) { for (double alpha3 = 0.1; alpha3 < 6.2; alpha3 += 0.3) { Rotation r = new Rotation(EulerOrders[i], alpha1, alpha2, alpha3); double[] angles = r.getAngles(EulerOrders[i]); checkAngle(angles[0], alpha1); checkAngle(angles[1], alpha2); checkAngle(angles[2], alpha3); } } } } } @Test public void testSingularities() { RotationOrder[] CardanOrders = { RotationOrder.XYZ, RotationOrder.XZY, RotationOrder.YXZ, RotationOrder.YZX, RotationOrder.ZXY, RotationOrder.ZYX }; double[] singularCardanAngle = { FastMath.PI / 2, -FastMath.PI / 2 }; for (int i = 0; i < CardanOrders.length; ++i) { for (int j = 0; j < singularCardanAngle.length; ++j) { Rotation r = new Rotation(CardanOrders[i], 0.1, singularCardanAngle[j], 0.3); try { r.getAngles(CardanOrders[i]); Assert.fail("an exception should have been caught"); } catch (CardanEulerSingularityException cese) { // expected behavior } } } RotationOrder[] EulerOrders = { RotationOrder.XYX, RotationOrder.XZX, RotationOrder.YXY, RotationOrder.YZY, RotationOrder.ZXZ, RotationOrder.ZYZ }; double[] singularEulerAngle = { 0, FastMath.PI }; for (int i = 0; i < EulerOrders.length; ++i) { for (int j = 0; j < singularEulerAngle.length; ++j) { Rotation r = new Rotation(EulerOrders[i], 0.1, singularEulerAngle[j], 0.3); try { r.getAngles(EulerOrders[i]); Assert.fail("an exception should have been caught"); } catch (CardanEulerSingularityException cese) { // expected behavior } } } } @Test public void testQuaternion() { Rotation r1 = new Rotation(new Vector3D(2, -3, 5), 1.7); double n = 23.5; Rotation r2 = new Rotation(n * r1.getQ0(), n * r1.getQ1(), n * r1.getQ2(), n * r1.getQ3(), true); for (double x = -0.9; x < 0.9; x += 0.2) { for (double y = -0.9; y < 0.9; y += 0.2) { for (double z = -0.9; z < 0.9; z += 0.2) { Vector3D u = new Vector3D(x, y, z); checkVector(r2.applyTo(u), r1.applyTo(u)); } } } r1 = new Rotation( 0.288, 0.384, 0.36, 0.8, false); checkRotation(r1, -r1.getQ0(), -r1.getQ1(), -r1.getQ2(), -r1.getQ3()); } @Test public void testCompose() { Rotation r1 = new Rotation(new Vector3D(2, -3, 5), 1.7); Rotation r2 = new Rotation(new Vector3D(-1, 3, 2), 0.3); Rotation r3 = r2.applyTo(r1); for (double x = -0.9; x < 0.9; x += 0.2) { for (double y = -0.9; y < 0.9; y += 0.2) { for (double z = -0.9; z < 0.9; z += 0.2) { Vector3D u = new Vector3D(x, y, z); checkVector(r2.applyTo(r1.applyTo(u)), r3.applyTo(u)); } } } } @Test public void testComposeInverse() { Rotation r1 = new Rotation(new Vector3D(2, -3, 5), 1.7); Rotation r2 = new Rotation(new Vector3D(-1, 3, 2), 0.3); Rotation r3 = r2.applyInverseTo(r1); for (double x = -0.9; x < 0.9; x += 0.2) { for (double y = -0.9; y < 0.9; y += 0.2) { for (double z = -0.9; z < 0.9; z += 0.2) { Vector3D u = new Vector3D(x, y, z); checkVector(r2.applyInverseTo(r1.applyTo(u)), r3.applyTo(u)); } } } } @Test public void testApplyInverseTo() { Rotation r = new Rotation(new Vector3D(2, -3, 5), 1.7); for (double lambda = 0; lambda < 6.2; lambda += 0.2) { for (double phi = -1.55; phi < 1.55; phi += 0.2) { Vector3D u = new Vector3D(FastMath.cos(lambda) * FastMath.cos(phi), FastMath.sin(lambda) * FastMath.cos(phi), FastMath.sin(phi)); r.applyInverseTo(r.applyTo(u)); checkVector(u, r.applyInverseTo(r.applyTo(u))); checkVector(u, r.applyTo(r.applyInverseTo(u))); } } r = Rotation.IDENTITY; for (double lambda = 0; lambda < 6.2; lambda += 0.2) { for (double phi = -1.55; phi < 1.55; phi += 0.2) { Vector3D u = new Vector3D(FastMath.cos(lambda) * FastMath.cos(phi), FastMath.sin(lambda) * FastMath.cos(phi), FastMath.sin(phi)); checkVector(u, r.applyInverseTo(r.applyTo(u))); checkVector(u, r.applyTo(r.applyInverseTo(u))); } } r = new Rotation(Vector3D.PLUS_K, FastMath.PI); for (double lambda = 0; lambda < 6.2; lambda += 0.2) { for (double phi = -1.55; phi < 1.55; phi += 0.2) { Vector3D u = new Vector3D(FastMath.cos(lambda) * FastMath.cos(phi), FastMath.sin(lambda) * FastMath.cos(phi), FastMath.sin(phi)); checkVector(u, r.applyInverseTo(r.applyTo(u))); checkVector(u, r.applyTo(r.applyInverseTo(u))); } } } @Test public void testIssue639(){ Vector3D u1 = new Vector3D(-1321008684645961.0 / 268435456.0, -5774608829631843.0 / 268435456.0, -3822921525525679.0 / 4294967296.0); Vector3D u2 =new Vector3D( -5712344449280879.0 / 2097152.0, -2275058564560979.0 / 1048576.0, 4423475992255071.0 / 65536.0); Rotation rot = new Rotation(u1, u2, Vector3D.PLUS_I,Vector3D.PLUS_K); Assert.assertEquals( 0.6228370359608200639829222, rot.getQ0(), 1.0e-15); Assert.assertEquals( 0.0257707621456498790029987, rot.getQ1(), 1.0e-15); Assert.assertEquals(-0.0000000002503012255839931, rot.getQ2(), 1.0e-15); Assert.assertEquals(-0.7819270390861109450724902, rot.getQ3(), 1.0e-15); } private void checkVector(Vector3D v1, Vector3D v2) { Assert.assertTrue(v1.subtract(v2).getNorm() < 1.0e-10); } private void checkAngle(double a1, double a2) { Assert.assertEquals(a1, MathUtils.normalizeAngle(a2, a1), 1.0e-10); } private void checkRotation(Rotation r, double q0, double q1, double q2, double q3) { Assert.assertEquals(0, Rotation.distance(r, new Rotation(q0, q1, q2, q3, false)), 1.0e-12); } }
// You are a professional Java test case writer, please create a test case named `testIssue639` for the issue `Math-MATH-639`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-639 // // ## Issue-Title: // numerical problems in rotation creation // // ## Issue-Description: // // building a rotation from the following vector pairs leads to NaN: // // u1 = -4921140.837095533, -2.1512094250440013E7, -890093.279426377 // // u2 = -2.7238580938724895E9, -2.169664921341876E9, 6.749688708885301E10 // // v1 = 1, 0, 0 // // v2 = 0, 0, 1 // // // The constructor first changes the (v1, v2) pair into (v1', v2') ensuring the following scalar products hold: // // <v1'|v1'> == <u1|u1> // // <v2'|v2'> == <u2|u2> // // <u1 |u2> == <v1'|v2'> // // // Once the (v1', v2') pair has been computed, we compute the cross product: // // k = (v1' - u1)^(v2' - u2) // // // and the scalar product: // // c = <k | (u1^u2)> // // // By construction, c is positive or null and the quaternion axis we want to build is q = k/[2\*sqrt(c)]. // // c should be null only if some of the vectors are aligned, and this is dealt with later in the algorithm. // // // However, there are numerical problems with the vector above with the way these computations are done, as shown // // by the following comparisons, showing the result we get from our Java code and the result we get from manual // // computation with the same formulas but with enhanced precision: // // // commons math: k = 38514476.5, -84., -1168590144 // // high precision: k = 38514410.36093388..., -0.374075245201180409222711..., -1168590152.10599715208... // // // and it becomes worse when computing c because the vectors are almost orthogonal to each other, hence inducing additional cancellations. We get: // // commons math c = -1.2397173627587605E20 // // high precision: c = 558382746168463196.7079627... // // // We have lost ALL significant digits in cancellations, and even the sign is wrong! // // // // // @Test public void testIssue639() {
491
52
478
src/test/java/org/apache/commons/math/geometry/euclidean/threed/RotationTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-639 ## Issue-Title: numerical problems in rotation creation ## Issue-Description: building a rotation from the following vector pairs leads to NaN: u1 = -4921140.837095533, -2.1512094250440013E7, -890093.279426377 u2 = -2.7238580938724895E9, -2.169664921341876E9, 6.749688708885301E10 v1 = 1, 0, 0 v2 = 0, 0, 1 The constructor first changes the (v1, v2) pair into (v1', v2') ensuring the following scalar products hold: <v1'|v1'> == <u1|u1> <v2'|v2'> == <u2|u2> <u1 |u2> == <v1'|v2'> Once the (v1', v2') pair has been computed, we compute the cross product: k = (v1' - u1)^(v2' - u2) and the scalar product: c = <k | (u1^u2)> By construction, c is positive or null and the quaternion axis we want to build is q = k/[2\*sqrt(c)]. c should be null only if some of the vectors are aligned, and this is dealt with later in the algorithm. However, there are numerical problems with the vector above with the way these computations are done, as shown by the following comparisons, showing the result we get from our Java code and the result we get from manual computation with the same formulas but with enhanced precision: commons math: k = 38514476.5, -84., -1168590144 high precision: k = 38514410.36093388..., -0.374075245201180409222711..., -1168590152.10599715208... and it becomes worse when computing c because the vectors are almost orthogonal to each other, hence inducing additional cancellations. We get: commons math c = -1.2397173627587605E20 high precision: c = 558382746168463196.7079627... We have lost ALL significant digits in cancellations, and even the sign is wrong! ``` You are a professional Java test case writer, please create a test case named `testIssue639` for the issue `Math-MATH-639`, utilizing the provided issue report information and the following function signature. ```java @Test public void testIssue639() { ```
478
[ "org.apache.commons.math.geometry.euclidean.threed.Rotation" ]
ecf7ca082969563e14eaad29e15cc995af182ffb036f75f1f9a5137360916435
@Test public void testIssue639()
// You are a professional Java test case writer, please create a test case named `testIssue639` for the issue `Math-MATH-639`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-639 // // ## Issue-Title: // numerical problems in rotation creation // // ## Issue-Description: // // building a rotation from the following vector pairs leads to NaN: // // u1 = -4921140.837095533, -2.1512094250440013E7, -890093.279426377 // // u2 = -2.7238580938724895E9, -2.169664921341876E9, 6.749688708885301E10 // // v1 = 1, 0, 0 // // v2 = 0, 0, 1 // // // The constructor first changes the (v1, v2) pair into (v1', v2') ensuring the following scalar products hold: // // <v1'|v1'> == <u1|u1> // // <v2'|v2'> == <u2|u2> // // <u1 |u2> == <v1'|v2'> // // // Once the (v1', v2') pair has been computed, we compute the cross product: // // k = (v1' - u1)^(v2' - u2) // // // and the scalar product: // // c = <k | (u1^u2)> // // // By construction, c is positive or null and the quaternion axis we want to build is q = k/[2\*sqrt(c)]. // // c should be null only if some of the vectors are aligned, and this is dealt with later in the algorithm. // // // However, there are numerical problems with the vector above with the way these computations are done, as shown // // by the following comparisons, showing the result we get from our Java code and the result we get from manual // // computation with the same formulas but with enhanced precision: // // // commons math: k = 38514476.5, -84., -1168590144 // // high precision: k = 38514410.36093388..., -0.374075245201180409222711..., -1168590152.10599715208... // // // and it becomes worse when computing c because the vectors are almost orthogonal to each other, hence inducing additional cancellations. We get: // // commons math c = -1.2397173627587605E20 // // high precision: c = 558382746168463196.7079627... // // // We have lost ALL significant digits in cancellations, and even the sign is wrong! // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.geometry.euclidean.threed; import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.MathUtils; import org.junit.Assert; import org.junit.Test; public class RotationTest { @Test public void testIdentity() { Rotation r = Rotation.IDENTITY; checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_K); checkAngle(r.getAngle(), 0); r = new Rotation(-1, 0, 0, 0, false); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_K); checkAngle(r.getAngle(), 0); r = new Rotation(42, 0, 0, 0, true); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_K); checkAngle(r.getAngle(), 0); } @Test public void testAxisAngle() { Rotation r = new Rotation(new Vector3D(10, 10, 10), 2 * FastMath.PI / 3); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_J); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_K); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_I); double s = 1 / FastMath.sqrt(3); checkVector(r.getAxis(), new Vector3D(s, s, s)); checkAngle(r.getAngle(), 2 * FastMath.PI / 3); try { new Rotation(new Vector3D(0, 0, 0), 2 * FastMath.PI / 3); Assert.fail("an exception should have been thrown"); } catch (ArithmeticException e) { } r = new Rotation(Vector3D.PLUS_K, 1.5 * FastMath.PI); checkVector(r.getAxis(), new Vector3D(0, 0, -1)); checkAngle(r.getAngle(), 0.5 * FastMath.PI); r = new Rotation(Vector3D.PLUS_J, FastMath.PI); checkVector(r.getAxis(), Vector3D.PLUS_J); checkAngle(r.getAngle(), FastMath.PI); checkVector(Rotation.IDENTITY.getAxis(), Vector3D.PLUS_I); } @Test public void testRevert() { Rotation r = new Rotation(0.001, 0.36, 0.48, 0.8, true); Rotation reverted = r.revert(); checkRotation(r.applyTo(reverted), 1, 0, 0, 0); checkRotation(reverted.applyTo(r), 1, 0, 0, 0); Assert.assertEquals(r.getAngle(), reverted.getAngle(), 1.0e-12); Assert.assertEquals(-1, Vector3D.dotProduct(r.getAxis(), reverted.getAxis()), 1.0e-12); } @Test public void testVectorOnePair() { Vector3D u = new Vector3D(3, 2, 1); Vector3D v = new Vector3D(-4, 2, 2); Rotation r = new Rotation(u, v); checkVector(r.applyTo(u.scalarMultiply(v.getNorm())), v.scalarMultiply(u.getNorm())); checkAngle(new Rotation(u, u.negate()).getAngle(), FastMath.PI); try { new Rotation(u, Vector3D.ZERO); Assert.fail("an exception should have been thrown"); } catch (IllegalArgumentException e) { // expected behavior } } @Test public void testVectorTwoPairs() { Vector3D u1 = new Vector3D(3, 0, 0); Vector3D u2 = new Vector3D(0, 5, 0); Vector3D v1 = new Vector3D(0, 0, 2); Vector3D v2 = new Vector3D(-2, 0, 2); Rotation r = new Rotation(u1, u2, v1, v2); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_K); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.MINUS_I); r = new Rotation(u1, u2, u1.negate(), u2.negate()); Vector3D axis = r.getAxis(); if (Vector3D.dotProduct(axis, Vector3D.PLUS_K) > 0) { checkVector(axis, Vector3D.PLUS_K); } else { checkVector(axis, Vector3D.MINUS_K); } checkAngle(r.getAngle(), FastMath.PI); double sqrt = FastMath.sqrt(2) / 2; r = new Rotation(Vector3D.PLUS_I, Vector3D.PLUS_J, new Vector3D(0.5, 0.5, sqrt), new Vector3D(0.5, 0.5, -sqrt)); checkRotation(r, sqrt, 0.5, 0.5, 0); r = new Rotation(u1, u2, u1, Vector3D.crossProduct(u1, u2)); checkRotation(r, sqrt, -sqrt, 0, 0); checkRotation(new Rotation(u1, u2, u1, u2), 1, 0, 0, 0); try { new Rotation(u1, u2, Vector3D.ZERO, v2); Assert.fail("an exception should have been thrown"); } catch (IllegalArgumentException e) { // expected behavior } } @Test public void testMatrix() throws NotARotationMatrixException { try { new Rotation(new double[][] { { 0.0, 1.0, 0.0 }, { 1.0, 0.0, 0.0 } }, 1.0e-7); Assert.fail("Expecting NotARotationMatrixException"); } catch (NotARotationMatrixException nrme) { // expected behavior } try { new Rotation(new double[][] { { 0.445888, 0.797184, -0.407040 }, { 0.821760, -0.184320, 0.539200 }, { -0.354816, 0.574912, 0.737280 } }, 1.0e-7); Assert.fail("Expecting NotARotationMatrixException"); } catch (NotARotationMatrixException nrme) { // expected behavior } try { new Rotation(new double[][] { { 0.4, 0.8, -0.4 }, { -0.4, 0.6, 0.7 }, { 0.8, -0.2, 0.5 } }, 1.0e-15); Assert.fail("Expecting NotARotationMatrixException"); } catch (NotARotationMatrixException nrme) { // expected behavior } checkRotation(new Rotation(new double[][] { { 0.445888, 0.797184, -0.407040 }, { -0.354816, 0.574912, 0.737280 }, { 0.821760, -0.184320, 0.539200 } }, 1.0e-10), 0.8, 0.288, 0.384, 0.36); checkRotation(new Rotation(new double[][] { { 0.539200, 0.737280, 0.407040 }, { 0.184320, -0.574912, 0.797184 }, { 0.821760, -0.354816, -0.445888 } }, 1.0e-10), 0.36, 0.8, 0.288, 0.384); checkRotation(new Rotation(new double[][] { { -0.445888, 0.797184, -0.407040 }, { 0.354816, 0.574912, 0.737280 }, { 0.821760, 0.184320, -0.539200 } }, 1.0e-10), 0.384, 0.36, 0.8, 0.288); checkRotation(new Rotation(new double[][] { { -0.539200, 0.737280, 0.407040 }, { -0.184320, -0.574912, 0.797184 }, { 0.821760, 0.354816, 0.445888 } }, 1.0e-10), 0.288, 0.384, 0.36, 0.8); double[][] m1 = { { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 1.0, 0.0, 0.0 } }; Rotation r = new Rotation(m1, 1.0e-7); checkVector(r.applyTo(Vector3D.PLUS_I), Vector3D.PLUS_K); checkVector(r.applyTo(Vector3D.PLUS_J), Vector3D.PLUS_I); checkVector(r.applyTo(Vector3D.PLUS_K), Vector3D.PLUS_J); double[][] m2 = { { 0.83203, -0.55012, -0.07139 }, { 0.48293, 0.78164, -0.39474 }, { 0.27296, 0.29396, 0.91602 } }; r = new Rotation(m2, 1.0e-12); double[][] m3 = r.getMatrix(); double d00 = m2[0][0] - m3[0][0]; double d01 = m2[0][1] - m3[0][1]; double d02 = m2[0][2] - m3[0][2]; double d10 = m2[1][0] - m3[1][0]; double d11 = m2[1][1] - m3[1][1]; double d12 = m2[1][2] - m3[1][2]; double d20 = m2[2][0] - m3[2][0]; double d21 = m2[2][1] - m3[2][1]; double d22 = m2[2][2] - m3[2][2]; Assert.assertTrue(FastMath.abs(d00) < 6.0e-6); Assert.assertTrue(FastMath.abs(d01) < 6.0e-6); Assert.assertTrue(FastMath.abs(d02) < 6.0e-6); Assert.assertTrue(FastMath.abs(d10) < 6.0e-6); Assert.assertTrue(FastMath.abs(d11) < 6.0e-6); Assert.assertTrue(FastMath.abs(d12) < 6.0e-6); Assert.assertTrue(FastMath.abs(d20) < 6.0e-6); Assert.assertTrue(FastMath.abs(d21) < 6.0e-6); Assert.assertTrue(FastMath.abs(d22) < 6.0e-6); Assert.assertTrue(FastMath.abs(d00) > 4.0e-7); Assert.assertTrue(FastMath.abs(d01) > 4.0e-7); Assert.assertTrue(FastMath.abs(d02) > 4.0e-7); Assert.assertTrue(FastMath.abs(d10) > 4.0e-7); Assert.assertTrue(FastMath.abs(d11) > 4.0e-7); Assert.assertTrue(FastMath.abs(d12) > 4.0e-7); Assert.assertTrue(FastMath.abs(d20) > 4.0e-7); Assert.assertTrue(FastMath.abs(d21) > 4.0e-7); Assert.assertTrue(FastMath.abs(d22) > 4.0e-7); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { double m3tm3 = m3[i][0] * m3[j][0] + m3[i][1] * m3[j][1] + m3[i][2] * m3[j][2]; if (i == j) { Assert.assertTrue(FastMath.abs(m3tm3 - 1.0) < 1.0e-10); } else { Assert.assertTrue(FastMath.abs(m3tm3) < 1.0e-10); } } } checkVector(r.applyTo(Vector3D.PLUS_I), new Vector3D(m3[0][0], m3[1][0], m3[2][0])); checkVector(r.applyTo(Vector3D.PLUS_J), new Vector3D(m3[0][1], m3[1][1], m3[2][1])); checkVector(r.applyTo(Vector3D.PLUS_K), new Vector3D(m3[0][2], m3[1][2], m3[2][2])); double[][] m4 = { { 1.0, 0.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, 0.0, -1.0 } }; r = new Rotation(m4, 1.0e-7); checkAngle(r.getAngle(), FastMath.PI); try { double[][] m5 = { { 0.0, 0.0, 1.0 }, { 0.0, 1.0, 0.0 }, { 1.0, 0.0, 0.0 } }; r = new Rotation(m5, 1.0e-7); Assert.fail("got " + r + ", should have caught an exception"); } catch (NotARotationMatrixException e) { // expected } } @Test public void testAngles() throws CardanEulerSingularityException { RotationOrder[] CardanOrders = { RotationOrder.XYZ, RotationOrder.XZY, RotationOrder.YXZ, RotationOrder.YZX, RotationOrder.ZXY, RotationOrder.ZYX }; for (int i = 0; i < CardanOrders.length; ++i) { for (double alpha1 = 0.1; alpha1 < 6.2; alpha1 += 0.3) { for (double alpha2 = -1.55; alpha2 < 1.55; alpha2 += 0.3) { for (double alpha3 = 0.1; alpha3 < 6.2; alpha3 += 0.3) { Rotation r = new Rotation(CardanOrders[i], alpha1, alpha2, alpha3); double[] angles = r.getAngles(CardanOrders[i]); checkAngle(angles[0], alpha1); checkAngle(angles[1], alpha2); checkAngle(angles[2], alpha3); } } } } RotationOrder[] EulerOrders = { RotationOrder.XYX, RotationOrder.XZX, RotationOrder.YXY, RotationOrder.YZY, RotationOrder.ZXZ, RotationOrder.ZYZ }; for (int i = 0; i < EulerOrders.length; ++i) { for (double alpha1 = 0.1; alpha1 < 6.2; alpha1 += 0.3) { for (double alpha2 = 0.05; alpha2 < 3.1; alpha2 += 0.3) { for (double alpha3 = 0.1; alpha3 < 6.2; alpha3 += 0.3) { Rotation r = new Rotation(EulerOrders[i], alpha1, alpha2, alpha3); double[] angles = r.getAngles(EulerOrders[i]); checkAngle(angles[0], alpha1); checkAngle(angles[1], alpha2); checkAngle(angles[2], alpha3); } } } } } @Test public void testSingularities() { RotationOrder[] CardanOrders = { RotationOrder.XYZ, RotationOrder.XZY, RotationOrder.YXZ, RotationOrder.YZX, RotationOrder.ZXY, RotationOrder.ZYX }; double[] singularCardanAngle = { FastMath.PI / 2, -FastMath.PI / 2 }; for (int i = 0; i < CardanOrders.length; ++i) { for (int j = 0; j < singularCardanAngle.length; ++j) { Rotation r = new Rotation(CardanOrders[i], 0.1, singularCardanAngle[j], 0.3); try { r.getAngles(CardanOrders[i]); Assert.fail("an exception should have been caught"); } catch (CardanEulerSingularityException cese) { // expected behavior } } } RotationOrder[] EulerOrders = { RotationOrder.XYX, RotationOrder.XZX, RotationOrder.YXY, RotationOrder.YZY, RotationOrder.ZXZ, RotationOrder.ZYZ }; double[] singularEulerAngle = { 0, FastMath.PI }; for (int i = 0; i < EulerOrders.length; ++i) { for (int j = 0; j < singularEulerAngle.length; ++j) { Rotation r = new Rotation(EulerOrders[i], 0.1, singularEulerAngle[j], 0.3); try { r.getAngles(EulerOrders[i]); Assert.fail("an exception should have been caught"); } catch (CardanEulerSingularityException cese) { // expected behavior } } } } @Test public void testQuaternion() { Rotation r1 = new Rotation(new Vector3D(2, -3, 5), 1.7); double n = 23.5; Rotation r2 = new Rotation(n * r1.getQ0(), n * r1.getQ1(), n * r1.getQ2(), n * r1.getQ3(), true); for (double x = -0.9; x < 0.9; x += 0.2) { for (double y = -0.9; y < 0.9; y += 0.2) { for (double z = -0.9; z < 0.9; z += 0.2) { Vector3D u = new Vector3D(x, y, z); checkVector(r2.applyTo(u), r1.applyTo(u)); } } } r1 = new Rotation( 0.288, 0.384, 0.36, 0.8, false); checkRotation(r1, -r1.getQ0(), -r1.getQ1(), -r1.getQ2(), -r1.getQ3()); } @Test public void testCompose() { Rotation r1 = new Rotation(new Vector3D(2, -3, 5), 1.7); Rotation r2 = new Rotation(new Vector3D(-1, 3, 2), 0.3); Rotation r3 = r2.applyTo(r1); for (double x = -0.9; x < 0.9; x += 0.2) { for (double y = -0.9; y < 0.9; y += 0.2) { for (double z = -0.9; z < 0.9; z += 0.2) { Vector3D u = new Vector3D(x, y, z); checkVector(r2.applyTo(r1.applyTo(u)), r3.applyTo(u)); } } } } @Test public void testComposeInverse() { Rotation r1 = new Rotation(new Vector3D(2, -3, 5), 1.7); Rotation r2 = new Rotation(new Vector3D(-1, 3, 2), 0.3); Rotation r3 = r2.applyInverseTo(r1); for (double x = -0.9; x < 0.9; x += 0.2) { for (double y = -0.9; y < 0.9; y += 0.2) { for (double z = -0.9; z < 0.9; z += 0.2) { Vector3D u = new Vector3D(x, y, z); checkVector(r2.applyInverseTo(r1.applyTo(u)), r3.applyTo(u)); } } } } @Test public void testApplyInverseTo() { Rotation r = new Rotation(new Vector3D(2, -3, 5), 1.7); for (double lambda = 0; lambda < 6.2; lambda += 0.2) { for (double phi = -1.55; phi < 1.55; phi += 0.2) { Vector3D u = new Vector3D(FastMath.cos(lambda) * FastMath.cos(phi), FastMath.sin(lambda) * FastMath.cos(phi), FastMath.sin(phi)); r.applyInverseTo(r.applyTo(u)); checkVector(u, r.applyInverseTo(r.applyTo(u))); checkVector(u, r.applyTo(r.applyInverseTo(u))); } } r = Rotation.IDENTITY; for (double lambda = 0; lambda < 6.2; lambda += 0.2) { for (double phi = -1.55; phi < 1.55; phi += 0.2) { Vector3D u = new Vector3D(FastMath.cos(lambda) * FastMath.cos(phi), FastMath.sin(lambda) * FastMath.cos(phi), FastMath.sin(phi)); checkVector(u, r.applyInverseTo(r.applyTo(u))); checkVector(u, r.applyTo(r.applyInverseTo(u))); } } r = new Rotation(Vector3D.PLUS_K, FastMath.PI); for (double lambda = 0; lambda < 6.2; lambda += 0.2) { for (double phi = -1.55; phi < 1.55; phi += 0.2) { Vector3D u = new Vector3D(FastMath.cos(lambda) * FastMath.cos(phi), FastMath.sin(lambda) * FastMath.cos(phi), FastMath.sin(phi)); checkVector(u, r.applyInverseTo(r.applyTo(u))); checkVector(u, r.applyTo(r.applyInverseTo(u))); } } } @Test public void testIssue639(){ Vector3D u1 = new Vector3D(-1321008684645961.0 / 268435456.0, -5774608829631843.0 / 268435456.0, -3822921525525679.0 / 4294967296.0); Vector3D u2 =new Vector3D( -5712344449280879.0 / 2097152.0, -2275058564560979.0 / 1048576.0, 4423475992255071.0 / 65536.0); Rotation rot = new Rotation(u1, u2, Vector3D.PLUS_I,Vector3D.PLUS_K); Assert.assertEquals( 0.6228370359608200639829222, rot.getQ0(), 1.0e-15); Assert.assertEquals( 0.0257707621456498790029987, rot.getQ1(), 1.0e-15); Assert.assertEquals(-0.0000000002503012255839931, rot.getQ2(), 1.0e-15); Assert.assertEquals(-0.7819270390861109450724902, rot.getQ3(), 1.0e-15); } private void checkVector(Vector3D v1, Vector3D v2) { Assert.assertTrue(v1.subtract(v2).getNorm() < 1.0e-10); } private void checkAngle(double a1, double a2) { Assert.assertEquals(a1, MathUtils.normalizeAngle(a2, a1), 1.0e-10); } private void checkRotation(Rotation r, double q0, double q1, double q2, double q3) { Assert.assertEquals(0, Rotation.distance(r, new Rotation(q0, q1, q2, q3, false)), 1.0e-12); } }
@Test public void booleanAttributesAreEmptyStringValues() { Document doc = Jsoup.parse("<div hidden>"); Attributes attributes = doc.body().child(0).attributes(); assertEquals("", attributes.get("hidden")); Attribute first = attributes.iterator().next(); assertEquals("hidden", first.getKey()); assertEquals("", first.getValue()); }
org.jsoup.nodes.AttributeTest::booleanAttributesAreEmptyStringValues
src/test/java/org/jsoup/nodes/AttributeTest.java
38
src/test/java/org/jsoup/nodes/AttributeTest.java
booleanAttributesAreEmptyStringValues
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AttributeTest { @Test public void html() { Attribute attr = new Attribute("key", "value &"); assertEquals("key=\"value &amp;\"", attr.html()); assertEquals(attr.html(), attr.toString()); } @Test public void testWithSupplementaryCharacterInAttributeKeyAndValue() { String s = new String(Character.toChars(135361)); Attribute attr = new Attribute(s, "A" + s + "B"); assertEquals(s + "=\"A" + s + "B\"", attr.html()); assertEquals(attr.html(), attr.toString()); } @Test(expected = IllegalArgumentException.class) public void validatesKeysNotEmpty() { Attribute attr = new Attribute(" ", "Check"); } @Test(expected = IllegalArgumentException.class) public void validatesKeysNotEmptyViaSet() { Attribute attr = new Attribute("One", "Check"); attr.setKey(" "); } @Test public void booleanAttributesAreEmptyStringValues() { Document doc = Jsoup.parse("<div hidden>"); Attributes attributes = doc.body().child(0).attributes(); assertEquals("", attributes.get("hidden")); Attribute first = attributes.iterator().next(); assertEquals("hidden", first.getKey()); assertEquals("", first.getValue()); } }
// You are a professional Java test case writer, please create a test case named `booleanAttributesAreEmptyStringValues` for the issue `Jsoup-1065`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1065 // // ## Issue-Title: // Attribute.getValue() broken for empty attributes since 1.11.1 // // ## Issue-Description: // // ``` // Document doc = Jsoup.parse("<div hidden>"); // Attributes attributes = doc.body().child(0).attributes(); // System.out.println(String.format("Attr: '%s', value: '%s'", "hidden", // attributes.get("hidden"))); // // Attribute first = attributes.iterator().next(); // System.out.println(String.format("Attr: '%s', value: '%s'", // first.getKey(), first.getValue())); // // ``` // // Expected output, as in 1.10.x // // // // ``` // Attr: 'hidden', value: '' // Attr: 'hidden', value: '' // // ``` // // Output in 1.11.1-1.11.3: // // // // ``` // Attr: 'hidden', value: '' // Attr: 'hidden', value: 'null' // // ``` // // // @Test public void booleanAttributesAreEmptyStringValues() {
38
88
30
src/test/java/org/jsoup/nodes/AttributeTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-1065 ## Issue-Title: Attribute.getValue() broken for empty attributes since 1.11.1 ## Issue-Description: ``` Document doc = Jsoup.parse("<div hidden>"); Attributes attributes = doc.body().child(0).attributes(); System.out.println(String.format("Attr: '%s', value: '%s'", "hidden", attributes.get("hidden"))); Attribute first = attributes.iterator().next(); System.out.println(String.format("Attr: '%s', value: '%s'", first.getKey(), first.getValue())); ``` Expected output, as in 1.10.x ``` Attr: 'hidden', value: '' Attr: 'hidden', value: '' ``` Output in 1.11.1-1.11.3: ``` Attr: 'hidden', value: '' Attr: 'hidden', value: 'null' ``` ``` You are a professional Java test case writer, please create a test case named `booleanAttributesAreEmptyStringValues` for the issue `Jsoup-1065`, utilizing the provided issue report information and the following function signature. ```java @Test public void booleanAttributesAreEmptyStringValues() { ```
30
[ "org.jsoup.nodes.Attribute" ]
ed2dcd1ee20aaaae04c21a35c2042edfea14d405a3c895e308f5ffefc36b7e57
@Test public void booleanAttributesAreEmptyStringValues()
// You are a professional Java test case writer, please create a test case named `booleanAttributesAreEmptyStringValues` for the issue `Jsoup-1065`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1065 // // ## Issue-Title: // Attribute.getValue() broken for empty attributes since 1.11.1 // // ## Issue-Description: // // ``` // Document doc = Jsoup.parse("<div hidden>"); // Attributes attributes = doc.body().child(0).attributes(); // System.out.println(String.format("Attr: '%s', value: '%s'", "hidden", // attributes.get("hidden"))); // // Attribute first = attributes.iterator().next(); // System.out.println(String.format("Attr: '%s', value: '%s'", // first.getKey(), first.getValue())); // // ``` // // Expected output, as in 1.10.x // // // // ``` // Attr: 'hidden', value: '' // Attr: 'hidden', value: '' // // ``` // // Output in 1.11.1-1.11.3: // // // // ``` // Attr: 'hidden', value: '' // Attr: 'hidden', value: 'null' // // ``` // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AttributeTest { @Test public void html() { Attribute attr = new Attribute("key", "value &"); assertEquals("key=\"value &amp;\"", attr.html()); assertEquals(attr.html(), attr.toString()); } @Test public void testWithSupplementaryCharacterInAttributeKeyAndValue() { String s = new String(Character.toChars(135361)); Attribute attr = new Attribute(s, "A" + s + "B"); assertEquals(s + "=\"A" + s + "B\"", attr.html()); assertEquals(attr.html(), attr.toString()); } @Test(expected = IllegalArgumentException.class) public void validatesKeysNotEmpty() { Attribute attr = new Attribute(" ", "Check"); } @Test(expected = IllegalArgumentException.class) public void validatesKeysNotEmptyViaSet() { Attribute attr = new Attribute("One", "Check"); attr.setKey(" "); } @Test public void booleanAttributesAreEmptyStringValues() { Document doc = Jsoup.parse("<div hidden>"); Attributes attributes = doc.body().child(0).attributes(); assertEquals("", attributes.get("hidden")); Attribute first = attributes.iterator().next(); assertEquals("hidden", first.getKey()); assertEquals("", first.getValue()); } }
@Test public void mock_should_be_injected_once_and_in_the_best_matching_type() { assertSame(REFERENCE, illegalInjectionExample.mockShouldNotGoInHere); assertSame(mockedBean, illegalInjectionExample.mockShouldGoInHere); }
org.mockitousage.bugs.InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest::mock_should_be_injected_once_and_in_the_best_matching_type
test/org/mockitousage/bugs/InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest.java
34
test/org/mockitousage/bugs/InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest.java
mock_should_be_injected_once_and_in_the_best_matching_type
package org.mockitousage.bugs; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.lang.reflect.Field; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @RunWith(MockitoJUnitRunner.class) public class InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest { private static final Object REFERENCE = new Object(); @Mock private Bean mockedBean; @InjectMocks private Service illegalInjectionExample = new Service(); @Test public void just_for_information_fields_are_read_in_declaration_order_see_Service() { Field[] declaredFields = Service.class.getDeclaredFields(); assertEquals("mockShouldNotGoInHere", declaredFields[0].getName()); assertEquals("mockShouldGoInHere", declaredFields[1].getName()); } @Test public void mock_should_be_injected_once_and_in_the_best_matching_type() { assertSame(REFERENCE, illegalInjectionExample.mockShouldNotGoInHere); assertSame(mockedBean, illegalInjectionExample.mockShouldGoInHere); } public static class Bean {} public static class Service { public final Object mockShouldNotGoInHere = REFERENCE; public Bean mockShouldGoInHere; } }
// You are a professional Java test case writer, please create a test case named `mock_should_be_injected_once_and_in_the_best_matching_type` for the issue `Mockito-236`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-236 // // ## Issue-Title: // nicer textual printing of typed parameters // // ## Issue-Description: // When matchers fail but yield the same toString(), Mockito prints extra type information. However, the type information is awkwardly printed for Strings. I've encountered this issue while working on removing hard dependency to hamcrest. // // // // ``` // //current: // someMethod(1, (Integer) 2); // someOther(1, "(String) 2"); // //desired: // someOther(1, (String) "2"); // // ``` // // // @Test public void mock_should_be_injected_once_and_in_the_best_matching_type() {
34
28
30
test/org/mockitousage/bugs/InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest.java
test
```markdown ## Issue-ID: Mockito-236 ## Issue-Title: nicer textual printing of typed parameters ## Issue-Description: When matchers fail but yield the same toString(), Mockito prints extra type information. However, the type information is awkwardly printed for Strings. I've encountered this issue while working on removing hard dependency to hamcrest. ``` //current: someMethod(1, (Integer) 2); someOther(1, "(String) 2"); //desired: someOther(1, (String) "2"); ``` ``` You are a professional Java test case writer, please create a test case named `mock_should_be_injected_once_and_in_the_best_matching_type` for the issue `Mockito-236`, utilizing the provided issue report information and the following function signature. ```java @Test public void mock_should_be_injected_once_and_in_the_best_matching_type() { ```
30
[ "org.mockito.internal.configuration.DefaultInjectionEngine" ]
ed59e20baeac60d029f56fb10b5b941cbe08c8d5daa7ef45ac3daad0ac62d942
@Test public void mock_should_be_injected_once_and_in_the_best_matching_type()
// You are a professional Java test case writer, please create a test case named `mock_should_be_injected_once_and_in_the_best_matching_type` for the issue `Mockito-236`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-236 // // ## Issue-Title: // nicer textual printing of typed parameters // // ## Issue-Description: // When matchers fail but yield the same toString(), Mockito prints extra type information. However, the type information is awkwardly printed for Strings. I've encountered this issue while working on removing hard dependency to hamcrest. // // // // ``` // //current: // someMethod(1, (Integer) 2); // someOther(1, "(String) 2"); // //desired: // someOther(1, (String) "2"); // // ``` // // //
Mockito
package org.mockitousage.bugs; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.lang.reflect.Field; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @RunWith(MockitoJUnitRunner.class) public class InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest { private static final Object REFERENCE = new Object(); @Mock private Bean mockedBean; @InjectMocks private Service illegalInjectionExample = new Service(); @Test public void just_for_information_fields_are_read_in_declaration_order_see_Service() { Field[] declaredFields = Service.class.getDeclaredFields(); assertEquals("mockShouldNotGoInHere", declaredFields[0].getName()); assertEquals("mockShouldGoInHere", declaredFields[1].getName()); } @Test public void mock_should_be_injected_once_and_in_the_best_matching_type() { assertSame(REFERENCE, illegalInjectionExample.mockShouldNotGoInHere); assertSame(mockedBean, illegalInjectionExample.mockShouldGoInHere); } public static class Bean {} public static class Service { public final Object mockShouldNotGoInHere = REFERENCE; public Bean mockShouldGoInHere; } }
@Test public void skipUsingRead() throws Exception { skip(new StreamWrapper() { public InputStream wrap(InputStream toWrap) { return new FilterInputStream(toWrap) { public long skip(long s) { return 0; } }; } }); }
org.apache.commons.compress.utils.IOUtilsTest::skipUsingRead
src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java
53
src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java
skipUsingRead
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.compress.utils; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class IOUtilsTest { private interface StreamWrapper { InputStream wrap(InputStream toWrap); } @Test public void skipUsingSkip() throws Exception { skip(new StreamWrapper() { public InputStream wrap(InputStream toWrap) { return toWrap; } }); } @Test public void skipUsingRead() throws Exception { skip(new StreamWrapper() { public InputStream wrap(InputStream toWrap) { return new FilterInputStream(toWrap) { public long skip(long s) { return 0; } }; } }); } @Test public void skipUsingSkipAndRead() throws Exception { skip(new StreamWrapper() { public InputStream wrap(final InputStream toWrap) { return new FilterInputStream(toWrap) { boolean skipped; public long skip(long s) throws IOException { if (!skipped) { toWrap.skip(5); skipped = true; return 5; } return 0; } }; } }); } private void skip(StreamWrapper wrapper) throws Exception { ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); InputStream sut = wrapper.wrap(in); Assert.assertEquals(10, IOUtils.skip(sut, 10)); Assert.assertEquals(11, sut.read()); } }
// You are a professional Java test case writer, please create a test case named `skipUsingRead` for the issue `Compress-COMPRESS-277`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-277 // // ## Issue-Title: // IOUtils.skip does not work as advertised // // ## Issue-Description: // // I am trying to feed a TarInputStream from a CipherInputStream. // // It does not work, because IOUtils.skip() does not adhere to the contract it claims in javadoc: // // // " \* <p>This method will only skip less than the requested number of // // // * bytes if the end of the input stream has been reached.</p>" // // // However it does: // // // long skipped = input.skip(numToSkip); // // if (skipped == 0) // // // { // break; // } // // And the input stream javadoc says: // // // " \* This may result from any of a number of conditions; reaching end of file // // // * before <code>n</code> bytes have been skipped is only one possibility." // // // In the case of CipherInputStream, it stops at the end of each byte buffer. // // // If you check the IOUtils from colleagues at commons-io, they have considered this case in IOUtils.skip() where they use a read to skip through the stream. // // An optimized version could combine trying to skip, then read then trying to skip again. // // // // // @Test public void skipUsingRead() throws Exception {
53
26
42
src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-277 ## Issue-Title: IOUtils.skip does not work as advertised ## Issue-Description: I am trying to feed a TarInputStream from a CipherInputStream. It does not work, because IOUtils.skip() does not adhere to the contract it claims in javadoc: " \* <p>This method will only skip less than the requested number of * bytes if the end of the input stream has been reached.</p>" However it does: long skipped = input.skip(numToSkip); if (skipped == 0) { break; } And the input stream javadoc says: " \* This may result from any of a number of conditions; reaching end of file * before <code>n</code> bytes have been skipped is only one possibility." In the case of CipherInputStream, it stops at the end of each byte buffer. If you check the IOUtils from colleagues at commons-io, they have considered this case in IOUtils.skip() where they use a read to skip through the stream. An optimized version could combine trying to skip, then read then trying to skip again. ``` You are a professional Java test case writer, please create a test case named `skipUsingRead` for the issue `Compress-COMPRESS-277`, utilizing the provided issue report information and the following function signature. ```java @Test public void skipUsingRead() throws Exception { ```
42
[ "org.apache.commons.compress.utils.IOUtils" ]
ee0fdea5bbbb50bfa8f3cfb14be68751809d23906bb97d423e5855d45a161fb1
@Test public void skipUsingRead() throws Exception
// You are a professional Java test case writer, please create a test case named `skipUsingRead` for the issue `Compress-COMPRESS-277`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-277 // // ## Issue-Title: // IOUtils.skip does not work as advertised // // ## Issue-Description: // // I am trying to feed a TarInputStream from a CipherInputStream. // // It does not work, because IOUtils.skip() does not adhere to the contract it claims in javadoc: // // // " \* <p>This method will only skip less than the requested number of // // // * bytes if the end of the input stream has been reached.</p>" // // // However it does: // // // long skipped = input.skip(numToSkip); // // if (skipped == 0) // // // { // break; // } // // And the input stream javadoc says: // // // " \* This may result from any of a number of conditions; reaching end of file // // // * before <code>n</code> bytes have been skipped is only one possibility." // // // In the case of CipherInputStream, it stops at the end of each byte buffer. // // // If you check the IOUtils from colleagues at commons-io, they have considered this case in IOUtils.skip() where they use a read to skip through the stream. // // An optimized version could combine trying to skip, then read then trying to skip again. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.compress.utils; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.InputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class IOUtilsTest { private interface StreamWrapper { InputStream wrap(InputStream toWrap); } @Test public void skipUsingSkip() throws Exception { skip(new StreamWrapper() { public InputStream wrap(InputStream toWrap) { return toWrap; } }); } @Test public void skipUsingRead() throws Exception { skip(new StreamWrapper() { public InputStream wrap(InputStream toWrap) { return new FilterInputStream(toWrap) { public long skip(long s) { return 0; } }; } }); } @Test public void skipUsingSkipAndRead() throws Exception { skip(new StreamWrapper() { public InputStream wrap(final InputStream toWrap) { return new FilterInputStream(toWrap) { boolean skipped; public long skip(long s) throws IOException { if (!skipped) { toWrap.skip(5); skipped = true; return 5; } return 0; } }; } }); } private void skip(StreamWrapper wrapper) throws Exception { ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); InputStream sut = wrapper.wrap(in); Assert.assertEquals(10, IOUtils.skip(sut, 10)); Assert.assertEquals(11, sut.read()); } }
public void testLang720() { String input = new StringBuilder("\ud842\udfb7").append("A").toString(); String escaped = StringEscapeUtils.escapeXml(input); assertEquals(input, escaped); }
org.apache.commons.lang3.StringEscapeUtilsTest::testLang720
src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
431
src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
testLang720
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests for {@link StringEscapeUtils}. * * @version $Id$ */ public class StringEscapeUtilsTest extends TestCase { private final static String FOO = "foo"; public StringEscapeUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new StringEscapeUtils()); Constructor<?>[] cons = StringEscapeUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(StringEscapeUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(StringEscapeUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testEscapeJava() throws IOException { assertEquals(null, StringEscapeUtils.escapeJava(null)); try { StringEscapeUtils.ESCAPE_JAVA.translate(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.ESCAPE_JAVA.translate("", null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEscapeJava("empty string", "", ""); assertEscapeJava(FOO, FOO); assertEscapeJava("tab", "\\t", "\t"); assertEscapeJava("backslash", "\\\\", "\\"); assertEscapeJava("single quote should not be escaped", "'", "'"); assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r"); assertEscapeJava("\\u1234", "\u1234"); assertEscapeJava("\\u0234", "\u0234"); assertEscapeJava("\\u00EF", "\u00ef"); assertEscapeJava("\\u0001", "\u0001"); assertEscapeJava("Should use capitalized unicode hex", "\\uABCD", "\uabcd"); assertEscapeJava("He didn't say, \\\"stop!\\\"", "He didn't say, \"stop!\""); assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0"); assertEscapeJava("\\uABCD\\u1234\\u012C", "\uABCD\u1234\u012C"); } /** * https://issues.apache.org/jira/browse/LANG-421 */ public void testEscapeJavaWithSlash() { final String input = "String with a slash (/) in it"; final String expected = input; final String actual = StringEscapeUtils.escapeJava(input); /** * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * in a Java string. */ assertEquals(expected, actual); } private void assertEscapeJava(String escaped, String original) throws IOException { assertEscapeJava(null, escaped, original); } private void assertEscapeJava(String message, String expected, String original) throws IOException { String converted = StringEscapeUtils.escapeJava(original); message = "escapeJava(String) failed" + (message == null ? "" : (": " + message)); assertEquals(message, expected, converted); StringWriter writer = new StringWriter(); StringEscapeUtils.ESCAPE_JAVA.translate(original, writer); assertEquals(expected, writer.toString()); } public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.UNESCAPE_JAVA.translate(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.UNESCAPE_JAVA.translate("", null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava("\\u02-3"); fail(); } catch (RuntimeException ex) { } assertUnescapeJava("", ""); assertUnescapeJava("test", "test"); assertUnescapeJava("\ntest\b", "\\ntest\\b"); assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); assertUnescapeJava("", "\\"); //foo assertUnescapeJava("lowercase unicode", "\uABCDx", "\\uabcdx"); assertUnescapeJava("uppercase unicode", "\uABCDx", "\\uABCDx"); assertUnescapeJava("unicode as final character", "\uABCD", "\\uabcd"); } private void assertUnescapeJava(String unescaped, String original) throws IOException { assertUnescapeJava(null, unescaped, original); } private void assertUnescapeJava(String message, String unescaped, String original) throws IOException { String expected = unescaped; String actual = StringEscapeUtils.unescapeJava(original); assertEquals("unescape(String) failed" + (message == null ? "" : (": " + message)) + ": expected '" + StringEscapeUtils.escapeJava(expected) + // we escape this so we can see it in the error message "' actual '" + StringEscapeUtils.escapeJava(actual) + "'", expected, actual); StringWriter writer = new StringWriter(); StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer); assertEquals(unescaped, writer.toString()); } public void testEscapeEcmaScript() { assertEquals(null, StringEscapeUtils.escapeEcmaScript(null)); try { StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeEcmaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeEcmaScript("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';")); } // HTML and XML //-------------------------------------------------------------- String[][] htmlEscapes = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, }; public void testEscapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][1]; String original = htmlEscapes[i][2]; assertEquals(message, expected, StringEscapeUtils.escapeHtml4(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.ESCAPE_HTML4.translate(original, sw); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } public void testUnescapeHtml4() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][2]; String original = htmlEscapes[i][1]; assertEquals(message, expected, StringEscapeUtils.unescapeHtml4(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } // \u00E7 is a cedilla (c with wiggle under) // note that the test string must be 7-bit-clean (unicode escaped) or else it will compile incorrectly // on some locales assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml4("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml4("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml4("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml4("Hello&##;World")); } public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("&#x80;&#x9F;")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("&#X80;&#X9F;")); // Test all Character values: for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { Character c1 = new Character(i); Character c2 = new Character((char)(i+1)); String expected = c1.toString() + c2.toString(); String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";"; String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";"; assertEquals("hex number unescape index " + (int)i, expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2)); } } public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml4("&zzzz;")); } public void testEscapeHtmlVersions() throws Exception { assertEquals("&Beta;", StringEscapeUtils.escapeHtml4("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml4("&Beta;")); // TODO: refine API for escaping/unescaping specific HTML versions } public void testEscapeXml() throws Exception { assertEquals("&lt;abc&gt;", StringEscapeUtils.escapeXml("<abc>")); assertEquals("<abc>", StringEscapeUtils.unescapeXml("&lt;abc&gt;")); assertEquals("XML should not escape >0x7f values", "\u00A1", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should be able to unescape >0x7f values", "\u00A0", StringEscapeUtils.unescapeXml("&#160;")); assertEquals("ain't", StringEscapeUtils.unescapeXml("ain&apos;t")); assertEquals("ain&apos;t", StringEscapeUtils.escapeXml("ain't")); assertEquals("", StringEscapeUtils.escapeXml("")); assertEquals(null, StringEscapeUtils.escapeXml(null)); assertEquals(null, StringEscapeUtils.unescapeXml(null)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.ESCAPE_XML.translate("<abc>", sw); } catch (IOException e) { } assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.UNESCAPE_XML.translate("&lt;abc&gt;", sw); } catch (IOException e) { } assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() ); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 public void testStandaloneAmphersand() { assertEquals("<P&O>", StringEscapeUtils.unescapeHtml4("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeHtml4("test & &lt;")); assertEquals("<P&O>", StringEscapeUtils.unescapeXml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & &lt;")); } public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml4("& &amp;")); } public void testEscapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); assertEquals("", StringEscapeUtils.escapeCsv("")); assertEquals(null, StringEscapeUtils.escapeCsv(null)); } public void testEscapeCsvWriter() throws Exception { checkCsvEscapeWriter("foo.bar", "foo.bar"); checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); checkCsvEscapeWriter("", null); checkCsvEscapeWriter("", ""); } private void checkCsvEscapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.ESCAPE_CSV.translate(value, writer); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } public void testUnescapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); assertEquals("", StringEscapeUtils.unescapeCsv("")); assertEquals(null, StringEscapeUtils.unescapeCsv(null)); assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); } public void testUnescapeCsvWriter() throws Exception { checkCsvUnescapeWriter("foo.bar", "foo.bar"); checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); checkCsvUnescapeWriter("", null); checkCsvUnescapeWriter("", ""); checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); } private void checkCsvUnescapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.UNESCAPE_CSV.translate(value, writer); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } // https://issues.apache.org/jira/browse/LANG-480 public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in unicode // codepoint: U+1D362 byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }; String original = new String(data, "UTF8"); String escaped = StringEscapeUtils.escapeHtml4( original ); assertEquals( "High unicode should not have been escaped", original, escaped); String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); assertEquals( "High unicode should have been unchanged", original, unescaped); // TODO: I think this should hold, needs further investigation // String unescapedFromEntity = StringEscapeUtils.unescapeHtml4( "&#119650;" ); // assertEquals( "High unicode should have been unescaped", original, unescapedFromEntity); } // https://issues.apache.org/jira/browse/LANG-339 public void testEscapeHiragana() { // Some random Japanese unicode characters String original = "\u304B\u304C\u3068"; String escaped = StringEscapeUtils.escapeHtml4(original); assertEquals( "Hiragana character unicode behaviour should not be being escaped by escapeHtml4", original, escaped); String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); assertEquals( "Hiragana character unicode behaviour has changed - expected no unescaping", escaped, unescaped); } // https://issues.apache.org/jira/browse/LANG-720 public void testLang720() { String input = new StringBuilder("\ud842\udfb7").append("A").toString(); String escaped = StringEscapeUtils.escapeXml(input); assertEquals(input, escaped); } }
// You are a professional Java test case writer, please create a test case named `testLang720` for the issue `Lang-LANG-720`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-720 // // ## Issue-Title: // StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. // // ## Issue-Description: // // Hello. // // // I use StringEscapeUtils.escapeXml(input) to escape special characters for XML. // // This method outputs wrong results when input contains characters in Supplementary Planes. // // // String str1 = "\uD842\uDFB7" + "A"; // // String str2 = StringEscapeUtils.escapeXml(str1); // // // // The value of str2 must be equal to the one of str1, // // // because str1 does not contain characters to be escaped. // // // However, str2 is diffrent from str1. // // // System.out.println(URLEncoder.encode(str1, "UTF-16BE")); //%D8%42%DF%B7A // // System.out.println(URLEncoder.encode(str2, "UTF-16BE")); //%D8%42%DF%B7%FF%FD // // // The cause of this problem is that the loop to translate input character by character is wrong. // // In CharSequenceTranslator.translate(CharSequence input, Writer out), // // loop counter "i" moves from 0 to Character.codePointCount(input, 0, input.length()), // // but it should move from 0 to input.length(). // // // // // public void testLang720() {
431
// https://issues.apache.org/jira/browse/LANG-720
17
427
src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-720 ## Issue-Title: StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. ## Issue-Description: Hello. I use StringEscapeUtils.escapeXml(input) to escape special characters for XML. This method outputs wrong results when input contains characters in Supplementary Planes. String str1 = "\uD842\uDFB7" + "A"; String str2 = StringEscapeUtils.escapeXml(str1); // The value of str2 must be equal to the one of str1, // because str1 does not contain characters to be escaped. // However, str2 is diffrent from str1. System.out.println(URLEncoder.encode(str1, "UTF-16BE")); //%D8%42%DF%B7A System.out.println(URLEncoder.encode(str2, "UTF-16BE")); //%D8%42%DF%B7%FF%FD The cause of this problem is that the loop to translate input character by character is wrong. In CharSequenceTranslator.translate(CharSequence input, Writer out), loop counter "i" moves from 0 to Character.codePointCount(input, 0, input.length()), but it should move from 0 to input.length(). ``` You are a professional Java test case writer, please create a test case named `testLang720` for the issue `Lang-LANG-720`, utilizing the provided issue report information and the following function signature. ```java public void testLang720() { ```
427
[ "org.apache.commons.lang3.text.translate.CharSequenceTranslator" ]
ee15e17485b0bf65b578a8097d9af5ad29ee6691945fdc7b766d4fb71dde26d5
public void testLang720()
// You are a professional Java test case writer, please create a test case named `testLang720` for the issue `Lang-LANG-720`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-720 // // ## Issue-Title: // StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. // // ## Issue-Description: // // Hello. // // // I use StringEscapeUtils.escapeXml(input) to escape special characters for XML. // // This method outputs wrong results when input contains characters in Supplementary Planes. // // // String str1 = "\uD842\uDFB7" + "A"; // // String str2 = StringEscapeUtils.escapeXml(str1); // // // // The value of str2 must be equal to the one of str1, // // // because str1 does not contain characters to be escaped. // // // However, str2 is diffrent from str1. // // // System.out.println(URLEncoder.encode(str1, "UTF-16BE")); //%D8%42%DF%B7A // // System.out.println(URLEncoder.encode(str2, "UTF-16BE")); //%D8%42%DF%B7%FF%FD // // // The cause of this problem is that the loop to translate input character by character is wrong. // // In CharSequenceTranslator.translate(CharSequence input, Writer out), // // loop counter "i" moves from 0 to Character.codePointCount(input, 0, input.length()), // // but it should move from 0 to input.length(). // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests for {@link StringEscapeUtils}. * * @version $Id$ */ public class StringEscapeUtilsTest extends TestCase { private final static String FOO = "foo"; public StringEscapeUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new StringEscapeUtils()); Constructor<?>[] cons = StringEscapeUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(StringEscapeUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(StringEscapeUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testEscapeJava() throws IOException { assertEquals(null, StringEscapeUtils.escapeJava(null)); try { StringEscapeUtils.ESCAPE_JAVA.translate(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.ESCAPE_JAVA.translate("", null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEscapeJava("empty string", "", ""); assertEscapeJava(FOO, FOO); assertEscapeJava("tab", "\\t", "\t"); assertEscapeJava("backslash", "\\\\", "\\"); assertEscapeJava("single quote should not be escaped", "'", "'"); assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r"); assertEscapeJava("\\u1234", "\u1234"); assertEscapeJava("\\u0234", "\u0234"); assertEscapeJava("\\u00EF", "\u00ef"); assertEscapeJava("\\u0001", "\u0001"); assertEscapeJava("Should use capitalized unicode hex", "\\uABCD", "\uabcd"); assertEscapeJava("He didn't say, \\\"stop!\\\"", "He didn't say, \"stop!\""); assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0"); assertEscapeJava("\\uABCD\\u1234\\u012C", "\uABCD\u1234\u012C"); } /** * https://issues.apache.org/jira/browse/LANG-421 */ public void testEscapeJavaWithSlash() { final String input = "String with a slash (/) in it"; final String expected = input; final String actual = StringEscapeUtils.escapeJava(input); /** * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * in a Java string. */ assertEquals(expected, actual); } private void assertEscapeJava(String escaped, String original) throws IOException { assertEscapeJava(null, escaped, original); } private void assertEscapeJava(String message, String expected, String original) throws IOException { String converted = StringEscapeUtils.escapeJava(original); message = "escapeJava(String) failed" + (message == null ? "" : (": " + message)); assertEquals(message, expected, converted); StringWriter writer = new StringWriter(); StringEscapeUtils.ESCAPE_JAVA.translate(original, writer); assertEquals(expected, writer.toString()); } public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.UNESCAPE_JAVA.translate(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.UNESCAPE_JAVA.translate("", null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava("\\u02-3"); fail(); } catch (RuntimeException ex) { } assertUnescapeJava("", ""); assertUnescapeJava("test", "test"); assertUnescapeJava("\ntest\b", "\\ntest\\b"); assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); assertUnescapeJava("", "\\"); //foo assertUnescapeJava("lowercase unicode", "\uABCDx", "\\uabcdx"); assertUnescapeJava("uppercase unicode", "\uABCDx", "\\uABCDx"); assertUnescapeJava("unicode as final character", "\uABCD", "\\uabcd"); } private void assertUnescapeJava(String unescaped, String original) throws IOException { assertUnescapeJava(null, unescaped, original); } private void assertUnescapeJava(String message, String unescaped, String original) throws IOException { String expected = unescaped; String actual = StringEscapeUtils.unescapeJava(original); assertEquals("unescape(String) failed" + (message == null ? "" : (": " + message)) + ": expected '" + StringEscapeUtils.escapeJava(expected) + // we escape this so we can see it in the error message "' actual '" + StringEscapeUtils.escapeJava(actual) + "'", expected, actual); StringWriter writer = new StringWriter(); StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer); assertEquals(unescaped, writer.toString()); } public void testEscapeEcmaScript() { assertEquals(null, StringEscapeUtils.escapeEcmaScript(null)); try { StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeEcmaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeEcmaScript("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';")); } // HTML and XML //-------------------------------------------------------------- String[][] htmlEscapes = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, }; public void testEscapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][1]; String original = htmlEscapes[i][2]; assertEquals(message, expected, StringEscapeUtils.escapeHtml4(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.ESCAPE_HTML4.translate(original, sw); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } public void testUnescapeHtml4() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][2]; String original = htmlEscapes[i][1]; assertEquals(message, expected, StringEscapeUtils.unescapeHtml4(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } // \u00E7 is a cedilla (c with wiggle under) // note that the test string must be 7-bit-clean (unicode escaped) or else it will compile incorrectly // on some locales assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml4("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml4("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml4("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml4("Hello&##;World")); } public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("&#x80;&#x9F;")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("&#X80;&#X9F;")); // Test all Character values: for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { Character c1 = new Character(i); Character c2 = new Character((char)(i+1)); String expected = c1.toString() + c2.toString(); String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";"; String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";"; assertEquals("hex number unescape index " + (int)i, expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2)); } } public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml4("&zzzz;")); } public void testEscapeHtmlVersions() throws Exception { assertEquals("&Beta;", StringEscapeUtils.escapeHtml4("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml4("&Beta;")); // TODO: refine API for escaping/unescaping specific HTML versions } public void testEscapeXml() throws Exception { assertEquals("&lt;abc&gt;", StringEscapeUtils.escapeXml("<abc>")); assertEquals("<abc>", StringEscapeUtils.unescapeXml("&lt;abc&gt;")); assertEquals("XML should not escape >0x7f values", "\u00A1", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should be able to unescape >0x7f values", "\u00A0", StringEscapeUtils.unescapeXml("&#160;")); assertEquals("ain't", StringEscapeUtils.unescapeXml("ain&apos;t")); assertEquals("ain&apos;t", StringEscapeUtils.escapeXml("ain't")); assertEquals("", StringEscapeUtils.escapeXml("")); assertEquals(null, StringEscapeUtils.escapeXml(null)); assertEquals(null, StringEscapeUtils.unescapeXml(null)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.ESCAPE_XML.translate("<abc>", sw); } catch (IOException e) { } assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.UNESCAPE_XML.translate("&lt;abc&gt;", sw); } catch (IOException e) { } assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() ); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 public void testStandaloneAmphersand() { assertEquals("<P&O>", StringEscapeUtils.unescapeHtml4("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeHtml4("test & &lt;")); assertEquals("<P&O>", StringEscapeUtils.unescapeXml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & &lt;")); } public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml4("& &amp;")); } public void testEscapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); assertEquals("", StringEscapeUtils.escapeCsv("")); assertEquals(null, StringEscapeUtils.escapeCsv(null)); } public void testEscapeCsvWriter() throws Exception { checkCsvEscapeWriter("foo.bar", "foo.bar"); checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); checkCsvEscapeWriter("", null); checkCsvEscapeWriter("", ""); } private void checkCsvEscapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.ESCAPE_CSV.translate(value, writer); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } public void testUnescapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); assertEquals("", StringEscapeUtils.unescapeCsv("")); assertEquals(null, StringEscapeUtils.unescapeCsv(null)); assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); } public void testUnescapeCsvWriter() throws Exception { checkCsvUnescapeWriter("foo.bar", "foo.bar"); checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); checkCsvUnescapeWriter("", null); checkCsvUnescapeWriter("", ""); checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); } private void checkCsvUnescapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.UNESCAPE_CSV.translate(value, writer); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } // https://issues.apache.org/jira/browse/LANG-480 public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in unicode // codepoint: U+1D362 byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }; String original = new String(data, "UTF8"); String escaped = StringEscapeUtils.escapeHtml4( original ); assertEquals( "High unicode should not have been escaped", original, escaped); String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); assertEquals( "High unicode should have been unchanged", original, unescaped); // TODO: I think this should hold, needs further investigation // String unescapedFromEntity = StringEscapeUtils.unescapeHtml4( "&#119650;" ); // assertEquals( "High unicode should have been unescaped", original, unescapedFromEntity); } // https://issues.apache.org/jira/browse/LANG-339 public void testEscapeHiragana() { // Some random Japanese unicode characters String original = "\u304B\u304C\u3068"; String escaped = StringEscapeUtils.escapeHtml4(original); assertEquals( "Hiragana character unicode behaviour should not be being escaped by escapeHtml4", original, escaped); String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); assertEquals( "Hiragana character unicode behaviour has changed - expected no unescaping", escaped, unescaped); } // https://issues.apache.org/jira/browse/LANG-720 public void testLang720() { String input = new StringBuilder("\ud842\udfb7").append("A").toString(); String escaped = StringEscapeUtils.escapeXml(input); assertEquals(input, escaped); } }
public void testPValueNearZero() throws Exception { /* * Create a dataset that has r -> 1, p -> 0 as dimension increases. * Prior to the fix for MATH-371, p vanished for dimension >= 14. * Post fix, p-values diminish smoothly, vanishing at dimension = 127. * Tested value is ~1E-303. */ int dimension = 120; double[][] data = new double[dimension][2]; for (int i = 0; i < dimension; i++) { data[i][0] = i; data[i][1] = i + 1/((double)i + 1); } PearsonsCorrelation corrInstance = new PearsonsCorrelation(data); assertTrue(corrInstance.getCorrelationPValues().getEntry(0, 1) > 0); }
org.apache.commons.math.stat.correlation.PearsonsCorrelationTest::testPValueNearZero
src/test/java/org/apache/commons/math/stat/correlation/PearsonsCorrelationTest.java
181
src/test/java/org/apache/commons/math/stat/correlation/PearsonsCorrelationTest.java
testPValueNearZero
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.stat.correlation; import org.apache.commons.math.TestUtils; import org.apache.commons.math.distribution.TDistribution; import org.apache.commons.math.distribution.TDistributionImpl; import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.BlockRealMatrix; import junit.framework.TestCase; public class PearsonsCorrelationTest extends TestCase { protected final double[] longleyData = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; protected final double[] swissData = new double[] { 80.2,17.0,15,12,9.96, 83.1,45.1,6,9,84.84, 92.5,39.7,5,5,93.40, 85.8,36.5,12,7,33.77, 76.9,43.5,17,15,5.16, 76.1,35.3,9,7,90.57, 83.8,70.2,16,7,92.85, 92.4,67.8,14,8,97.16, 82.4,53.3,12,7,97.67, 82.9,45.2,16,13,91.38, 87.1,64.5,14,6,98.61, 64.1,62.0,21,12,8.52, 66.9,67.5,14,7,2.27, 68.9,60.7,19,12,4.43, 61.7,69.3,22,5,2.82, 68.3,72.6,18,2,24.20, 71.7,34.0,17,8,3.30, 55.7,19.4,26,28,12.11, 54.3,15.2,31,20,2.15, 65.1,73.0,19,9,2.84, 65.5,59.8,22,10,5.23, 65.0,55.1,14,3,4.52, 56.6,50.9,22,12,15.14, 57.4,54.1,20,6,4.20, 72.5,71.2,12,1,2.40, 74.2,58.1,14,8,5.23, 72.0,63.5,6,3,2.56, 60.5,60.8,16,10,7.72, 58.3,26.8,25,19,18.46, 65.4,49.5,15,8,6.10, 75.5,85.9,3,2,99.71, 69.3,84.9,7,6,99.68, 77.3,89.7,5,2,100.00, 70.5,78.2,12,6,98.96, 79.4,64.9,7,3,98.22, 65.0,75.9,9,9,99.06, 92.2,84.6,3,3,99.46, 79.3,63.1,13,13,96.83, 70.4,38.4,26,12,5.62, 65.7,7.7,29,11,13.79, 72.7,16.7,22,13,11.22, 64.4,17.6,35,32,16.92, 77.6,37.6,15,7,4.97, 67.6,18.7,25,7,8.65, 35.0,1.2,37,53,42.34, 44.7,46.6,16,29,50.43, 42.8,27.7,22,29,58.33 }; /** * Test Longley dataset against R. */ public void testLongly() throws Exception { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.000000000000000, 0.9708985250610560, 0.9835516111796693, 0.5024980838759942, 0.4573073999764817, 0.960390571594376, 0.9713294591921188, 0.970898525061056, 1.0000000000000000, 0.9915891780247822, 0.6206333925590966, 0.4647441876006747, 0.979163432977498, 0.9911491900672053, 0.983551611179669, 0.9915891780247822, 1.0000000000000000, 0.6042609398895580, 0.4464367918926265, 0.991090069458478, 0.9952734837647849, 0.502498083875994, 0.6206333925590966, 0.6042609398895580, 1.0000000000000000, -0.1774206295018783, 0.686551516365312, 0.6682566045621746, 0.457307399976482, 0.4647441876006747, 0.4464367918926265, -0.1774206295018783, 1.0000000000000000, 0.364416267189032, 0.4172451498349454, 0.960390571594376, 0.9791634329774981, 0.9910900694584777, 0.6865515163653120, 0.3644162671890320, 1.000000000000000, 0.9939528462329257, 0.971329459192119, 0.9911491900672053, 0.9952734837647849, 0.6682566045621746, 0.4172451498349454, 0.993952846232926, 1.0000000000000000 }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 7, 7), correlationMatrix, 10E-15); double[] rPvalues = new double[] { 4.38904690369668e-10, 8.36353208910623e-12, 7.8159700933611e-14, 0.0472894097790304, 0.01030636128354301, 0.01316878049026582, 0.0749178049642416, 0.06971758330341182, 0.0830166169296545, 0.510948586323452, 3.693245043123738e-09, 4.327782576751815e-11, 1.167954621905665e-13, 0.00331028281967516, 0.1652293725106684, 3.95834476307755e-10, 1.114663916723657e-13, 1.332267629550188e-15, 0.00466039138541463, 0.1078477071581498, 7.771561172376096e-15 }; RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 7); fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } /** * Test R Swiss fertility dataset against R. */ public void testSwissFertility() throws Exception { RealMatrix matrix = createRealMatrix(swissData, 47, 5); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.0000000000000000, 0.3530791836199747, -0.6458827064572875, -0.6637888570350691, 0.4636847006517939, 0.3530791836199747, 1.0000000000000000,-0.6865422086171366, -0.6395225189483201, 0.4010950530487398, -0.6458827064572875, -0.6865422086171366, 1.0000000000000000, 0.6984152962884830, -0.5727418060641666, -0.6637888570350691, -0.6395225189483201, 0.6984152962884830, 1.0000000000000000, -0.1538589170909148, 0.4636847006517939, 0.4010950530487398, -0.5727418060641666, -0.1538589170909148, 1.0000000000000000 }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 5, 5), correlationMatrix, 10E-15); double[] rPvalues = new double[] { 0.01491720061472623, 9.45043734069043e-07, 9.95151527133974e-08, 3.658616965962355e-07, 1.304590105694471e-06, 4.811397236181847e-08, 0.001028523190118147, 0.005204433539191644, 2.588307925380906e-05, 0.301807756132683 }; RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 5); fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } /** * Test p-value near 0. JIRA: MATH-371 */ public void testPValueNearZero() throws Exception { /* * Create a dataset that has r -> 1, p -> 0 as dimension increases. * Prior to the fix for MATH-371, p vanished for dimension >= 14. * Post fix, p-values diminish smoothly, vanishing at dimension = 127. * Tested value is ~1E-303. */ int dimension = 120; double[][] data = new double[dimension][2]; for (int i = 0; i < dimension; i++) { data[i][0] = i; data[i][1] = i + 1/((double)i + 1); } PearsonsCorrelation corrInstance = new PearsonsCorrelation(data); assertTrue(corrInstance.getCorrelationPValues().getEntry(0, 1) > 0); } /** * Constant column */ public void testConstant() { double[] noVariance = new double[] {1, 1, 1, 1}; double[] values = new double[] {1, 2, 3, 4}; assertTrue(Double.isNaN(new PearsonsCorrelation().correlation(noVariance, values))); } /** * Insufficient data */ public void testInsufficientData() { double[] one = new double[] {1}; double[] two = new double[] {2}; try { new PearsonsCorrelation().correlation(one, two); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } RealMatrix matrix = new BlockRealMatrix(new double[][] {{0},{1}}); try { new PearsonsCorrelation(matrix); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } } /** * Verify that direct t-tests using standard error estimates are consistent * with reported p-values */ public void testStdErrorConsistency() throws Exception { TDistribution tDistribution = new TDistributionImpl(45); RealMatrix matrix = createRealMatrix(swissData, 47, 5); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix rValues = corrInstance.getCorrelationMatrix(); RealMatrix pValues = corrInstance.getCorrelationPValues(); RealMatrix stdErrors = corrInstance.getCorrelationStandardErrors(); for (int i = 0; i < 5; i++) { for (int j = 0; j < i; j++) { double t = Math.abs(rValues.getEntry(i, j)) / stdErrors.getEntry(i, j); double p = 2 * (1 - tDistribution.cumulativeProbability(t)); assertEquals(p, pValues.getEntry(i, j), 10E-15); } } } /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */ public void testCovarianceConsistency() throws Exception { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); Covariance covInstance = new Covariance(matrix); PearsonsCorrelation corrFromCovInstance = new PearsonsCorrelation(covInstance); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance.getCorrelationStandardErrors(), 10E-15); PearsonsCorrelation corrFromCovInstance2 = new PearsonsCorrelation(covInstance.getCovarianceMatrix(), 16); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance2.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance2.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance2.getCorrelationStandardErrors(), 10E-15); } public void testConsistency() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); double[][] data = matrix.getData(); double[] x = matrix.getColumn(0); double[] y = matrix.getColumn(1); assertEquals(new PearsonsCorrelation().correlation(x, y), corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE); TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(), new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE); } protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols) { double[][] matrixData = new double[nRows][nCols]; int ptr = 0; for (int i = 0; i < nRows; i++) { System.arraycopy(data, ptr, matrixData[i], 0, nCols); ptr += nCols; } return new BlockRealMatrix(matrixData); } protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension) { int ptr = 0; RealMatrix result = new BlockRealMatrix(dimension, dimension); for (int i = 1; i < dimension; i++) { for (int j = 0; j < i; j++) { result.setEntry(i, j, data[ptr]); ptr++; } } return result; } protected void fillUpper(RealMatrix matrix, double diagonalValue) { int dimension = matrix.getColumnDimension(); for (int i = 0; i < dimension; i++) { matrix.setEntry(i, i, diagonalValue); for (int j = i+1; j < dimension; j++) { matrix.setEntry(i, j, matrix.getEntry(j, i)); } } } }
// You are a professional Java test case writer, please create a test case named `testPValueNearZero` for the issue `Math-MATH-371`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-371 // // ## Issue-Title: // PearsonsCorrelation.getCorrelationPValues() precision limited by machine epsilon // // ## Issue-Description: // // Similar to the issue described in [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon"), using PearsonsCorrelation.getCorrelationPValues() with many treatments results in p-values that are continuous down to 2.2e-16 but that drop to 0 after that. // // // In [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon"), the problem was described as such: // // > So in essence, the p-value returned by TTestImpl.tTest() is: // // > // // > 1.0 - (cumulativeProbability(t) - cumulativeProbabily(-t)) // // > // // > For large-ish t-statistics, cumulativeProbabilty(-t) can get quite small, and cumulativeProbabilty(t) can get very close to 1.0. When // // > cumulativeProbability(-t) is less than the machine epsilon, we get p-values equal to zero because: // // > // // > 1.0 - 1.0 + 0.0 = 0.0 // // // The solution in [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon") was to modify the p-value calculation to this: // // > p = 2.0 \* cumulativeProbability(-t) // // // Here, the problem is similar. From PearsonsCorrelation.getCorrelationPValues(): // // p = 2 \* (1 - tDistribution.cumulativeProbability(t)); // // // Directly calculating the p-value using identical code as PearsonsCorrelation.getCorrelationPValues(), but with the following change seems to solve the problem: // // p = 2 \* (tDistribution.cumulativeProbability(-t)); // // // // // public void testPValueNearZero() throws Exception {
181
/** * Test p-value near 0. JIRA: MATH-371 */
69
166
src/test/java/org/apache/commons/math/stat/correlation/PearsonsCorrelationTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-371 ## Issue-Title: PearsonsCorrelation.getCorrelationPValues() precision limited by machine epsilon ## Issue-Description: Similar to the issue described in [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon"), using PearsonsCorrelation.getCorrelationPValues() with many treatments results in p-values that are continuous down to 2.2e-16 but that drop to 0 after that. In [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon"), the problem was described as such: > So in essence, the p-value returned by TTestImpl.tTest() is: > > 1.0 - (cumulativeProbability(t) - cumulativeProbabily(-t)) > > For large-ish t-statistics, cumulativeProbabilty(-t) can get quite small, and cumulativeProbabilty(t) can get very close to 1.0. When > cumulativeProbability(-t) is less than the machine epsilon, we get p-values equal to zero because: > > 1.0 - 1.0 + 0.0 = 0.0 The solution in [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon") was to modify the p-value calculation to this: > p = 2.0 \* cumulativeProbability(-t) Here, the problem is similar. From PearsonsCorrelation.getCorrelationPValues(): p = 2 \* (1 - tDistribution.cumulativeProbability(t)); Directly calculating the p-value using identical code as PearsonsCorrelation.getCorrelationPValues(), but with the following change seems to solve the problem: p = 2 \* (tDistribution.cumulativeProbability(-t)); ``` You are a professional Java test case writer, please create a test case named `testPValueNearZero` for the issue `Math-MATH-371`, utilizing the provided issue report information and the following function signature. ```java public void testPValueNearZero() throws Exception { ```
166
[ "org.apache.commons.math.stat.correlation.PearsonsCorrelation" ]
eefaf2784b85ed584e0b4cb52d300851276dd8d9a8fdaabe0eb748da83a61ae6
public void testPValueNearZero() throws Exception
// You are a professional Java test case writer, please create a test case named `testPValueNearZero` for the issue `Math-MATH-371`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-371 // // ## Issue-Title: // PearsonsCorrelation.getCorrelationPValues() precision limited by machine epsilon // // ## Issue-Description: // // Similar to the issue described in [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon"), using PearsonsCorrelation.getCorrelationPValues() with many treatments results in p-values that are continuous down to 2.2e-16 but that drop to 0 after that. // // // In [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon"), the problem was described as such: // // > So in essence, the p-value returned by TTestImpl.tTest() is: // // > // // > 1.0 - (cumulativeProbability(t) - cumulativeProbabily(-t)) // // > // // > For large-ish t-statistics, cumulativeProbabilty(-t) can get quite small, and cumulativeProbabilty(t) can get very close to 1.0. When // // > cumulativeProbability(-t) is less than the machine epsilon, we get p-values equal to zero because: // // > // // > 1.0 - 1.0 + 0.0 = 0.0 // // // The solution in [~~MATH-201~~](https://issues.apache.org/jira/browse/MATH-201 "T-test p-value precision hampered by machine epsilon") was to modify the p-value calculation to this: // // > p = 2.0 \* cumulativeProbability(-t) // // // Here, the problem is similar. From PearsonsCorrelation.getCorrelationPValues(): // // p = 2 \* (1 - tDistribution.cumulativeProbability(t)); // // // Directly calculating the p-value using identical code as PearsonsCorrelation.getCorrelationPValues(), but with the following change seems to solve the problem: // // p = 2 \* (tDistribution.cumulativeProbability(-t)); // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.stat.correlation; import org.apache.commons.math.TestUtils; import org.apache.commons.math.distribution.TDistribution; import org.apache.commons.math.distribution.TDistributionImpl; import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.BlockRealMatrix; import junit.framework.TestCase; public class PearsonsCorrelationTest extends TestCase { protected final double[] longleyData = new double[] { 60323,83.0,234289,2356,1590,107608,1947, 61122,88.5,259426,2325,1456,108632,1948, 60171,88.2,258054,3682,1616,109773,1949, 61187,89.5,284599,3351,1650,110929,1950, 63221,96.2,328975,2099,3099,112075,1951, 63639,98.1,346999,1932,3594,113270,1952, 64989,99.0,365385,1870,3547,115094,1953, 63761,100.0,363112,3578,3350,116219,1954, 66019,101.2,397469,2904,3048,117388,1955, 67857,104.6,419180,2822,2857,118734,1956, 68169,108.4,442769,2936,2798,120445,1957, 66513,110.8,444546,4681,2637,121950,1958, 68655,112.6,482704,3813,2552,123366,1959, 69564,114.2,502601,3931,2514,125368,1960, 69331,115.7,518173,4806,2572,127852,1961, 70551,116.9,554894,4007,2827,130081,1962 }; protected final double[] swissData = new double[] { 80.2,17.0,15,12,9.96, 83.1,45.1,6,9,84.84, 92.5,39.7,5,5,93.40, 85.8,36.5,12,7,33.77, 76.9,43.5,17,15,5.16, 76.1,35.3,9,7,90.57, 83.8,70.2,16,7,92.85, 92.4,67.8,14,8,97.16, 82.4,53.3,12,7,97.67, 82.9,45.2,16,13,91.38, 87.1,64.5,14,6,98.61, 64.1,62.0,21,12,8.52, 66.9,67.5,14,7,2.27, 68.9,60.7,19,12,4.43, 61.7,69.3,22,5,2.82, 68.3,72.6,18,2,24.20, 71.7,34.0,17,8,3.30, 55.7,19.4,26,28,12.11, 54.3,15.2,31,20,2.15, 65.1,73.0,19,9,2.84, 65.5,59.8,22,10,5.23, 65.0,55.1,14,3,4.52, 56.6,50.9,22,12,15.14, 57.4,54.1,20,6,4.20, 72.5,71.2,12,1,2.40, 74.2,58.1,14,8,5.23, 72.0,63.5,6,3,2.56, 60.5,60.8,16,10,7.72, 58.3,26.8,25,19,18.46, 65.4,49.5,15,8,6.10, 75.5,85.9,3,2,99.71, 69.3,84.9,7,6,99.68, 77.3,89.7,5,2,100.00, 70.5,78.2,12,6,98.96, 79.4,64.9,7,3,98.22, 65.0,75.9,9,9,99.06, 92.2,84.6,3,3,99.46, 79.3,63.1,13,13,96.83, 70.4,38.4,26,12,5.62, 65.7,7.7,29,11,13.79, 72.7,16.7,22,13,11.22, 64.4,17.6,35,32,16.92, 77.6,37.6,15,7,4.97, 67.6,18.7,25,7,8.65, 35.0,1.2,37,53,42.34, 44.7,46.6,16,29,50.43, 42.8,27.7,22,29,58.33 }; /** * Test Longley dataset against R. */ public void testLongly() throws Exception { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.000000000000000, 0.9708985250610560, 0.9835516111796693, 0.5024980838759942, 0.4573073999764817, 0.960390571594376, 0.9713294591921188, 0.970898525061056, 1.0000000000000000, 0.9915891780247822, 0.6206333925590966, 0.4647441876006747, 0.979163432977498, 0.9911491900672053, 0.983551611179669, 0.9915891780247822, 1.0000000000000000, 0.6042609398895580, 0.4464367918926265, 0.991090069458478, 0.9952734837647849, 0.502498083875994, 0.6206333925590966, 0.6042609398895580, 1.0000000000000000, -0.1774206295018783, 0.686551516365312, 0.6682566045621746, 0.457307399976482, 0.4647441876006747, 0.4464367918926265, -0.1774206295018783, 1.0000000000000000, 0.364416267189032, 0.4172451498349454, 0.960390571594376, 0.9791634329774981, 0.9910900694584777, 0.6865515163653120, 0.3644162671890320, 1.000000000000000, 0.9939528462329257, 0.971329459192119, 0.9911491900672053, 0.9952734837647849, 0.6682566045621746, 0.4172451498349454, 0.993952846232926, 1.0000000000000000 }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 7, 7), correlationMatrix, 10E-15); double[] rPvalues = new double[] { 4.38904690369668e-10, 8.36353208910623e-12, 7.8159700933611e-14, 0.0472894097790304, 0.01030636128354301, 0.01316878049026582, 0.0749178049642416, 0.06971758330341182, 0.0830166169296545, 0.510948586323452, 3.693245043123738e-09, 4.327782576751815e-11, 1.167954621905665e-13, 0.00331028281967516, 0.1652293725106684, 3.95834476307755e-10, 1.114663916723657e-13, 1.332267629550188e-15, 0.00466039138541463, 0.1078477071581498, 7.771561172376096e-15 }; RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 7); fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } /** * Test R Swiss fertility dataset against R. */ public void testSwissFertility() throws Exception { RealMatrix matrix = createRealMatrix(swissData, 47, 5); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.0000000000000000, 0.3530791836199747, -0.6458827064572875, -0.6637888570350691, 0.4636847006517939, 0.3530791836199747, 1.0000000000000000,-0.6865422086171366, -0.6395225189483201, 0.4010950530487398, -0.6458827064572875, -0.6865422086171366, 1.0000000000000000, 0.6984152962884830, -0.5727418060641666, -0.6637888570350691, -0.6395225189483201, 0.6984152962884830, 1.0000000000000000, -0.1538589170909148, 0.4636847006517939, 0.4010950530487398, -0.5727418060641666, -0.1538589170909148, 1.0000000000000000 }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 5, 5), correlationMatrix, 10E-15); double[] rPvalues = new double[] { 0.01491720061472623, 9.45043734069043e-07, 9.95151527133974e-08, 3.658616965962355e-07, 1.304590105694471e-06, 4.811397236181847e-08, 0.001028523190118147, 0.005204433539191644, 2.588307925380906e-05, 0.301807756132683 }; RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 5); fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } /** * Test p-value near 0. JIRA: MATH-371 */ public void testPValueNearZero() throws Exception { /* * Create a dataset that has r -> 1, p -> 0 as dimension increases. * Prior to the fix for MATH-371, p vanished for dimension >= 14. * Post fix, p-values diminish smoothly, vanishing at dimension = 127. * Tested value is ~1E-303. */ int dimension = 120; double[][] data = new double[dimension][2]; for (int i = 0; i < dimension; i++) { data[i][0] = i; data[i][1] = i + 1/((double)i + 1); } PearsonsCorrelation corrInstance = new PearsonsCorrelation(data); assertTrue(corrInstance.getCorrelationPValues().getEntry(0, 1) > 0); } /** * Constant column */ public void testConstant() { double[] noVariance = new double[] {1, 1, 1, 1}; double[] values = new double[] {1, 2, 3, 4}; assertTrue(Double.isNaN(new PearsonsCorrelation().correlation(noVariance, values))); } /** * Insufficient data */ public void testInsufficientData() { double[] one = new double[] {1}; double[] two = new double[] {2}; try { new PearsonsCorrelation().correlation(one, two); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } RealMatrix matrix = new BlockRealMatrix(new double[][] {{0},{1}}); try { new PearsonsCorrelation(matrix); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } } /** * Verify that direct t-tests using standard error estimates are consistent * with reported p-values */ public void testStdErrorConsistency() throws Exception { TDistribution tDistribution = new TDistributionImpl(45); RealMatrix matrix = createRealMatrix(swissData, 47, 5); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix rValues = corrInstance.getCorrelationMatrix(); RealMatrix pValues = corrInstance.getCorrelationPValues(); RealMatrix stdErrors = corrInstance.getCorrelationStandardErrors(); for (int i = 0; i < 5; i++) { for (int j = 0; j < i; j++) { double t = Math.abs(rValues.getEntry(i, j)) / stdErrors.getEntry(i, j); double p = 2 * (1 - tDistribution.cumulativeProbability(t)); assertEquals(p, pValues.getEntry(i, j), 10E-15); } } } /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */ public void testCovarianceConsistency() throws Exception { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); Covariance covInstance = new Covariance(matrix); PearsonsCorrelation corrFromCovInstance = new PearsonsCorrelation(covInstance); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance.getCorrelationStandardErrors(), 10E-15); PearsonsCorrelation corrFromCovInstance2 = new PearsonsCorrelation(covInstance.getCovarianceMatrix(), 16); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance2.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance2.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance2.getCorrelationStandardErrors(), 10E-15); } public void testConsistency() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); double[][] data = matrix.getData(); double[] x = matrix.getColumn(0); double[] y = matrix.getColumn(1); assertEquals(new PearsonsCorrelation().correlation(x, y), corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE); TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(), new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE); } protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols) { double[][] matrixData = new double[nRows][nCols]; int ptr = 0; for (int i = 0; i < nRows; i++) { System.arraycopy(data, ptr, matrixData[i], 0, nCols); ptr += nCols; } return new BlockRealMatrix(matrixData); } protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension) { int ptr = 0; RealMatrix result = new BlockRealMatrix(dimension, dimension); for (int i = 1; i < dimension; i++) { for (int j = 0; j < i; j++) { result.setEntry(i, j, data[ptr]); ptr++; } } return result; } protected void fillUpper(RealMatrix matrix, double diagonalValue) { int dimension = matrix.getColumnDimension(); for (int i = 0; i < dimension; i++) { matrix.setEntry(i, i, diagonalValue); for (int j = i+1; j < dimension; j++) { matrix.setEntry(i, j, matrix.getEntry(j, i)); } } } }
public void testStructuralConstructor2() throws Exception { JSType type = testParseType( "function (new:?)", // toString skips unknowns, but isConstructor reveals the truth. "function (): ?"); assertTrue(type.isConstructor()); assertFalse(type.isNominalConstructor()); }
com.google.javascript.jscomp.parsing.JsDocInfoParserTest::testStructuralConstructor2
test/com/google/javascript/jscomp/parsing/JsDocInfoParserTest.java
590
test/com/google/javascript/jscomp/parsing/JsDocInfoParserTest.java
testStructuralConstructor2
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.parsing; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.SourceFile; import com.google.javascript.jscomp.parsing.Config.LanguageMode; import com.google.javascript.jscomp.testing.TestErrorReporter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Marker; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.JSTypeExpression; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.head.CompilerEnvirons; import com.google.javascript.rhino.head.Parser; import com.google.javascript.rhino.head.Token.CommentType; import com.google.javascript.rhino.head.ast.AstRoot; import com.google.javascript.rhino.head.ast.Comment; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.jstype.SimpleSourceFile; import com.google.javascript.rhino.jstype.StaticSourceFile; import com.google.javascript.rhino.jstype.TemplateType; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Set; public class JsDocInfoParserTest extends BaseJSTypeTestCase { private Set<String> extraAnnotations; private Set<String> extraSuppressions; private Node.FileLevelJsDocBuilder fileLevelJsDocBuilder = null; @Override public void setUp() throws Exception { super.setUp(); extraAnnotations = Sets.newHashSet( ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false) .annotationNames.keySet()); extraSuppressions = Sets.newHashSet( ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false) .suppressionNames); extraSuppressions.add("x"); extraSuppressions.add("y"); extraSuppressions.add("z"); } public void testParseTypeViaStatic1() throws Exception { Node typeNode = parseType("null"); assertTypeEquals(NULL_TYPE, typeNode); } public void testParseTypeViaStatic2() throws Exception { Node typeNode = parseType("string"); assertTypeEquals(STRING_TYPE, typeNode); } public void testParseTypeViaStatic3() throws Exception { Node typeNode = parseType("!Date"); assertTypeEquals(DATE_TYPE, typeNode); } public void testParseTypeViaStatic4() throws Exception { Node typeNode = parseType("boolean|string"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, STRING_TYPE), typeNode); } public void testParseInvalidTypeViaStatic() throws Exception { Node typeNode = parseType("sometype.<anothertype"); assertNull(typeNode); } public void testParseInvalidTypeViaStatic2() throws Exception { Node typeNode = parseType(""); assertNull(typeNode); } public void testParseNamedType1() throws Exception { assertNull(parse("@type null", "Unexpected end of file")); } public void testParseNamedType2() throws Exception { JSDocInfo info = parse("@type null*/"); assertTypeEquals(NULL_TYPE, info.getType()); } public void testParseNamedType3() throws Exception { JSDocInfo info = parse("@type {string}*/"); assertTypeEquals(STRING_TYPE, info.getType()); } public void testParseNamedType4() throws Exception { // Multi-line @type. JSDocInfo info = parse("@type \n {string}*/"); assertTypeEquals(STRING_TYPE, info.getType()); } public void testParseNamedType5() throws Exception { JSDocInfo info = parse("@type {!goog.\nBar}*/"); assertTypeEquals( registry.createNamedType("goog.Bar", null, -1, -1), info.getType()); } public void testParseNamedType6() throws Exception { JSDocInfo info = parse("@type {!goog.\n * Bar.\n * Baz}*/"); assertTypeEquals( registry.createNamedType("goog.Bar.Baz", null, -1, -1), info.getType()); } public void testParseNamedTypeError1() throws Exception { // To avoid parsing ambiguities, type names must end in a '.' to // get the continuation behavior. parse("@type {!goog\n * .Bar} */", "Bad type annotation. expected closing }"); } public void testParseNamedTypeError2() throws Exception { parse("@type {!goog.\n * Bar\n * .Baz} */", "Bad type annotation. expected closing }"); } public void testParseNamespaceType1() throws Exception { JSDocInfo info = parse("@type {goog.}*/"); assertTypeEquals( registry.createNamedType("goog.", null, -1, -1), info.getType()); } public void testTypedefType1() throws Exception { JSDocInfo info = parse("@typedef string */"); assertTrue(info.hasTypedefType()); assertTypeEquals(STRING_TYPE, info.getTypedefType()); } public void testTypedefType2() throws Exception { JSDocInfo info = parse("@typedef \n {string}*/"); assertTrue(info.hasTypedefType()); assertTypeEquals(STRING_TYPE, info.getTypedefType()); } public void testTypedefType3() throws Exception { JSDocInfo info = parse("@typedef \n {(string|number)}*/"); assertTrue(info.hasTypedefType()); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), info.getTypedefType()); } public void testParseStringType1() throws Exception { assertTypeEquals(STRING_TYPE, parse("@type {string}*/").getType()); } public void testParseStringType2() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@type {!String}*/").getType()); } public void testParseBooleanType1() throws Exception { assertTypeEquals(BOOLEAN_TYPE, parse("@type {boolean}*/").getType()); } public void testParseBooleanType2() throws Exception { assertTypeEquals( BOOLEAN_OBJECT_TYPE, parse("@type {!Boolean}*/").getType()); } public void testParseNumberType1() throws Exception { assertTypeEquals(NUMBER_TYPE, parse("@type {number}*/").getType()); } public void testParseNumberType2() throws Exception { assertTypeEquals(NUMBER_OBJECT_TYPE, parse("@type {!Number}*/").getType()); } public void testParseNullType1() throws Exception { assertTypeEquals(NULL_TYPE, parse("@type {null}*/").getType()); } public void testParseNullType2() throws Exception { assertTypeEquals(NULL_TYPE, parse("@type {Null}*/").getType()); } public void testParseAllType1() throws Exception { testParseType("*"); } public void testParseAllType2() throws Exception { testParseType("*?", "*"); } public void testParseObjectType() throws Exception { assertTypeEquals(OBJECT_TYPE, parse("@type {!Object}*/").getType()); } public void testParseDateType() throws Exception { assertTypeEquals(DATE_TYPE, parse("@type {!Date}*/").getType()); } public void testParseFunctionType() throws Exception { assertTypeEquals( createNullableType(U2U_CONSTRUCTOR_TYPE), parse("@type {Function}*/").getType()); } public void testParseRegExpType() throws Exception { assertTypeEquals(REGEXP_TYPE, parse("@type {!RegExp}*/").getType()); } public void testParseErrorTypes() throws Exception { assertTypeEquals(ERROR_TYPE, parse("@type {!Error}*/").getType()); assertTypeEquals(URI_ERROR_TYPE, parse("@type {!URIError}*/").getType()); assertTypeEquals(EVAL_ERROR_TYPE, parse("@type {!EvalError}*/").getType()); assertTypeEquals(REFERENCE_ERROR_TYPE, parse("@type {!ReferenceError}*/").getType()); assertTypeEquals(TYPE_ERROR_TYPE, parse("@type {!TypeError}*/").getType()); assertTypeEquals( RANGE_ERROR_TYPE, parse("@type {!RangeError}*/").getType()); assertTypeEquals( SYNTAX_ERROR_TYPE, parse("@type {!SyntaxError}*/").getType()); } public void testParseUndefinedType1() throws Exception { assertTypeEquals(VOID_TYPE, parse("@type {undefined}*/").getType()); } public void testParseUndefinedType2() throws Exception { assertTypeEquals(VOID_TYPE, parse("@type {Undefined}*/").getType()); } public void testParseUndefinedType3() throws Exception { assertTypeEquals(VOID_TYPE, parse("@type {void}*/").getType()); } public void testParseTemplatizedType1() throws Exception { JSDocInfo info = parse("@type !Array.<number> */"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType()); } public void testParseTemplatizedType2() throws Exception { JSDocInfo info = parse("@type {!Array.<number>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType()); } public void testParseTemplatizedType3() throws Exception { JSDocInfo info = parse("@type !Array.<(number,null)>*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType4() throws Exception { JSDocInfo info = parse("@type {!Array.<(number|null)>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType5() throws Exception { JSDocInfo info = parse("@type {!Array.<Array.<(number|null)>>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(NULL_TYPE, createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)))), info.getType()); } public void testParseTemplatizedType6() throws Exception { JSDocInfo info = parse("@type {!Array.<!Array.<(number|null)>>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE))), info.getType()); } public void testParseTemplatizedType7() throws Exception { JSDocInfo info = parse("@type {!Array.<function():Date>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, registry.createFunctionType( createUnionType(DATE_TYPE, NULL_TYPE))), info.getType()); } public void testParseTemplatizedType8() throws Exception { JSDocInfo info = parse("@type {!Array.<function():!Date>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, registry.createFunctionType(DATE_TYPE)), info.getType()); } public void testParseTemplatizedType9() throws Exception { JSDocInfo info = parse("@type {!Array.<Date|number>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(DATE_TYPE, NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType10() throws Exception { JSDocInfo info = parse("@type {!Array.<Date|number|boolean>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(DATE_TYPE, NUMBER_TYPE, BOOLEAN_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType11() throws Exception { JSDocInfo info = parse("@type {!Object.<number>}*/"); assertTypeEquals( createTemplatizedType( OBJECT_TYPE, ImmutableList.of(UNKNOWN_TYPE, NUMBER_TYPE)), info.getType()); assertTemplatizedTypeEquals( registry.getObjectElementKey(), NUMBER_TYPE, info.getType()); } public void testParseTemplatizedType12() throws Exception { JSDocInfo info = parse("@type {!Object.<string,number>}*/"); assertTypeEquals( createTemplatizedType( OBJECT_TYPE, ImmutableList.of(STRING_TYPE, NUMBER_TYPE)), info.getType()); assertTemplatizedTypeEquals( registry.getObjectElementKey(), NUMBER_TYPE, info.getType()); assertTemplatizedTypeEquals( registry.getObjectIndexKey(), STRING_TYPE, info.getType()); } public void testParseTemplatizedType13() throws Exception { JSDocInfo info = parse("@type !Array.<?> */"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, UNKNOWN_TYPE), info.getType()); } public void testParseUnionType1() throws Exception { JSDocInfo info = parse("@type {(boolean,null)}*/"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType()); } public void testParseUnionType2() throws Exception { JSDocInfo info = parse("@type {boolean|null}*/"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType()); } public void testParseUnionType3() throws Exception { JSDocInfo info = parse("@type {boolean||null}*/"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType()); } public void testParseUnionType4() throws Exception { JSDocInfo info = parse("@type {(Array.<boolean>,null)}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType5() throws Exception { JSDocInfo info = parse("@type {(null, Array.<boolean>)}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType6() throws Exception { JSDocInfo info = parse("@type {Array.<boolean>|null}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType7() throws Exception { JSDocInfo info = parse("@type {null|Array.<boolean>}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType8() throws Exception { JSDocInfo info = parse("@type {null||Array.<boolean>}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType9() throws Exception { JSDocInfo info = parse("@type {Array.<boolean>||null}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType10() throws Exception { parse("@type {string|}*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnionType11() throws Exception { parse("@type {(string,)}*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnionType12() throws Exception { parse("@type {()}*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnionType13() throws Exception { testParseType( "(function(this:Date),function(this:String):number)", "Function"); } public void testParseUnionType14() throws Exception { testParseType( "(function(...[function(number):boolean]):number)|" + "function(this:String, string):number", "Function"); } public void testParseUnionType15() throws Exception { testParseType("*|number", "*"); } public void testParseUnionType16() throws Exception { testParseType("number|*", "*"); } public void testParseUnionType17() throws Exception { testParseType("string|number|*", "*"); } public void testParseUnionType18() throws Exception { testParseType("(string,*,number)", "*"); } public void testParseUnionTypeError1() throws Exception { parse("@type {(string,|number)} */", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnknownType1() throws Exception { testParseType("?"); } public void testParseUnknownType2() throws Exception { testParseType("(?|number)", "?"); } public void testParseUnknownType3() throws Exception { testParseType("(number|?)", "?"); } public void testParseFunctionalType1() throws Exception { testParseType("function (): number"); } public void testParseFunctionalType2() throws Exception { testParseType("function (number, string): boolean"); } public void testParseFunctionalType3() throws Exception { testParseType( "function(this:Array)", "function (this:Array): ?"); } public void testParseFunctionalType4() throws Exception { testParseType("function (...[number]): boolean"); } public void testParseFunctionalType5() throws Exception { testParseType("function (number, ...[string]): boolean"); } public void testParseFunctionalType6() throws Exception { testParseType( "function (this:Date, number): (boolean|number|string)"); } public void testParseFunctionalType7() throws Exception { testParseType("function()", "function (): ?"); } public void testParseFunctionalType8() throws Exception { testParseType( "function(this:Array,...[boolean])", "function (this:Array, ...[boolean]): ?"); } public void testParseFunctionalType9() throws Exception { testParseType( "function(this:Array,!Date,...[boolean?])", "function (this:Array, Date, ...[(boolean|null)]): ?"); } public void testParseFunctionalType10() throws Exception { testParseType( "function(...[Object?]):boolean?", "function (...[(Object|null)]): (boolean|null)"); } public void testParseFunctionalType11() throws Exception { testParseType( "function(...[[number]]):[number?]", "function (...[Array]): Array"); } public void testParseFunctionalType12() throws Exception { testParseType( "function(...)", "function (...[?]): ?"); } public void testParseFunctionalType13() throws Exception { testParseType( "function(...): void", "function (...[?]): undefined"); } public void testParseFunctionalType14() throws Exception { testParseType("function (*, string, number): boolean"); } public void testParseFunctionalType15() throws Exception { testParseType("function (?, string): boolean"); } public void testParseFunctionalType16() throws Exception { testParseType("function (string, ?): ?"); } public void testParseFunctionalType17() throws Exception { testParseType("(function (?): ?|number)"); } public void testParseFunctionalType18() throws Exception { testParseType("function (?): (?|number)", "function (?): ?"); } public void testParseFunctionalType19() throws Exception { testParseType( "function(...[?]): void", "function (...[?]): undefined"); } public void testStructuralConstructor() throws Exception { JSType type = testParseType( "function (new:Object)", "function (new:Object): ?"); assertTrue(type.isConstructor()); assertFalse(type.isNominalConstructor()); } public void testStructuralConstructor2() throws Exception { JSType type = testParseType( "function (new:?)", // toString skips unknowns, but isConstructor reveals the truth. "function (): ?"); assertTrue(type.isConstructor()); assertFalse(type.isNominalConstructor()); } public void testStructuralConstructor3() throws Exception { resolve(parse("@type {function (new:*)} */").getType(), "constructed type must be an object type"); } public void testNominalConstructor() throws Exception { ObjectType type = testParseType("Array", "(Array|null)").dereference(); assertTrue(type.getConstructor().isNominalConstructor()); } public void testBug1419535() throws Exception { parse("@type {function(Object, string, *)?} */"); parse("@type {function(Object, string, *)|null} */"); } public void testIssue477() throws Exception { parse("@type function */", "Bad type annotation. missing opening ("); } public void testMalformedThisAnnotation() throws Exception { parse("@this */", "Bad type annotation. type not recognized due to syntax error"); } public void testParseFunctionalTypeError1() throws Exception { parse("@type {function number):string}*/", "Bad type annotation. missing opening ("); } public void testParseFunctionalTypeError2() throws Exception { parse("@type {function( number}*/", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError3() throws Exception { parse("@type {function(...[number], string)}*/", "Bad type annotation. variable length argument must be last"); } public void testParseFunctionalTypeError4() throws Exception { parse("@type {function(string, ...[number], boolean):string}*/", "Bad type annotation. variable length argument must be last"); } public void testParseFunctionalTypeError5() throws Exception { parse("@type {function (thi:Array)}*/", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError6() throws Exception { resolve(parse("@type {function (this:number)}*/").getType(), "this type must be an object type"); } public void testParseFunctionalTypeError7() throws Exception { parse("@type {function(...[number)}*/", "Bad type annotation. missing closing ]"); } public void testParseFunctionalTypeError8() throws Exception { parse("@type {function(...number])}*/", "Bad type annotation. missing opening ["); } public void testParseFunctionalTypeError9() throws Exception { parse("@type {function (new:Array, this:Object)} */", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError10() throws Exception { parse("@type {function (this:Array, new:Object)} */", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError11() throws Exception { parse("@type {function (Array, new:Object)} */", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError12() throws Exception { resolve(parse("@type {function (new:number)}*/").getType(), "constructed type must be an object type"); } public void testParseArrayType1() throws Exception { testParseType("[number]", "Array"); } public void testParseArrayType2() throws Exception { testParseType("[(number,boolean,[Object?])]", "Array"); } public void testParseArrayType3() throws Exception { testParseType("[[number],[string]]?", "(Array|null)"); } public void testParseArrayTypeError1() throws Exception { parse("@type {[number}*/", "Bad type annotation. missing closing ]"); } public void testParseArrayTypeError2() throws Exception { parse("@type {number]}*/", "Bad type annotation. expected closing }"); } public void testParseArrayTypeError3() throws Exception { parse("@type {[(number,boolean,Object?])]}*/", "Bad type annotation. missing closing )"); } public void testParseArrayTypeError4() throws Exception { parse("@type {(number,boolean,[Object?)]}*/", "Bad type annotation. missing closing ]"); } private JSType testParseType(String type) throws Exception { return testParseType(type, type); } private JSType testParseType( String type, String typeExpected) throws Exception { JSDocInfo info = parse("@type {" + type + "}*/"); assertNotNull(info); assertTrue(info.hasType()); JSType actual = resolve(info.getType()); assertEquals(typeExpected, actual.toString()); return actual; } public void testParseNullableModifiers1() throws Exception { JSDocInfo info = parse("@type {string?}*/"); assertTypeEquals(createNullableType(STRING_TYPE), info.getType()); } public void testParseNullableModifiers2() throws Exception { JSDocInfo info = parse("@type {!Array.<string?>}*/"); assertTypeEquals( createTemplatizedType( ARRAY_TYPE, createUnionType(STRING_TYPE, NULL_TYPE)), info.getType()); } public void testParseNullableModifiers3() throws Exception { JSDocInfo info = parse("@type {Array.<boolean>?}*/"); assertTypeEquals( createNullableType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers4() throws Exception { JSDocInfo info = parse("@type {(string,boolean)?}*/"); assertTypeEquals( createNullableType(createUnionType(STRING_TYPE, BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers5() throws Exception { JSDocInfo info = parse("@type {(string?,boolean)}*/"); assertTypeEquals( createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE), info.getType()); } public void testParseNullableModifiers6() throws Exception { JSDocInfo info = parse("@type {(string,boolean?)}*/"); assertTypeEquals( createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers7() throws Exception { JSDocInfo info = parse("@type {string?|boolean}*/"); assertTypeEquals( createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE), info.getType()); } public void testParseNullableModifiers8() throws Exception { JSDocInfo info = parse("@type {string|boolean?}*/"); assertTypeEquals( createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers9() throws Exception { JSDocInfo info = parse("@type {foo.Hello.World?}*/"); assertTypeEquals( createNullableType( registry.createNamedType( "foo.Hello.World", null, -1, -1)), info.getType()); } public void testParseOptionalModifier() throws Exception { JSDocInfo info = parse("@type {function(number=)}*/"); assertTypeEquals( registry.createFunctionType( UNKNOWN_TYPE, registry.createOptionalParameters(NUMBER_TYPE)), info.getType()); } public void testParseNewline1() throws Exception { JSDocInfo info = parse("@type {string\n* }\n*/"); assertTypeEquals(STRING_TYPE, info.getType()); } public void testParseNewline2() throws Exception { JSDocInfo info = parse("@type !Array.<\n* number\n* > */"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType()); } public void testParseNewline3() throws Exception { JSDocInfo info = parse("@type !Array.<(number,\n* null)>*/"); assertTypeEquals( createTemplatizedType( ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseNewline4() throws Exception { JSDocInfo info = parse("@type !Array.<(number|\n* null)>*/"); assertTypeEquals( createTemplatizedType( ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseNewline5() throws Exception { JSDocInfo info = parse("@type !Array.<function(\n* )\n* :\n* Date>*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, registry.createFunctionType( createUnionType(DATE_TYPE, NULL_TYPE))), info.getType()); } public void testParseReturnType1() throws Exception { JSDocInfo info = parse("@return {null|string|Array.<boolean>}*/"); assertTypeEquals( createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE, STRING_TYPE), info.getReturnType()); } public void testParseReturnType2() throws Exception { JSDocInfo info = parse("@returns {null|(string,Array.<boolean>)}*/"); assertTypeEquals( createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE, STRING_TYPE), info.getReturnType()); } public void testParseReturnType3() throws Exception { JSDocInfo info = parse("@return {((null||Array.<boolean>,string),boolean)}*/"); assertTypeEquals( createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE, STRING_TYPE, BOOLEAN_TYPE), info.getReturnType()); } public void testParseThisType1() throws Exception { JSDocInfo info = parse("@this {goog.foo.Bar}*/"); assertTypeEquals( registry.createNamedType("goog.foo.Bar", null, -1, -1), info.getThisType()); } public void testParseThisType2() throws Exception { JSDocInfo info = parse("@this goog.foo.Bar*/"); assertTypeEquals( registry.createNamedType("goog.foo.Bar", null, -1, -1), info.getThisType()); } public void testParseThisType3() throws Exception { parse("@type {number}\n@this goog.foo.Bar*/", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testParseThisType4() throws Exception { resolve(parse("@this number*/").getThisType(), "@this must specify an object type"); } public void testParseThisType5() throws Exception { parse("@this {Date|Error}*/"); } public void testParseThisType6() throws Exception { resolve(parse("@this {Date|number}*/").getThisType(), "@this must specify an object type"); } public void testParseParam1() throws Exception { JSDocInfo info = parse("@param {number} index*/"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam2() throws Exception { JSDocInfo info = parse("@param index*/"); assertEquals(1, info.getParameterCount()); assertEquals(null, info.getParameterType("index")); } public void testParseParam3() throws Exception { JSDocInfo info = parse("@param {number} index useful comments*/"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam4() throws Exception { JSDocInfo info = parse("@param index useful comments*/"); assertEquals(1, info.getParameterCount()); assertEquals(null, info.getParameterType("index")); } public void testParseParam5() throws Exception { // Test for multi-line @param. JSDocInfo info = parse("@param {number} \n index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam6() throws Exception { // Test for multi-line @param. JSDocInfo info = parse("@param {number} \n * index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam7() throws Exception { // Optional @param JSDocInfo info = parse("@param {number=} index */"); assertTypeEquals( registry.createOptionalType(NUMBER_TYPE), info.getParameterType("index")); } public void testParseParam8() throws Exception { // Var args @param JSDocInfo info = parse("@param {...number} index */"); assertTypeEquals( registry.createOptionalType(NUMBER_TYPE), info.getParameterType("index")); } public void testParseParam9() throws Exception { parse("@param {...number=} index */", "Bad type annotation. expected closing }", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParam10() throws Exception { parse("@param {...number index */", "Bad type annotation. expected closing }"); } public void testParseParam11() throws Exception { parse("@param {number= index */", "Bad type annotation. expected closing }"); } public void testParseParam12() throws Exception { JSDocInfo info = parse("@param {...number|string} index */"); assertTypeEquals( registry.createOptionalType( registry.createUnionType(STRING_TYPE, NUMBER_TYPE)), info.getParameterType("index")); } public void testParseParam13() throws Exception { JSDocInfo info = parse("@param {...(number|string)} index */"); assertTypeEquals( registry.createOptionalType( registry.createUnionType(STRING_TYPE, NUMBER_TYPE)), info.getParameterType("index")); } public void testParseParam14() throws Exception { JSDocInfo info = parse("@param {string} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("index")); } public void testParseParam15() throws Exception { JSDocInfo info = parse("@param {string} [index */", "Bad type annotation. missing closing ]"); assertEquals(1, info.getParameterCount()); assertTypeEquals(STRING_TYPE, info.getParameterType("index")); } public void testParseParam16() throws Exception { JSDocInfo info = parse("@param {string} index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals(STRING_TYPE, info.getParameterType("index")); } public void testParseParam17() throws Exception { JSDocInfo info = parse("@param {string=} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("index")); } public void testParseParam18() throws Exception { JSDocInfo info = parse("@param {...string} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("index")); } public void testParseParam19() throws Exception { JSDocInfo info = parse("@param {...} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(UNKNOWN_TYPE), info.getParameterType("index")); assertTrue(info.getParameterType("index").isVarArgs()); } public void testParseParam20() throws Exception { JSDocInfo info = parse("@param {?=} index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( UNKNOWN_TYPE, info.getParameterType("index")); } public void testParseParam21() throws Exception { JSDocInfo info = parse("@param {...?} index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( UNKNOWN_TYPE, info.getParameterType("index")); assertTrue(info.getParameterType("index").isVarArgs()); } public void testParseThrows1() throws Exception { JSDocInfo info = parse("@throws {number} Some number */"); assertEquals(1, info.getThrownTypes().size()); assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0)); } public void testParseThrows2() throws Exception { JSDocInfo info = parse("@throws {number} Some number\n " + "*@throws {String} A string */"); assertEquals(2, info.getThrownTypes().size()); assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0)); } public void testParseRecordType1() throws Exception { parseFull("/** @param {{x}} n\n*/"); } public void testParseRecordType2() throws Exception { parseFull("/** @param {{z, y}} n\n*/"); } public void testParseRecordType3() throws Exception { parseFull("/** @param {{z, y, x, q, hello, thisisatest}} n\n*/"); } public void testParseRecordType4() throws Exception { parseFull("/** @param {{a, 'a', 'hello', 2, this, do, while, for}} n\n*/"); } public void testParseRecordType5() throws Exception { parseFull("/** @param {{x : hello}} n\n*/"); } public void testParseRecordType6() throws Exception { parseFull("/** @param {{'x' : hello}} n\n*/"); } public void testParseRecordType7() throws Exception { parseFull("/** @param {{'x' : !hello}} n\n*/"); } public void testParseRecordType8() throws Exception { parseFull("/** @param {{'x' : !hello, y : bar}} n\n*/"); } public void testParseRecordType9() throws Exception { parseFull("/** @param {{'x' : !hello, y : {z : bar, 3 : meh}}} n\n*/"); } public void testParseRecordType10() throws Exception { parseFull("/** @param {{__proto__ : moo}} n\n*/"); } public void testParseRecordType11() throws Exception { parseFull("/** @param {{a : b} n\n*/", "Bad type annotation. expected closing }"); } public void testParseRecordType12() throws Exception { parseFull("/** @param {{!hello : hey}} n\n*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseRecordType13() throws Exception { parseFull("/** @param {{x}|number} n\n*/"); } public void testParseRecordType14() throws Exception { parseFull("/** @param {{x : y}|number} n\n*/"); } public void testParseRecordType15() throws Exception { parseFull("/** @param {{'x' : y}|number} n\n*/"); } public void testParseRecordType16() throws Exception { parseFull("/** @param {{x, y}|number} n\n*/"); } public void testParseRecordType17() throws Exception { parseFull("/** @param {{x : hello, 'y'}|number} n\n*/"); } public void testParseRecordType18() throws Exception { parseFull("/** @param {number|{x : hello, 'y'}} n\n*/"); } public void testParseRecordType19() throws Exception { parseFull("/** @param {?{x : hello, 'y'}} n\n*/"); } public void testParseRecordType20() throws Exception { parseFull("/** @param {!{x : hello, 'y'}} n\n*/"); } public void testParseRecordType21() throws Exception { parseFull("/** @param {{x : hello, 'y'}|boolean} n\n*/"); } public void testParseRecordType22() throws Exception { parseFull("/** @param {{x : hello, 'y'}|function()} n\n*/"); } public void testParseRecordType23() throws Exception { parseFull("/** @param {{x : function(), 'y'}|function()} n\n*/"); } public void testParseParamError1() throws Exception { parseFull("/** @param\n*/", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError2() throws Exception { parseFull("/** @param {Number}*/", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError3() throws Exception { parseFull("/** @param {Number}\n*/", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError4() throws Exception { parseFull("/** @param {Number}\n* * num */", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError5() throws Exception { parse("@param {number} x \n * @param {string} x */", "Bad type annotation. duplicate variable name \"x\""); } public void testParseExtends1() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends String*/").getBaseType()); } public void testParseExtends2() throws Exception { JSDocInfo info = parse("@extends com.google.Foo.Bar.Hello.World*/"); assertTypeEquals( registry.createNamedType( "com.google.Foo.Bar.Hello.World", null, -1, -1), info.getBaseType()); } public void testParseExtendsGenerics() throws Exception { JSDocInfo info = parse("@extends com.google.Foo.Bar.Hello.World.<Boolean,number>*/"); assertTypeEquals( registry.createNamedType( "com.google.Foo.Bar.Hello.World", null, -1, -1), info.getBaseType()); } public void testParseImplementsGenerics() throws Exception { // For types that are not templatized, <> annotations are ignored. List<JSTypeExpression> interfaces = parse("@implements {SomeInterface.<*>} */") .getImplementedInterfaces(); assertEquals(1, interfaces.size()); assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1), interfaces.get(0)); } public void testParseExtends4() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends {String}*/").getBaseType()); } public void testParseExtends5() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends {String*/", "Bad type annotation. expected closing }").getBaseType()); } public void testParseExtends6() throws Exception { // Multi-line extends assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends \n * {String}*/").getBaseType()); } public void testParseExtendsInvalidName() throws Exception { // This looks bad, but for the time being it should be OK, as // we will not find a type with this name in the JS parsed tree. // If this is fixed in the future, change this test to check for a // warning/error message. assertTypeEquals( registry.createNamedType("some_++#%$%_UglyString", null, -1, -1), parse("@extends {some_++#%$%_UglyString} */").getBaseType()); } public void testParseExtendsNullable1() throws Exception { parse("@extends {Base?} */", "Bad type annotation. expected closing }"); } public void testParseExtendsNullable2() throws Exception { parse("@extends Base? */", "Bad type annotation. expected end of line or comment"); } public void testParseEnum1() throws Exception { assertTypeEquals(NUMBER_TYPE, parse("@enum*/").getEnumParameterType()); } public void testParseEnum2() throws Exception { assertTypeEquals(STRING_TYPE, parse("@enum {string}*/").getEnumParameterType()); } public void testParseEnum3() throws Exception { assertTypeEquals(STRING_TYPE, parse("@enum string*/").getEnumParameterType()); } public void testParseDesc1() throws Exception { assertEquals("hello world!", parse("@desc hello world!*/").getDescription()); } public void testParseDesc2() throws Exception { assertEquals("hello world!", parse("@desc hello world!\n*/").getDescription()); } public void testParseDesc3() throws Exception { assertEquals("", parse("@desc*/").getDescription()); } public void testParseDesc4() throws Exception { assertEquals("", parse("@desc\n*/").getDescription()); } public void testParseDesc5() throws Exception { assertEquals("hello world!", parse("@desc hello\nworld!\n*/").getDescription()); } public void testParseDesc6() throws Exception { assertEquals("hello world!", parse("@desc hello\n* world!\n*/").getDescription()); } public void testParseDesc7() throws Exception { assertEquals("a b c", parse("@desc a\n\nb\nc*/").getDescription()); } public void testParseDesc8() throws Exception { assertEquals("a b c d", parse("@desc a\n *b\n\n *c\n\nd*/").getDescription()); } public void testParseDesc9() throws Exception { String comment = "@desc\n.\n,\n{\n)\n}\n|\n.<\n>\n<\n?\n~\n+\n-\n;\n:\n*/"; assertEquals(". , { ) } | .< > < ? ~ + - ; :", parse(comment).getDescription()); } public void testParseDesc10() throws Exception { String comment = "@desc\n?\n?\n?\n?*/"; assertEquals("? ? ? ?", parse(comment).getDescription()); } public void testParseDesc11() throws Exception { String comment = "@desc :[]*/"; assertEquals(":[]", parse(comment).getDescription()); } public void testParseDesc12() throws Exception { String comment = "@desc\n:\n[\n]\n...*/"; assertEquals(": [ ] ...", parse(comment).getDescription()); } public void testParseMeaning1() throws Exception { assertEquals("tigers", parse("@meaning tigers */").getMeaning()); } public void testParseMeaning2() throws Exception { assertEquals("tigers and lions and bears", parse("@meaning tigers\n * and lions\n * and bears */").getMeaning()); } public void testParseMeaning3() throws Exception { JSDocInfo info = parse("@meaning tigers\n * and lions\n * @desc and bears */"); assertEquals("tigers and lions", info.getMeaning()); assertEquals("and bears", info.getDescription()); } public void testParseMeaning4() throws Exception { parse("@meaning tigers\n * @meaning and lions */", "extra @meaning tag"); } public void testParseLends1() throws Exception { JSDocInfo info = parse("@lends {name} */"); assertEquals("name", info.getLendsName()); } public void testParseLends2() throws Exception { JSDocInfo info = parse("@lends foo.bar */"); assertEquals("foo.bar", info.getLendsName()); } public void testParseLends3() throws Exception { parse("@lends {name */", "Bad type annotation. expected closing }"); } public void testParseLends4() throws Exception { parse("@lends {} */", "Bad type annotation. missing object name in @lends tag"); } public void testParseLends5() throws Exception { parse("@lends } */", "Bad type annotation. missing object name in @lends tag"); } public void testParseLends6() throws Exception { parse("@lends {string} \n * @lends {string} */", "Bad type annotation. @lends tag incompatible with other annotations"); } public void testParseLends7() throws Exception { parse("@type {string} \n * @lends {string} */", "Bad type annotation. @lends tag incompatible with other annotations"); } public void testStackedAnnotation() throws Exception { JSDocInfo info = parse("@const @type {string}*/"); assertTrue(info.isConstant()); assertTrue(info.hasType()); assertTypeEquals(STRING_TYPE, info.getType()); } public void testStackedAnnotation2() throws Exception { JSDocInfo info = parse("@type {string} @const */"); assertTrue(info.isConstant()); assertTrue(info.hasType()); assertTypeEquals(STRING_TYPE, info.getType()); } public void testStackedAnnotation3() throws Exception { JSDocInfo info = parse("@const @see {string}*/"); assertTrue(info.isConstant()); assertFalse(info.hasType()); } public void testStackedAnnotation4() throws Exception { JSDocInfo info = parse("@constructor @extends {Foo} @implements {Bar}*/"); assertTrue(info.isConstructor()); assertTrue(info.hasBaseType()); assertEquals(1, info.getImplementedInterfaceCount()); } public void testStackedAnnotation5() throws Exception { JSDocInfo info = parse("@param {number} x @constructor */"); assertTrue(info.hasParameterType("x")); assertTrue(info.isConstructor()); } public void testStackedAnnotation6() throws Exception { JSDocInfo info = parse("@return {number} @constructor */", true); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); info = parse("@return {number} @constructor */", false); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); } public void testStackedAnnotation7() throws Exception { JSDocInfo info = parse("@return @constructor */"); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); } public void testStackedAnnotation8() throws Exception { JSDocInfo info = parse("@throws {number} @constructor */", true); assertTrue(!info.getThrownTypes().isEmpty()); assertTrue(info.isConstructor()); info = parse("@return {number} @constructor */", false); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); } public void testParsePreserve() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@preserve Foo\nBar\n\nBaz*/"; parse(comment); assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense()); } public void testParseLicense() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@license Foo\nBar\n\nBaz*/"; parse(comment); assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense()); } public void testParseLicenseAscii() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@license Foo\n * Bar\n\n Baz*/"; parse(comment); assertEquals(" Foo\n Bar\n\n Baz", node.getJSDocInfo().getLicense()); } public void testParseLicenseWithAnnotation() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@license Foo \n * @author Charlie Brown */"; parse(comment); assertEquals(" Foo \n @author Charlie Brown ", node.getJSDocInfo().getLicense()); } public void testParseDefine1() throws Exception { assertTypeEquals(STRING_TYPE, parse("@define {string}*/").getType()); } public void testParseDefine2() throws Exception { assertTypeEquals(STRING_TYPE, parse("@define {string*/", "Bad type annotation. expected closing }").getType()); } public void testParseDefine3() throws Exception { JSDocInfo info = parse("@define {boolean}*/"); assertTrue(info.isConstant()); assertTrue(info.isDefine()); assertTypeEquals(BOOLEAN_TYPE, info.getType()); } public void testParseDefine4() throws Exception { assertTypeEquals(NUMBER_TYPE, parse("@define {number}*/").getType()); } public void testParseDefine5() throws Exception { assertTypeEquals(createUnionType(NUMBER_TYPE, BOOLEAN_TYPE), parse("@define {number|boolean}*/").getType()); } public void testParseDefineDescription() throws Exception { JSDocInfo doc = parse( "@define {string} description of element \n next line*/", true); Marker defineMarker = doc.getMarkers().iterator().next(); assertEquals("define", defineMarker.getAnnotation().getItem()); assertTrue(defineMarker.getDescription().getItem().contains("description of element")); assertTrue(defineMarker.getDescription().getItem().contains("next line")); } public void testParsePrivateDescription() throws Exception { JSDocInfo doc = parse("@private {string} description \n next line*/", true); Marker defineMarker = doc.getMarkers().iterator().next(); assertEquals("private", defineMarker.getAnnotation().getItem()); assertTrue(defineMarker.getDescription().getItem().contains("description ")); assertTrue(defineMarker.getDescription().getItem().contains("next line")); } public void testParseProtectedDescription() throws Exception { JSDocInfo doc = parse("@protected {string} description \n next line*/", true); Marker defineMarker = doc.getMarkers().iterator().next(); assertEquals("protected", defineMarker.getAnnotation().getItem()); assertTrue(defineMarker.getDescription().getItem().contains("description ")); assertTrue(defineMarker.getDescription().getItem().contains("next line")); } public void testParseDefineErrors1() throws Exception { parse("@enum {string}\n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors2() throws Exception { parse("@define {string}\n @enum {string} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testParseDefineErrors3() throws Exception { parse("@const\n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors4() throws Exception { parse("@type string \n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors5() throws Exception { parse("@return {string}\n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors7() throws Exception { parse("@define {string}\n @const */", "conflicting @const tag"); } public void testParseDefineErrors8() throws Exception { parse("@define {string}\n @type string */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testParseNoCheck1() throws Exception { assertTrue(parse("@notypecheck*/").isNoTypeCheck()); } public void testParseNoCheck2() throws Exception { parse("@notypecheck\n@notypecheck*/", "extra @notypecheck tag"); } public void testParseOverride1() throws Exception { assertTrue(parse("@override*/").isOverride()); } public void testParseOverride2() throws Exception { parse("@override\n@override*/", "Bad type annotation. extra @override/@inheritDoc tag"); } public void testParseInheritDoc1() throws Exception { assertTrue(parse("@inheritDoc*/").isOverride()); } public void testParseInheritDoc2() throws Exception { parse("@override\n@inheritDoc*/", "Bad type annotation. extra @override/@inheritDoc tag"); } public void testParseInheritDoc3() throws Exception { parse("@inheritDoc\n@inheritDoc*/", "Bad type annotation. extra @override/@inheritDoc tag"); } public void testParseNoAlias1() throws Exception { assertTrue(parse("@noalias*/").isNoAlias()); } public void testParseNoAlias2() throws Exception { parse("@noalias\n@noalias*/", "extra @noalias tag"); } public void testParseDeprecated1() throws Exception { assertTrue(parse("@deprecated*/").isDeprecated()); } public void testParseDeprecated2() throws Exception { parse("@deprecated\n@deprecated*/", "extra @deprecated tag"); } public void testParseExport1() throws Exception { assertTrue(parse("@export*/").isExport()); } public void testParseExport2() throws Exception { parse("@export\n@export*/", "extra @export tag"); } public void testParseExpose1() throws Exception { assertTrue(parse("@expose*/").isExpose()); } public void testParseExpose2() throws Exception { parse("@expose\n@expose*/", "extra @expose tag"); } public void testParseExterns1() throws Exception { assertTrue(parseFileOverview("@externs*/").isExterns()); } public void testParseExterns2() throws Exception { parseFileOverview("@externs\n@externs*/", "extra @externs tag"); } public void testParseExterns3() throws Exception { assertNull(parse("@externs*/")); } public void testParseJavaDispatch1() throws Exception { assertTrue(parse("@javadispatch*/").isJavaDispatch()); } public void testParseJavaDispatch2() throws Exception { parse("@javadispatch\n@javadispatch*/", "extra @javadispatch tag"); } public void testParseJavaDispatch3() throws Exception { assertNull(parseFileOverview("@javadispatch*/")); } public void testParseNoCompile1() throws Exception { assertTrue(parseFileOverview("@nocompile*/").isNoCompile()); } public void testParseNoCompile2() throws Exception { parseFileOverview("@nocompile\n@nocompile*/", "extra @nocompile tag"); } public void testBugAnnotation() throws Exception { parse("@bug */"); } public void testDescriptionAnnotation() throws Exception { parse("@description */"); } public void testRegression1() throws Exception { String comment = " * @param {number} index the index of blah\n" + " * @return {boolean} whatever\n" + " * @private\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); assertTypeEquals(BOOLEAN_TYPE, info.getReturnType()); assertEquals(Visibility.PRIVATE, info.getVisibility()); } public void testRegression2() throws Exception { String comment = " * @return {boolean} whatever\n" + " * but important\n" + " *\n" + " * @param {number} index the index of blah\n" + " * some more comments here\n" + " * @param name the name of the guy\n" + " *\n" + " * @protected\n" + " */"; JSDocInfo info = parse(comment); assertEquals(2, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); assertEquals(null, info.getParameterType("name")); assertTypeEquals(BOOLEAN_TYPE, info.getReturnType()); assertEquals(Visibility.PROTECTED, info.getVisibility()); } public void testRegression3() throws Exception { String comment = " * @param mediaTag this specified whether the @media tag is ....\n" + " *\n" + "\n" + "@public\n" + " *\n" + "\n" + " **********\n" + " * @final\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertEquals(null, info.getParameterType("mediaTag")); assertEquals(Visibility.PUBLIC, info.getVisibility()); assertTrue(info.isConstant()); } public void testRegression4() throws Exception { String comment = " * @const\n" + " * @hidden\n" + " * @preserveTry\n" + " * @constructor\n" + " */"; JSDocInfo info = parse(comment); assertTrue(info.isConstant()); assertFalse(info.isDefine()); assertTrue(info.isConstructor()); assertTrue(info.isHidden()); assertTrue(info.shouldPreserveTry()); } public void testRegression5() throws Exception { String comment = "@const\n@enum {string}\n@public*/"; JSDocInfo info = parse(comment); assertTrue(info.isConstant()); assertFalse(info.isDefine()); assertTypeEquals(STRING_TYPE, info.getEnumParameterType()); assertEquals(Visibility.PUBLIC, info.getVisibility()); } public void testRegression6() throws Exception { String comment = "@hidden\n@enum\n@public*/"; JSDocInfo info = parse(comment); assertTrue(info.isHidden()); assertTypeEquals(NUMBER_TYPE, info.getEnumParameterType()); assertEquals(Visibility.PUBLIC, info.getVisibility()); } public void testRegression7() throws Exception { String comment = " * @desc description here\n" + " * @param {boolean} flag and some more description\n" + " * nicely formatted\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag")); assertEquals("description here", info.getDescription()); } public void testRegression8() throws Exception { String comment = " * @name random tag here\n" + " * @desc description here\n" + " *\n" + " * @param {boolean} flag and some more description\n" + " * nicely formatted\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag")); assertEquals("description here", info.getDescription()); } public void testRegression9() throws Exception { JSDocInfo jsdoc = parse( " * @param {string} p0 blah blah blah\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(1, jsdoc.getParameterCount()); assertTypeEquals(STRING_TYPE, jsdoc.getParameterType("p0")); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression10() throws Exception { JSDocInfo jsdoc = parse( " * @param {!String} p0 blah blah blah\n" + " * @param {boolean} p1 fobar\n" + " * @return {!Date} jksjkash dshad\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(2, jsdoc.getParameterCount()); assertTypeEquals(STRING_OBJECT_TYPE, jsdoc.getParameterType("p0")); assertTypeEquals(BOOLEAN_TYPE, jsdoc.getParameterType("p1")); assertTypeEquals(DATE_TYPE, jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression11() throws Exception { JSDocInfo jsdoc = parse( " * @constructor\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression12() throws Exception { JSDocInfo jsdoc = parse( " * @extends FooBar\n" + " */"); assertTypeEquals(registry.createNamedType("FooBar", null, 0, 0), jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression13() throws Exception { JSDocInfo jsdoc = parse( " * @type {!RegExp}\n" + " * @protected\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertTypeEquals(REGEXP_TYPE, jsdoc.getType()); assertEquals(Visibility.PROTECTED, jsdoc.getVisibility()); } public void testRegression14() throws Exception { JSDocInfo jsdoc = parse( " * @const\n" + " * @private\n" + " */"); assertNull(jsdoc.getBaseType()); assertTrue(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.PRIVATE, jsdoc.getVisibility()); } public void testRegression15() throws Exception { JSDocInfo jsdoc = parse( " * @desc Hello,\n" + " * World!\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertEquals("Hello, World!", jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); assertFalse(jsdoc.isExport()); } public void testRegression16() throws Exception { JSDocInfo jsdoc = parse( " Email is plp@foo.bar\n" + " @type {string}\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertTypeEquals(STRING_TYPE, jsdoc.getType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression17() throws Exception { // verifying that if no @desc is present the description is empty assertNull(parse("@private*/").getDescription()); } public void testFullRegression1() throws Exception { parseFull("/** @param (string,number) foo*/function bar(foo){}", "Bad type annotation. expecting a variable name in a @param tag"); } public void testFullRegression2() throws Exception { parseFull("/** @param {string,number) foo*/function bar(foo){}", "Bad type annotation. expected closing }", "Bad type annotation. expecting a variable name in a @param tag"); } public void testFullRegression3() throws Exception { parseFull("/**..\n*/"); } public void testBug907488() throws Exception { parse("@type {number,null} */", "Bad type annotation. expected closing }"); } public void testBug907494() throws Exception { parse("@return {Object,undefined} */", "Bad type annotation. expected closing }"); } public void testBug909468() throws Exception { parse("@extends {(x)}*/", "Bad type annotation. expecting a type name"); } public void testParseInterface() throws Exception { assertTrue(parse("@interface*/").isInterface()); } public void testParseImplicitCast1() throws Exception { assertTrue(parse("@type {string} \n * @implicitCast*/").isImplicitCast()); } public void testParseImplicitCast2() throws Exception { assertFalse(parse("@type {string}*/").isImplicitCast()); } public void testParseDuplicateImplicitCast() throws Exception { parse("@type {string} \n * @implicitCast \n * @implicitCast*/", "Bad type annotation. extra @implicitCast tag"); } public void testParseInterfaceDoubled() throws Exception { parse( "* @interface\n" + "* @interface\n" + "*/", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testParseImplements() throws Exception { List<JSTypeExpression> interfaces = parse("@implements {SomeInterface}*/") .getImplementedInterfaces(); assertEquals(1, interfaces.size()); assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1), interfaces.get(0)); } public void testParseImplementsTwo() throws Exception { List<JSTypeExpression> interfaces = parse( "* @implements {SomeInterface1}\n" + "* @implements {SomeInterface2}\n" + "*/") .getImplementedInterfaces(); assertEquals(2, interfaces.size()); assertTypeEquals(registry.createNamedType("SomeInterface1", null, -1, -1), interfaces.get(0)); assertTypeEquals(registry.createNamedType("SomeInterface2", null, -1, -1), interfaces.get(1)); } public void testParseImplementsSameTwice() throws Exception { parse( "* @implements {Smth}\n" + "* @implements {Smth}\n" + "*/", "Bad type annotation. duplicate @implements tag"); } public void testParseImplementsNoName() throws Exception { parse("* @implements {} */", "Bad type annotation. expecting a type name"); } public void testParseImplementsMissingRC() throws Exception { parse("* @implements {Smth */", "Bad type annotation. expected closing }"); } public void testParseImplementsNullable1() throws Exception { parse("@implements {Base?} */", "Bad type annotation. expected closing }"); } public void testParseImplementsNullable2() throws Exception { parse("@implements Base? */", "Bad type annotation. expected end of line or comment"); } public void testInterfaceExtends() throws Exception { JSDocInfo jsdoc = parse( " * @interface \n" + " * @extends {Extended} */"); assertTrue(jsdoc.isInterface()); assertEquals(1, jsdoc.getExtendedInterfacesCount()); List<JSTypeExpression> types = jsdoc.getExtendedInterfaces(); assertTypeEquals(registry.createNamedType("Extended", null, -1, -1), types.get(0)); } public void testInterfaceMultiExtends1() throws Exception { JSDocInfo jsdoc = parse( " * @interface \n" + " * @extends {Extended1} \n" + " * @extends {Extended2} */"); assertTrue(jsdoc.isInterface()); assertNull(jsdoc.getBaseType()); assertEquals(2, jsdoc.getExtendedInterfacesCount()); List<JSTypeExpression> types = jsdoc.getExtendedInterfaces(); assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1), types.get(0)); assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1), types.get(1)); } public void testInterfaceMultiExtends2() throws Exception { JSDocInfo jsdoc = parse( " * @extends {Extended1} \n" + " * @interface \n" + " * @extends {Extended2} \n" + " * @extends {Extended3} */"); assertTrue(jsdoc.isInterface()); assertNull(jsdoc.getBaseType()); assertEquals(3, jsdoc.getExtendedInterfacesCount()); List<JSTypeExpression> types = jsdoc.getExtendedInterfaces(); assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1), types.get(0)); assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1), types.get(1)); assertTypeEquals(registry.createNamedType("Extended3", null, -1, -1), types.get(2)); } public void testBadClassMultiExtends() throws Exception { parse(" * @extends {Extended1} \n" + " * @constructor \n" + " * @extends {Extended2} */", "Bad type annotation. type annotation incompatible with other " + "annotations"); } public void testBadExtendsWithNullable() throws Exception { JSDocInfo jsdoc = parse("@constructor\n * @extends {Object?} */", "Bad type annotation. expected closing }"); assertTrue(jsdoc.isConstructor()); assertTypeEquals(OBJECT_TYPE, jsdoc.getBaseType()); } public void testBadImplementsWithNullable() throws Exception { JSDocInfo jsdoc = parse("@implements {Disposable?}\n * @constructor */", "Bad type annotation. expected closing }"); assertTrue(jsdoc.isConstructor()); assertTypeEquals(registry.createNamedType("Disposable", null, -1, -1), jsdoc.getImplementedInterfaces().get(0)); } public void testBadTypeDefInterfaceAndConstructor1() throws Exception { JSDocInfo jsdoc = parse("@interface\n@constructor*/", "Bad type annotation. cannot be both an interface and a constructor"); assertTrue(jsdoc.isInterface()); } public void testBadTypeDefInterfaceAndConstructor2() throws Exception { JSDocInfo jsdoc = parse("@constructor\n@interface*/", "Bad type annotation. cannot be both an interface and a constructor"); assertTrue(jsdoc.isConstructor()); } public void testDocumentationParameter() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description.*/", true); assertTrue(jsdoc.hasDescriptionForParameter("number42")); assertEquals("This is a description.", jsdoc.getDescriptionForParameter("number42")); } public void testMultilineDocumentationParameter() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description" + "\n* on multiple \n* lines.*/", true); assertTrue(jsdoc.hasDescriptionForParameter("number42")); assertEquals("This is a description on multiple lines.", jsdoc.getDescriptionForParameter("number42")); } public void testDocumentationMultipleParameter() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description." + "\n* @param {Integer} number87 This is another description.*/" , true); assertTrue(jsdoc.hasDescriptionForParameter("number42")); assertEquals("This is a description.", jsdoc.getDescriptionForParameter("number42")); assertTrue(jsdoc.hasDescriptionForParameter("number87")); assertEquals("This is another description.", jsdoc.getDescriptionForParameter("number87")); } public void testDocumentationMultipleParameter2() throws Exception { JSDocInfo jsdoc = parse("@param {number} delta = 0 results in a redraw\n" + " != 0 ..... */", true); assertTrue(jsdoc.hasDescriptionForParameter("delta")); assertEquals("= 0 results in a redraw != 0 .....", jsdoc.getDescriptionForParameter("delta")); } public void testAuthors() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description." + "\n* @param {Integer} number87 This is another description." + "\n* @author a@google.com (A Person)" + "\n* @author b@google.com (B Person)" + "\n* @author c@google.com (C Person)*/" , true); Collection<String> authors = jsdoc.getAuthors(); assertTrue(authors != null); assertTrue(authors.size() == 3); assertContains(authors, "a@google.com (A Person)"); assertContains(authors, "b@google.com (B Person)"); assertContains(authors, "c@google.com (C Person)"); } public void testSuppress1() throws Exception { JSDocInfo info = parse("@suppress {x} */"); assertEquals(Sets.newHashSet("x"), info.getSuppressions()); } public void testSuppress2() throws Exception { JSDocInfo info = parse("@suppress {x|y|x|z} */"); assertEquals(Sets.newHashSet("x", "y", "z"), info.getSuppressions()); } public void testSuppress3() throws Exception { JSDocInfo info = parse("@suppress {x,y} */"); assertEquals(Sets.newHashSet("x", "y"), info.getSuppressions()); } public void testBadSuppress1() throws Exception { parse("@suppress {} */", "malformed @suppress tag"); } public void testBadSuppress2() throws Exception { parse("@suppress {x|} */", "malformed @suppress tag"); } public void testBadSuppress3() throws Exception { parse("@suppress {|x} */", "malformed @suppress tag"); } public void testBadSuppress4() throws Exception { parse("@suppress {x|y */", "malformed @suppress tag"); } public void testBadSuppress6() throws Exception { parse("@suppress {x} \n * @suppress {y} */", "duplicate @suppress tag"); } public void testBadSuppress7() throws Exception { parse("@suppress {impossible} */", "unknown @suppress parameter: impossible"); } public void testModifies1() throws Exception { JSDocInfo info = parse("@modifies {this} */"); assertEquals(Sets.newHashSet("this"), info.getModifies()); } public void testModifies2() throws Exception { JSDocInfo info = parse("@modifies {arguments} */"); assertEquals(Sets.newHashSet("arguments"), info.getModifies()); } public void testModifies3() throws Exception { JSDocInfo info = parse("@modifies {this|arguments} */"); assertEquals(Sets.newHashSet("this", "arguments"), info.getModifies()); } public void testModifies4() throws Exception { JSDocInfo info = parse("@param {*} x\n * @modifies {x} */"); assertEquals(Sets.newHashSet("x"), info.getModifies()); } public void testModifies5() throws Exception { JSDocInfo info = parse( "@param {*} x\n" + " * @param {*} y\n" + " * @modifies {x} */"); assertEquals(Sets.newHashSet("x"), info.getModifies()); } public void testModifies6() throws Exception { JSDocInfo info = parse( "@param {*} x\n" + " * @param {*} y\n" + " * @modifies {x|y} */"); assertEquals(Sets.newHashSet("x", "y"), info.getModifies()); } public void testBadModifies1() throws Exception { parse("@modifies {} */", "malformed @modifies tag"); } public void testBadModifies2() throws Exception { parse("@modifies {this|} */", "malformed @modifies tag"); } public void testBadModifies3() throws Exception { parse("@modifies {|this} */", "malformed @modifies tag"); } public void testBadModifies4() throws Exception { parse("@modifies {this|arguments */", "malformed @modifies tag"); } public void testBadModifies5() throws Exception { parse("@modifies {this,arguments} */", "malformed @modifies tag"); } public void testBadModifies6() throws Exception { parse("@modifies {this} \n * @modifies {this} */", "conflicting @modifies tag"); } public void testBadModifies7() throws Exception { parse("@modifies {impossible} */", "unknown @modifies parameter: impossible"); } public void testBadModifies8() throws Exception { parse("@modifies {this}\n" + "@nosideeffects */", "conflicting @nosideeffects tag"); } public void testBadModifies9() throws Exception { parse("@nosideeffects\n" + "@modifies {this} */", "conflicting @modifies tag"); } //public void testNoParseFileOverview() throws Exception { // JSDocInfo jsdoc = parseFileOverviewWithoutDoc("@fileoverview Hi mom! */"); // assertNull(jsdoc.getFileOverview()); // assertTrue(jsdoc.hasFileOverview()); //} public void testFileOverviewSingleLine() throws Exception { JSDocInfo jsdoc = parseFileOverview("@fileoverview Hi mom! */"); assertEquals("Hi mom!", jsdoc.getFileOverview()); } public void testFileOverviewMultiLine() throws Exception { JSDocInfo jsdoc = parseFileOverview("@fileoverview Pie is \n * good! */"); assertEquals("Pie is\n good!", jsdoc.getFileOverview()); } public void testFileOverviewDuplicate() throws Exception { parseFileOverview( "@fileoverview Pie \n * @fileoverview Cake */", "extra @fileoverview tag"); } public void testReferences() throws Exception { JSDocInfo jsdoc = parse("@see A cool place!" + "\n* @see The world." + "\n* @see SomeClass#SomeMember" + "\n* @see A boring test case*/" , true); Collection<String> references = jsdoc.getReferences(); assertTrue(references != null); assertTrue(references.size() == 4); assertContains(references, "A cool place!"); assertContains(references, "The world."); assertContains(references, "SomeClass#SomeMember"); assertContains(references, "A boring test case"); } public void testSingleTags() throws Exception { JSDocInfo jsdoc = parse("@version Some old version" + "\n* @deprecated In favor of the new one!" + "\n* @return {SomeType} The most important object :-)*/" , true); assertTrue(jsdoc.isDeprecated()); assertEquals("In favor of the new one!", jsdoc.getDeprecationReason()); assertEquals("Some old version", jsdoc.getVersion()); assertEquals("The most important object :-)", jsdoc.getReturnDescription()); } public void testSingleTags2() throws Exception { JSDocInfo jsdoc = parse( "@param {SomeType} a The most important object :-)*/", true); assertEquals("The most important object :-)", jsdoc.getDescriptionForParameter("a")); } public void testSingleTagsReordered() throws Exception { JSDocInfo jsdoc = parse("@deprecated In favor of the new one!" + "\n * @return {SomeType} The most important object :-)" + "\n * @version Some old version*/" , true); assertTrue(jsdoc.isDeprecated()); assertEquals("In favor of the new one!", jsdoc.getDeprecationReason()); assertEquals("Some old version", jsdoc.getVersion()); assertEquals("The most important object :-)", jsdoc.getReturnDescription()); } public void testVersionDuplication() throws Exception { parse("* @version Some old version" + "\n* @version Another version*/", true, "conflicting @version tag"); } public void testVersionMissing() throws Exception { parse("* @version */", true, "@version tag missing version information"); } public void testAuthorMissing() throws Exception { parse("* @author */", true, "@author tag missing author"); } public void testSeeMissing() throws Exception { parse("* @see */", true, "@see tag missing description"); } public void testSourceName() throws Exception { JSDocInfo jsdoc = parse("@deprecated */", true); assertEquals("testcode", jsdoc.getAssociatedNode().getSourceFileName()); } public void testParseBlockComment() throws Exception { JSDocInfo jsdoc = parse("this is a nice comment\n " + "* that is multiline \n" + "* @author abc@google.com */", true); assertEquals("this is a nice comment\nthat is multiline", jsdoc.getBlockDescription()); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 2, 2), "abc@google.com", 9, 2, 23); } public void testParseBlockComment2() throws Exception { JSDocInfo jsdoc = parse("this is a nice comment\n " + "* that is *** multiline \n" + "* @author abc@google.com */", true); assertEquals("this is a nice comment\nthat is *** multiline", jsdoc.getBlockDescription()); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 2, 2), "abc@google.com", 9, 2, 23); } public void testParseBlockComment3() throws Exception { JSDocInfo jsdoc = parse("\n " + "* hello world \n" + "* @author abc@google.com */", true); assertEquals("hello world", jsdoc.getBlockDescription()); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 2, 2), "abc@google.com", 9, 2, 23); } public void testParseWithMarkers1() throws Exception { JSDocInfo jsdoc = parse("@author abc@google.com */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 0, 0), "abc@google.com", 7, 0, 21); } public void testParseWithMarkers2() throws Exception { JSDocInfo jsdoc = parse("@param {Foo} somename abc@google.com */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0), "abc@google.com", 21, 0, 37); } public void testParseWithMarkers3() throws Exception { JSDocInfo jsdoc = parse("@return {Foo} some long \n * multiline" + " \n * description */", true); JSDocInfo.Marker returnDoc = assertAnnotationMarker(jsdoc, "return", 0, 0); assertDocumentationInMarker(returnDoc, "some long multiline description", 14, 2, 15); assertEquals(8, returnDoc.getType().getPositionOnStartLine()); assertEquals(12, returnDoc.getType().getPositionOnEndLine()); } public void testParseWithMarkers4() throws Exception { JSDocInfo jsdoc = parse("@author foobar \n * @param {Foo} somename abc@google.com */", true); assertAnnotationMarker(jsdoc, "author", 0, 0); assertAnnotationMarker(jsdoc, "param", 1, 3); } public void testParseWithMarkers5() throws Exception { JSDocInfo jsdoc = parse("@return some long \n * multiline" + " \n * description */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "return", 0, 0), "some long multiline description", 8, 2, 15); } public void testParseWithMarkers6() throws Exception { JSDocInfo jsdoc = parse("@param x some long \n * multiline" + " \n * description */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0), "some long multiline description", 8, 2, 15); } public void testParseWithMarkerNames1() throws Exception { JSDocInfo jsdoc = parse("@param {SomeType} name somedescription */", true); assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0), "name", 0, 18); } public void testParseWithMarkerNames2() throws Exception { JSDocInfo jsdoc = parse("@param {SomeType} name somedescription \n" + "* @param {AnotherType} anothername des */", true); assertTypeInMarker( assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0, 0), "name", 0, 18), "SomeType", 0, 7, 0, 16, true); assertTypeInMarker( assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 1, 2, 1), "anothername", 1, 23), "AnotherType", 1, 9, 1, 21, true); } public void testParseWithMarkerNames3() throws Exception { JSDocInfo jsdoc = parse( "@param {Some.Long.Type.\n * Name} name somedescription */", true); assertTypeInMarker( assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0, 0), "name", 1, 10), "Some.Long.Type.Name", 0, 7, 1, 8, true); } @SuppressWarnings("deprecation") public void testParseWithoutMarkerName() throws Exception { JSDocInfo jsdoc = parse("@author helloworld*/", true); assertNull(assertAnnotationMarker(jsdoc, "author", 0, 0).getName()); } public void testParseWithMarkerType() throws Exception { JSDocInfo jsdoc = parse("@extends {FooBar}*/", true); assertTypeInMarker( assertAnnotationMarker(jsdoc, "extends", 0, 0), "FooBar", 0, 9, 0, 16, true); } public void testParseWithMarkerType2() throws Exception { JSDocInfo jsdoc = parse("@extends FooBar*/", true); assertTypeInMarker( assertAnnotationMarker(jsdoc, "extends", 0, 0), "FooBar", 0, 9, 0, 15, false); } public void testTypeTagConflict1() throws Exception { parse("@constructor \n * @constructor */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict2() throws Exception { parse("@interface \n * @interface */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict3() throws Exception { parse("@constructor \n * @interface */", "Bad type annotation. cannot be both an interface and a constructor"); } public void testTypeTagConflict4() throws Exception { parse("@interface \n * @constructor */", "Bad type annotation. cannot be both an interface and a constructor"); } public void testTypeTagConflict5() throws Exception { parse("@interface \n * @type {string} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict6() throws Exception { parse("@typedef {string} \n * @type {string} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict7() throws Exception { parse("@typedef {string} \n * @constructor */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict8() throws Exception { parse("@typedef {string} \n * @return {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict9() throws Exception { parse("@enum {string} \n * @return {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict10() throws Exception { parse("@this {Object} \n * @enum {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict11() throws Exception { parse("@param {Object} x \n * @type {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict12() throws Exception { parse("@typedef {boolean} \n * @param {Object} x */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict13() throws Exception { parse("@typedef {boolean} \n * @extends {Object} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict14() throws Exception { parse("@return x \n * @return y */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict15() throws Exception { parse("/**\n" + " * @struct\n" + " * @struct\n" + " */\n" + "function StrStr() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict16() throws Exception { parse("/**\n" + " * @struct\n" + " * @interface\n" + " */\n" + "function StrIntf() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict17() throws Exception { parse("/**\n" + " * @interface\n" + " * @struct\n" + " */\n" + "function StrIntf() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict18() throws Exception { parse("/**\n" + " * @dict\n" + " * @dict\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict19() throws Exception { parse("/**\n" + " * @dict\n" + " * @interface\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict20() throws Exception { parse("/**\n" + " * @interface\n" + " * @dict\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict21() throws Exception { parse("/**\n" + " * @private {string}\n" + " * @type {number}\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict22() throws Exception { parse("/**\n" + " * @protected {string}\n" + " * @param {string} x\n" + " */\n" + "function DictDict(x) {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict23() throws Exception { parse("/**\n" + " * @public {string}\n" + " * @return {string} x\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict24() throws Exception { parse("/**\n" + " * @const {string}\n" + " * @return {string} x\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testPrivateType() throws Exception { JSDocInfo jsdoc = parse("@private {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testProtectedType() throws Exception { JSDocInfo jsdoc = parse("@protected {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testPublicType() throws Exception { JSDocInfo jsdoc = parse("@public {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testConstType() throws Exception { JSDocInfo jsdoc = parse("@const {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testStableIdGeneratorConflict() throws Exception { parse("/**\n" + " * @stableIdGenerator\n" + " * @stableIdGenerator\n" + " */\n" + "function getId() {}", "extra @stableIdGenerator tag"); } public void testIdGenerator() throws Exception { JSDocInfo info = parse("/**\n" + " * @idGenerator\n" + " */\n" + "function getId() {}"); assertTrue(info.isIdGenerator()); } public void testIdGeneratorConflict() throws Exception { parse("/**\n" + " * @idGenerator\n" + " * @idGenerator\n" + " */\n" + "function getId() {}", "extra @idGenerator tag"); } public void testIdGenerator1() throws Exception { JSDocInfo info = parse("@idGenerator {unique} */"); assertTrue(info.isIdGenerator()); } public void testIdGenerator2() throws Exception { JSDocInfo info = parse("@idGenerator {consistent} */"); assertTrue(info.isConsistentIdGenerator()); } public void testIdGenerator3() throws Exception { JSDocInfo info = parse("@idGenerator {stable} */"); assertTrue(info.isStableIdGenerator()); } public void testIdGenerator4() throws Exception { JSDocInfo info = parse("@idGenerator {mapped} */"); assertTrue(info.isMappedIdGenerator()); } public void testBadIdGenerator1() throws Exception { parse("@idGenerator {} */", "malformed @idGenerator tag"); } public void testBadIdGenerator2() throws Exception { parse("@idGenerator {impossible} */", "unknown @idGenerator parameter: impossible"); } public void testBadIdGenerator3() throws Exception { parse("@idGenerator {unique */", "malformed @idGenerator tag"); } public void testParserWithTemplateTypeNameMissing() { parse("@template */", "Bad type annotation. @template tag missing type name"); } public void testParserWithTemplateDuplicated() { parse("@template T\n@template V */", "Bad type annotation. @template tag at most once"); } public void testParserWithTwoTemplates() { parse("@template T,V */"); } public void testWhitelistedNewAnnotations() { parse("@foobar */", "illegal use of unknown JSDoc tag \"foobar\"; ignoring it"); extraAnnotations.add("foobar"); parse("@foobar */"); } public void testWhitelistedConflictingAnnotation() { extraAnnotations.add("param"); JSDocInfo info = parse("@param {number} index */"); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testNonIdentifierAnnotation() { // Try to whitelist an annotation that is not a valid JS identifier. // It should not work. extraAnnotations.add("123"); parse("@123 */", "illegal use of unknown JSDoc tag \"\"; ignoring it"); } public void testUnsupportedJsDocSyntax1() { JSDocInfo info = parse("@param {string} [accessLevel=\"author\"] The user level */", true); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("accessLevel")); assertEquals("The user level", info.getDescriptionForParameter("accessLevel")); } public void testUnsupportedJsDocSyntax2() { JSDocInfo info = parse("@param userInfo The user info. \n" + " * @param userInfo.name The name of the user */", true); assertEquals(1, info.getParameterCount()); assertEquals("The user info.", info.getDescriptionForParameter("userInfo")); } public void testWhitelistedAnnotations() { parse( "* @addon \n" + "* @augments \n" + "* @base \n" + "* @borrows \n" + "* @bug \n" + "* @class \n" + "* @config \n" + "* @constructs \n" + "* @default \n" + "* @description \n" + "* @enhance \n" + "* @enhanceable \n" + "* @event \n" + "* @example \n" + "* @exception \n" + "* @exec \n" + "* @externs \n" + "* @field \n" + "* @function \n" + "* @hassoydelcall \n" + "* @hassoydeltemplate \n" + "* @id \n" + "* @ignore \n" + "* @inner \n" + "* @jaggerInject \n" + "* @jaggerModule \n" + "* @jaggerProvide \n" + "* @lends {string} \n" + "* @link \n" + "* @member \n" + "* @memberOf \n" + "* @modName \n" + "* @mods \n" + "* @name \n" + "* @namespace \n" + "* @ngInject \n" + "* @nocompile \n" + "* @property \n" + "* @requirecss \n" + "* @requires \n" + "* @since \n" + "* @static \n" + "* @supported\n" + "* @wizaction \n" + "* @wizmodule \n" + "*/"); } public void testJsDocInfoPosition() throws IOException { SourceFile sourceFile = SourceFile.fromCode("comment-position-test.js", " \n" + " /**\n" + " * A comment\n" + " */\n" + " function double(x) {}"); List<JSDocInfo> jsdocs = parseFull(sourceFile.getCode()); assertEquals(1, jsdocs.size()); assertEquals(6, jsdocs.get(0).getOriginalCommentPosition()); assertEquals(2, sourceFile.getLineOfOffset(jsdocs.get(0).getOriginalCommentPosition())); assertEquals(2, sourceFile.getColumnOfOffset(jsdocs.get(0).getOriginalCommentPosition())); } public void testGetOriginalCommentString() throws Exception { String comment = "* @desc This is a comment */"; JSDocInfo info = parse(comment); assertNull(info.getOriginalCommentString()); info = parse(comment, true /* parseDocumentation */); assertEquals(comment, info.getOriginalCommentString()); } public void testParseNgInject1() throws Exception { assertTrue(parse("@ngInject*/").isNgInject()); } public void testParseNgInject2() throws Exception { parse("@ngInject \n@ngInject*/", "extra @ngInject tag"); } public void testParseJaggerInject() throws Exception { assertTrue(parse("@jaggerInject*/").isJaggerInject()); } public void testParseJaggerInjectExtra() throws Exception { parse("@jaggerInject \n@jaggerInject*/", "extra @jaggerInject tag"); } public void testParseJaggerModule() throws Exception { assertTrue(parse("@jaggerModule*/").isJaggerModule()); } public void testParseJaggerModuleExtra() throws Exception { parse("@jaggerModule \n@jaggerModule*/", "extra @jaggerModule tag"); } public void testParseJaggerProvide() throws Exception { assertTrue(parse("@jaggerProvide*/").isJaggerProvide()); } public void testParseJaggerProvideExtra() throws Exception { parse("@jaggerProvide \n@jaggerProvide*/", "extra @jaggerProvide tag"); } public void testParseWizaction1() throws Exception { assertTrue(parse("@wizaction*/").isWizaction()); } public void testParseWizaction2() throws Exception { parse("@wizaction \n@wizaction*/", "extra @wizaction tag"); } public void testParseDisposes1() throws Exception { assertTrue(parse("@param x \n * @disposes x */").isDisposes()); } public void testParseDisposes2() throws Exception { parse("@param x \n * @disposes */", true, "Bad type annotation. @disposes tag missing parameter name"); } public void testParseDisposes3() throws Exception { assertTrue(parse("@param x \n @param y\n * @disposes x, y */").isDisposes()); } public void testParseDisposesUnknown() throws Exception { parse("@param x \n * @disposes x,y */", true, "Bad type annotation. @disposes parameter unknown or parameter specified multiple times"); } public void testParseDisposesMultiple() throws Exception { parse("@param x \n * @disposes x,x */", true, "Bad type annotation. @disposes parameter unknown or parameter specified multiple times"); } public void testParseDisposesAll1() throws Exception { assertTrue(parse("@param x \n * @disposes * */").isDisposes()); } public void testParseDisposesAll2() throws Exception { assertTrue(parse("@param x \n * @disposes x,* */").isDisposes()); } public void testParseDisposesAll3() throws Exception { parse("@param x \n * @disposes *, * */", true, "Bad type annotation. @disposes parameter unknown or parameter specified multiple times"); } public void testTextExtents() { parse("@return {@code foo} bar \n * baz. */", true, "Bad type annotation. type not recognized due to syntax error"); } /** * Asserts that a documentation field exists on the given marker. * * @param description The text of the documentation field expected. * @param startCharno The starting character of the text. * @param endLineno The ending line of the text. * @param endCharno The ending character of the text. * @return The marker, for chaining purposes. */ private JSDocInfo.Marker assertDocumentationInMarker(JSDocInfo.Marker marker, String description, int startCharno, int endLineno, int endCharno) { assertTrue(marker.getDescription() != null); assertEquals(description, marker.getDescription().getItem()); // Match positional information. assertEquals(marker.getAnnotation().getStartLine(), marker.getDescription().getStartLine()); assertEquals(startCharno, marker.getDescription().getPositionOnStartLine()); assertEquals(endLineno, marker.getDescription().getEndLine()); assertEquals(endCharno, marker.getDescription().getPositionOnEndLine()); return marker; } /** * Asserts that a type field exists on the given marker. * * @param typeName The name of the type expected in the type field. * @param startCharno The starting character of the type declaration. * @param hasBrackets Whether the type in the type field is expected * to have brackets. * @return The marker, for chaining purposes. */ private JSDocInfo.Marker assertTypeInMarker( JSDocInfo.Marker marker, String typeName, int startLineno, int startCharno, int endLineno, int endCharno, boolean hasBrackets) { assertTrue(marker.getType() != null); assertTrue(marker.getType().getItem().isString()); // Match the name and brackets information. String foundName = marker.getType().getItem().getString(); assertEquals(typeName, foundName); assertEquals(hasBrackets, marker.getType().hasBrackets()); // Match position information. assertEquals(startCharno, marker.getType().getPositionOnStartLine()); assertEquals(endCharno, marker.getType().getPositionOnEndLine()); assertEquals(startLineno, marker.getType().getStartLine()); assertEquals(endLineno, marker.getType().getEndLine()); return marker; } /** * Asserts that a name field exists on the given marker. * * @param name The name expected in the name field. * @param startCharno The starting character of the text. * @return The marker, for chaining purposes. */ @SuppressWarnings("deprecation") private JSDocInfo.Marker assertNameInMarker(JSDocInfo.Marker marker, String name, int startLine, int startCharno) { assertTrue(marker.getName() != null); assertEquals(name, marker.getName().getItem()); assertEquals(startCharno, marker.getName().getPositionOnStartLine()); assertEquals(startCharno + name.length(), marker.getName().getPositionOnEndLine()); assertEquals(startLine, marker.getName().getStartLine()); assertEquals(startLine, marker.getName().getEndLine()); return marker; } /** * Asserts that an annotation marker of a given annotation name * is found in the given JSDocInfo. * * @param jsdoc The JSDocInfo in which to search for the annotation marker. * @param annotationName The name/type of the annotation for which to * search. Example: "author" for an "@author" annotation. * @param startLineno The expected starting line number of the marker. * @param startCharno The expected character on the starting line. * @return The marker found, for further testing. */ private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc, String annotationName, int startLineno, int startCharno) { return assertAnnotationMarker(jsdoc, annotationName, startLineno, startCharno, 0); } /** * Asserts that the index-th annotation marker of a given annotation name * is found in the given JSDocInfo. * * @param jsdoc The JSDocInfo in which to search for the annotation marker. * @param annotationName The name/type of the annotation for which to * search. Example: "author" for an "@author" annotation. * @param startLineno The expected starting line number of the marker. * @param startCharno The expected character on the starting line. * @param index The index of the marker. * @return The marker found, for further testing. */ private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc, String annotationName, int startLineno, int startCharno, int index) { Collection<JSDocInfo.Marker> markers = jsdoc.getMarkers(); assertTrue(markers.size() > 0); int counter = 0; for (JSDocInfo.Marker marker : markers) { if (marker.getAnnotation() != null) { if (annotationName.equals(marker.getAnnotation().getItem())) { if (counter == index) { assertEquals(startLineno, marker.getAnnotation().getStartLine()); assertEquals(startCharno, marker.getAnnotation().getPositionOnStartLine()); assertEquals(startLineno, marker.getAnnotation().getEndLine()); assertEquals(startCharno + annotationName.length(), marker.getAnnotation().getPositionOnEndLine()); return marker; } counter++; } } } fail("No marker found"); return null; } private <T> void assertContains(Collection<T> collection, T item) { assertTrue(collection.contains(item)); } private List<JSDocInfo> parseFull(String code, String... warnings) { CompilerEnvirons environment = new CompilerEnvirons(); TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings); environment.setErrorReporter(testErrorReporter); environment.setRecordingComments(true); environment.setRecordingLocalJsDocComments(true); Parser p = new Parser(environment, testErrorReporter); AstRoot script = p.parse(code, null, 0); Config config = new Config(extraAnnotations, extraSuppressions, true, LanguageMode.ECMASCRIPT3, false); List<JSDocInfo> jsdocs = Lists.newArrayList(); for (Comment comment : script.getComments()) { JsDocInfoParser jsdocParser = new JsDocInfoParser( new JsDocTokenStream(comment.getValue().substring(3), comment.getLineno()), comment, null, config, testErrorReporter); jsdocParser.parse(); jsdocs.add(jsdocParser.retrieveAndResetParsedJSDocInfo()); } assertTrue("some expected warnings were not reported", testErrorReporter.hasEncounteredAllWarnings()); return jsdocs; } @SuppressWarnings("unused") private JSDocInfo parseFileOverviewWithoutDoc(String comment, String... warnings) { return parse(comment, false, true, warnings); } private JSDocInfo parseFileOverview(String comment, String... warnings) { return parse(comment, true, true, warnings); } private JSDocInfo parse(String comment, String... warnings) { return parse(comment, false, warnings); } private JSDocInfo parse(String comment, boolean parseDocumentation, String... warnings) { return parse(comment, parseDocumentation, false, warnings); } private JSDocInfo parse(String comment, boolean parseDocumentation, boolean parseFileOverview, String... warnings) { TestErrorReporter errorReporter = new TestErrorReporter(null, warnings); Config config = new Config(extraAnnotations, extraSuppressions, parseDocumentation, LanguageMode.ECMASCRIPT3, false); StaticSourceFile file = new SimpleSourceFile("testcode", false); Node associatedNode = new Node(Token.SCRIPT); associatedNode.setInputId(new InputId(file.getName())); associatedNode.setStaticSourceFile(file); JsDocInfoParser jsdocParser = new JsDocInfoParser( stream(comment), new Comment(0, 0, CommentType.JSDOC, comment), associatedNode, config, errorReporter); if (fileLevelJsDocBuilder != null) { jsdocParser.setFileLevelJsDocBuilder(fileLevelJsDocBuilder); } jsdocParser.parse(); assertTrue("expected warnings were not reported", errorReporter.hasEncounteredAllWarnings()); if (parseFileOverview) { return jsdocParser.getFileOverviewJSDocInfo(); } else { return jsdocParser.retrieveAndResetParsedJSDocInfo(); } } private Node parseType(String typeComment) { return JsDocInfoParser.parseTypeString(typeComment); } private JsDocTokenStream stream(String source) { return new JsDocTokenStream(source, 0); } private void assertTemplatizedTypeEquals(TemplateType key, JSType expected, JSTypeExpression te) { assertEquals( expected, resolve(te).getTemplateTypeMap().getTemplateType(key)); } }
// You are a professional Java test case writer, please create a test case named `testStructuralConstructor2` for the issue `Closure-1105`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1105 // // ## Issue-Title: // Constructor types that return all or unknown fail to parse // // ## Issue-Description: // Constructor types that return the all type or the unknown type currently fail to parse: // // /\*\* @type {function(new:?)} \*/ var foo = function() {}; // /\*\* @type {function(new:\*)} \*/ var bar = function() {}; // // foo.js:1: ERROR - Bad type annotation. type not recognized due to syntax error // /\*\* @type {function(new:?)} \*/ var foo = function() {}; // ^ // // foo.js:2: ERROR - Bad type annotation. type not recognized due to syntax error // /\*\* @type {function(new:\*)} \*/ var bar = function() {}; // ^ // // This is an issue for a code generator that I'm working on. // // public void testStructuralConstructor2() throws Exception {
590
109
583
test/com/google/javascript/jscomp/parsing/JsDocInfoParserTest.java
test
```markdown ## Issue-ID: Closure-1105 ## Issue-Title: Constructor types that return all or unknown fail to parse ## Issue-Description: Constructor types that return the all type or the unknown type currently fail to parse: /\*\* @type {function(new:?)} \*/ var foo = function() {}; /\*\* @type {function(new:\*)} \*/ var bar = function() {}; foo.js:1: ERROR - Bad type annotation. type not recognized due to syntax error /\*\* @type {function(new:?)} \*/ var foo = function() {}; ^ foo.js:2: ERROR - Bad type annotation. type not recognized due to syntax error /\*\* @type {function(new:\*)} \*/ var bar = function() {}; ^ This is an issue for a code generator that I'm working on. ``` You are a professional Java test case writer, please create a test case named `testStructuralConstructor2` for the issue `Closure-1105`, utilizing the provided issue report information and the following function signature. ```java public void testStructuralConstructor2() throws Exception { ```
583
[ "com.google.javascript.jscomp.parsing.JsDocInfoParser" ]
ef05e7088ae3c867d80c5e864e5d9e0b050b6a4aba5204b1f8bb6120d6c595d9
public void testStructuralConstructor2() throws Exception
// You are a professional Java test case writer, please create a test case named `testStructuralConstructor2` for the issue `Closure-1105`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1105 // // ## Issue-Title: // Constructor types that return all or unknown fail to parse // // ## Issue-Description: // Constructor types that return the all type or the unknown type currently fail to parse: // // /\*\* @type {function(new:?)} \*/ var foo = function() {}; // /\*\* @type {function(new:\*)} \*/ var bar = function() {}; // // foo.js:1: ERROR - Bad type annotation. type not recognized due to syntax error // /\*\* @type {function(new:?)} \*/ var foo = function() {}; // ^ // // foo.js:2: ERROR - Bad type annotation. type not recognized due to syntax error // /\*\* @type {function(new:\*)} \*/ var bar = function() {}; // ^ // // This is an issue for a code generator that I'm working on. // //
Closure
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.parsing; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.SourceFile; import com.google.javascript.jscomp.parsing.Config.LanguageMode; import com.google.javascript.jscomp.testing.TestErrorReporter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Marker; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.JSTypeExpression; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.head.CompilerEnvirons; import com.google.javascript.rhino.head.Parser; import com.google.javascript.rhino.head.Token.CommentType; import com.google.javascript.rhino.head.ast.AstRoot; import com.google.javascript.rhino.head.ast.Comment; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.jstype.SimpleSourceFile; import com.google.javascript.rhino.jstype.StaticSourceFile; import com.google.javascript.rhino.jstype.TemplateType; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Set; public class JsDocInfoParserTest extends BaseJSTypeTestCase { private Set<String> extraAnnotations; private Set<String> extraSuppressions; private Node.FileLevelJsDocBuilder fileLevelJsDocBuilder = null; @Override public void setUp() throws Exception { super.setUp(); extraAnnotations = Sets.newHashSet( ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false) .annotationNames.keySet()); extraSuppressions = Sets.newHashSet( ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false) .suppressionNames); extraSuppressions.add("x"); extraSuppressions.add("y"); extraSuppressions.add("z"); } public void testParseTypeViaStatic1() throws Exception { Node typeNode = parseType("null"); assertTypeEquals(NULL_TYPE, typeNode); } public void testParseTypeViaStatic2() throws Exception { Node typeNode = parseType("string"); assertTypeEquals(STRING_TYPE, typeNode); } public void testParseTypeViaStatic3() throws Exception { Node typeNode = parseType("!Date"); assertTypeEquals(DATE_TYPE, typeNode); } public void testParseTypeViaStatic4() throws Exception { Node typeNode = parseType("boolean|string"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, STRING_TYPE), typeNode); } public void testParseInvalidTypeViaStatic() throws Exception { Node typeNode = parseType("sometype.<anothertype"); assertNull(typeNode); } public void testParseInvalidTypeViaStatic2() throws Exception { Node typeNode = parseType(""); assertNull(typeNode); } public void testParseNamedType1() throws Exception { assertNull(parse("@type null", "Unexpected end of file")); } public void testParseNamedType2() throws Exception { JSDocInfo info = parse("@type null*/"); assertTypeEquals(NULL_TYPE, info.getType()); } public void testParseNamedType3() throws Exception { JSDocInfo info = parse("@type {string}*/"); assertTypeEquals(STRING_TYPE, info.getType()); } public void testParseNamedType4() throws Exception { // Multi-line @type. JSDocInfo info = parse("@type \n {string}*/"); assertTypeEquals(STRING_TYPE, info.getType()); } public void testParseNamedType5() throws Exception { JSDocInfo info = parse("@type {!goog.\nBar}*/"); assertTypeEquals( registry.createNamedType("goog.Bar", null, -1, -1), info.getType()); } public void testParseNamedType6() throws Exception { JSDocInfo info = parse("@type {!goog.\n * Bar.\n * Baz}*/"); assertTypeEquals( registry.createNamedType("goog.Bar.Baz", null, -1, -1), info.getType()); } public void testParseNamedTypeError1() throws Exception { // To avoid parsing ambiguities, type names must end in a '.' to // get the continuation behavior. parse("@type {!goog\n * .Bar} */", "Bad type annotation. expected closing }"); } public void testParseNamedTypeError2() throws Exception { parse("@type {!goog.\n * Bar\n * .Baz} */", "Bad type annotation. expected closing }"); } public void testParseNamespaceType1() throws Exception { JSDocInfo info = parse("@type {goog.}*/"); assertTypeEquals( registry.createNamedType("goog.", null, -1, -1), info.getType()); } public void testTypedefType1() throws Exception { JSDocInfo info = parse("@typedef string */"); assertTrue(info.hasTypedefType()); assertTypeEquals(STRING_TYPE, info.getTypedefType()); } public void testTypedefType2() throws Exception { JSDocInfo info = parse("@typedef \n {string}*/"); assertTrue(info.hasTypedefType()); assertTypeEquals(STRING_TYPE, info.getTypedefType()); } public void testTypedefType3() throws Exception { JSDocInfo info = parse("@typedef \n {(string|number)}*/"); assertTrue(info.hasTypedefType()); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), info.getTypedefType()); } public void testParseStringType1() throws Exception { assertTypeEquals(STRING_TYPE, parse("@type {string}*/").getType()); } public void testParseStringType2() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@type {!String}*/").getType()); } public void testParseBooleanType1() throws Exception { assertTypeEquals(BOOLEAN_TYPE, parse("@type {boolean}*/").getType()); } public void testParseBooleanType2() throws Exception { assertTypeEquals( BOOLEAN_OBJECT_TYPE, parse("@type {!Boolean}*/").getType()); } public void testParseNumberType1() throws Exception { assertTypeEquals(NUMBER_TYPE, parse("@type {number}*/").getType()); } public void testParseNumberType2() throws Exception { assertTypeEquals(NUMBER_OBJECT_TYPE, parse("@type {!Number}*/").getType()); } public void testParseNullType1() throws Exception { assertTypeEquals(NULL_TYPE, parse("@type {null}*/").getType()); } public void testParseNullType2() throws Exception { assertTypeEquals(NULL_TYPE, parse("@type {Null}*/").getType()); } public void testParseAllType1() throws Exception { testParseType("*"); } public void testParseAllType2() throws Exception { testParseType("*?", "*"); } public void testParseObjectType() throws Exception { assertTypeEquals(OBJECT_TYPE, parse("@type {!Object}*/").getType()); } public void testParseDateType() throws Exception { assertTypeEquals(DATE_TYPE, parse("@type {!Date}*/").getType()); } public void testParseFunctionType() throws Exception { assertTypeEquals( createNullableType(U2U_CONSTRUCTOR_TYPE), parse("@type {Function}*/").getType()); } public void testParseRegExpType() throws Exception { assertTypeEquals(REGEXP_TYPE, parse("@type {!RegExp}*/").getType()); } public void testParseErrorTypes() throws Exception { assertTypeEquals(ERROR_TYPE, parse("@type {!Error}*/").getType()); assertTypeEquals(URI_ERROR_TYPE, parse("@type {!URIError}*/").getType()); assertTypeEquals(EVAL_ERROR_TYPE, parse("@type {!EvalError}*/").getType()); assertTypeEquals(REFERENCE_ERROR_TYPE, parse("@type {!ReferenceError}*/").getType()); assertTypeEquals(TYPE_ERROR_TYPE, parse("@type {!TypeError}*/").getType()); assertTypeEquals( RANGE_ERROR_TYPE, parse("@type {!RangeError}*/").getType()); assertTypeEquals( SYNTAX_ERROR_TYPE, parse("@type {!SyntaxError}*/").getType()); } public void testParseUndefinedType1() throws Exception { assertTypeEquals(VOID_TYPE, parse("@type {undefined}*/").getType()); } public void testParseUndefinedType2() throws Exception { assertTypeEquals(VOID_TYPE, parse("@type {Undefined}*/").getType()); } public void testParseUndefinedType3() throws Exception { assertTypeEquals(VOID_TYPE, parse("@type {void}*/").getType()); } public void testParseTemplatizedType1() throws Exception { JSDocInfo info = parse("@type !Array.<number> */"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType()); } public void testParseTemplatizedType2() throws Exception { JSDocInfo info = parse("@type {!Array.<number>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType()); } public void testParseTemplatizedType3() throws Exception { JSDocInfo info = parse("@type !Array.<(number,null)>*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType4() throws Exception { JSDocInfo info = parse("@type {!Array.<(number|null)>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType5() throws Exception { JSDocInfo info = parse("@type {!Array.<Array.<(number|null)>>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(NULL_TYPE, createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)))), info.getType()); } public void testParseTemplatizedType6() throws Exception { JSDocInfo info = parse("@type {!Array.<!Array.<(number|null)>>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createTemplatizedType(ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE))), info.getType()); } public void testParseTemplatizedType7() throws Exception { JSDocInfo info = parse("@type {!Array.<function():Date>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, registry.createFunctionType( createUnionType(DATE_TYPE, NULL_TYPE))), info.getType()); } public void testParseTemplatizedType8() throws Exception { JSDocInfo info = parse("@type {!Array.<function():!Date>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, registry.createFunctionType(DATE_TYPE)), info.getType()); } public void testParseTemplatizedType9() throws Exception { JSDocInfo info = parse("@type {!Array.<Date|number>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(DATE_TYPE, NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType10() throws Exception { JSDocInfo info = parse("@type {!Array.<Date|number|boolean>}*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, createUnionType(DATE_TYPE, NUMBER_TYPE, BOOLEAN_TYPE, NULL_TYPE)), info.getType()); } public void testParseTemplatizedType11() throws Exception { JSDocInfo info = parse("@type {!Object.<number>}*/"); assertTypeEquals( createTemplatizedType( OBJECT_TYPE, ImmutableList.of(UNKNOWN_TYPE, NUMBER_TYPE)), info.getType()); assertTemplatizedTypeEquals( registry.getObjectElementKey(), NUMBER_TYPE, info.getType()); } public void testParseTemplatizedType12() throws Exception { JSDocInfo info = parse("@type {!Object.<string,number>}*/"); assertTypeEquals( createTemplatizedType( OBJECT_TYPE, ImmutableList.of(STRING_TYPE, NUMBER_TYPE)), info.getType()); assertTemplatizedTypeEquals( registry.getObjectElementKey(), NUMBER_TYPE, info.getType()); assertTemplatizedTypeEquals( registry.getObjectIndexKey(), STRING_TYPE, info.getType()); } public void testParseTemplatizedType13() throws Exception { JSDocInfo info = parse("@type !Array.<?> */"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, UNKNOWN_TYPE), info.getType()); } public void testParseUnionType1() throws Exception { JSDocInfo info = parse("@type {(boolean,null)}*/"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType()); } public void testParseUnionType2() throws Exception { JSDocInfo info = parse("@type {boolean|null}*/"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType()); } public void testParseUnionType3() throws Exception { JSDocInfo info = parse("@type {boolean||null}*/"); assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType()); } public void testParseUnionType4() throws Exception { JSDocInfo info = parse("@type {(Array.<boolean>,null)}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType5() throws Exception { JSDocInfo info = parse("@type {(null, Array.<boolean>)}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType6() throws Exception { JSDocInfo info = parse("@type {Array.<boolean>|null}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType7() throws Exception { JSDocInfo info = parse("@type {null|Array.<boolean>}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType8() throws Exception { JSDocInfo info = parse("@type {null||Array.<boolean>}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType9() throws Exception { JSDocInfo info = parse("@type {Array.<boolean>||null}*/"); assertTypeEquals(createUnionType( createTemplatizedType( ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType()); } public void testParseUnionType10() throws Exception { parse("@type {string|}*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnionType11() throws Exception { parse("@type {(string,)}*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnionType12() throws Exception { parse("@type {()}*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnionType13() throws Exception { testParseType( "(function(this:Date),function(this:String):number)", "Function"); } public void testParseUnionType14() throws Exception { testParseType( "(function(...[function(number):boolean]):number)|" + "function(this:String, string):number", "Function"); } public void testParseUnionType15() throws Exception { testParseType("*|number", "*"); } public void testParseUnionType16() throws Exception { testParseType("number|*", "*"); } public void testParseUnionType17() throws Exception { testParseType("string|number|*", "*"); } public void testParseUnionType18() throws Exception { testParseType("(string,*,number)", "*"); } public void testParseUnionTypeError1() throws Exception { parse("@type {(string,|number)} */", "Bad type annotation. type not recognized due to syntax error"); } public void testParseUnknownType1() throws Exception { testParseType("?"); } public void testParseUnknownType2() throws Exception { testParseType("(?|number)", "?"); } public void testParseUnknownType3() throws Exception { testParseType("(number|?)", "?"); } public void testParseFunctionalType1() throws Exception { testParseType("function (): number"); } public void testParseFunctionalType2() throws Exception { testParseType("function (number, string): boolean"); } public void testParseFunctionalType3() throws Exception { testParseType( "function(this:Array)", "function (this:Array): ?"); } public void testParseFunctionalType4() throws Exception { testParseType("function (...[number]): boolean"); } public void testParseFunctionalType5() throws Exception { testParseType("function (number, ...[string]): boolean"); } public void testParseFunctionalType6() throws Exception { testParseType( "function (this:Date, number): (boolean|number|string)"); } public void testParseFunctionalType7() throws Exception { testParseType("function()", "function (): ?"); } public void testParseFunctionalType8() throws Exception { testParseType( "function(this:Array,...[boolean])", "function (this:Array, ...[boolean]): ?"); } public void testParseFunctionalType9() throws Exception { testParseType( "function(this:Array,!Date,...[boolean?])", "function (this:Array, Date, ...[(boolean|null)]): ?"); } public void testParseFunctionalType10() throws Exception { testParseType( "function(...[Object?]):boolean?", "function (...[(Object|null)]): (boolean|null)"); } public void testParseFunctionalType11() throws Exception { testParseType( "function(...[[number]]):[number?]", "function (...[Array]): Array"); } public void testParseFunctionalType12() throws Exception { testParseType( "function(...)", "function (...[?]): ?"); } public void testParseFunctionalType13() throws Exception { testParseType( "function(...): void", "function (...[?]): undefined"); } public void testParseFunctionalType14() throws Exception { testParseType("function (*, string, number): boolean"); } public void testParseFunctionalType15() throws Exception { testParseType("function (?, string): boolean"); } public void testParseFunctionalType16() throws Exception { testParseType("function (string, ?): ?"); } public void testParseFunctionalType17() throws Exception { testParseType("(function (?): ?|number)"); } public void testParseFunctionalType18() throws Exception { testParseType("function (?): (?|number)", "function (?): ?"); } public void testParseFunctionalType19() throws Exception { testParseType( "function(...[?]): void", "function (...[?]): undefined"); } public void testStructuralConstructor() throws Exception { JSType type = testParseType( "function (new:Object)", "function (new:Object): ?"); assertTrue(type.isConstructor()); assertFalse(type.isNominalConstructor()); } public void testStructuralConstructor2() throws Exception { JSType type = testParseType( "function (new:?)", // toString skips unknowns, but isConstructor reveals the truth. "function (): ?"); assertTrue(type.isConstructor()); assertFalse(type.isNominalConstructor()); } public void testStructuralConstructor3() throws Exception { resolve(parse("@type {function (new:*)} */").getType(), "constructed type must be an object type"); } public void testNominalConstructor() throws Exception { ObjectType type = testParseType("Array", "(Array|null)").dereference(); assertTrue(type.getConstructor().isNominalConstructor()); } public void testBug1419535() throws Exception { parse("@type {function(Object, string, *)?} */"); parse("@type {function(Object, string, *)|null} */"); } public void testIssue477() throws Exception { parse("@type function */", "Bad type annotation. missing opening ("); } public void testMalformedThisAnnotation() throws Exception { parse("@this */", "Bad type annotation. type not recognized due to syntax error"); } public void testParseFunctionalTypeError1() throws Exception { parse("@type {function number):string}*/", "Bad type annotation. missing opening ("); } public void testParseFunctionalTypeError2() throws Exception { parse("@type {function( number}*/", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError3() throws Exception { parse("@type {function(...[number], string)}*/", "Bad type annotation. variable length argument must be last"); } public void testParseFunctionalTypeError4() throws Exception { parse("@type {function(string, ...[number], boolean):string}*/", "Bad type annotation. variable length argument must be last"); } public void testParseFunctionalTypeError5() throws Exception { parse("@type {function (thi:Array)}*/", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError6() throws Exception { resolve(parse("@type {function (this:number)}*/").getType(), "this type must be an object type"); } public void testParseFunctionalTypeError7() throws Exception { parse("@type {function(...[number)}*/", "Bad type annotation. missing closing ]"); } public void testParseFunctionalTypeError8() throws Exception { parse("@type {function(...number])}*/", "Bad type annotation. missing opening ["); } public void testParseFunctionalTypeError9() throws Exception { parse("@type {function (new:Array, this:Object)} */", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError10() throws Exception { parse("@type {function (this:Array, new:Object)} */", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError11() throws Exception { parse("@type {function (Array, new:Object)} */", "Bad type annotation. missing closing )"); } public void testParseFunctionalTypeError12() throws Exception { resolve(parse("@type {function (new:number)}*/").getType(), "constructed type must be an object type"); } public void testParseArrayType1() throws Exception { testParseType("[number]", "Array"); } public void testParseArrayType2() throws Exception { testParseType("[(number,boolean,[Object?])]", "Array"); } public void testParseArrayType3() throws Exception { testParseType("[[number],[string]]?", "(Array|null)"); } public void testParseArrayTypeError1() throws Exception { parse("@type {[number}*/", "Bad type annotation. missing closing ]"); } public void testParseArrayTypeError2() throws Exception { parse("@type {number]}*/", "Bad type annotation. expected closing }"); } public void testParseArrayTypeError3() throws Exception { parse("@type {[(number,boolean,Object?])]}*/", "Bad type annotation. missing closing )"); } public void testParseArrayTypeError4() throws Exception { parse("@type {(number,boolean,[Object?)]}*/", "Bad type annotation. missing closing ]"); } private JSType testParseType(String type) throws Exception { return testParseType(type, type); } private JSType testParseType( String type, String typeExpected) throws Exception { JSDocInfo info = parse("@type {" + type + "}*/"); assertNotNull(info); assertTrue(info.hasType()); JSType actual = resolve(info.getType()); assertEquals(typeExpected, actual.toString()); return actual; } public void testParseNullableModifiers1() throws Exception { JSDocInfo info = parse("@type {string?}*/"); assertTypeEquals(createNullableType(STRING_TYPE), info.getType()); } public void testParseNullableModifiers2() throws Exception { JSDocInfo info = parse("@type {!Array.<string?>}*/"); assertTypeEquals( createTemplatizedType( ARRAY_TYPE, createUnionType(STRING_TYPE, NULL_TYPE)), info.getType()); } public void testParseNullableModifiers3() throws Exception { JSDocInfo info = parse("@type {Array.<boolean>?}*/"); assertTypeEquals( createNullableType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers4() throws Exception { JSDocInfo info = parse("@type {(string,boolean)?}*/"); assertTypeEquals( createNullableType(createUnionType(STRING_TYPE, BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers5() throws Exception { JSDocInfo info = parse("@type {(string?,boolean)}*/"); assertTypeEquals( createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE), info.getType()); } public void testParseNullableModifiers6() throws Exception { JSDocInfo info = parse("@type {(string,boolean?)}*/"); assertTypeEquals( createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers7() throws Exception { JSDocInfo info = parse("@type {string?|boolean}*/"); assertTypeEquals( createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE), info.getType()); } public void testParseNullableModifiers8() throws Exception { JSDocInfo info = parse("@type {string|boolean?}*/"); assertTypeEquals( createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)), info.getType()); } public void testParseNullableModifiers9() throws Exception { JSDocInfo info = parse("@type {foo.Hello.World?}*/"); assertTypeEquals( createNullableType( registry.createNamedType( "foo.Hello.World", null, -1, -1)), info.getType()); } public void testParseOptionalModifier() throws Exception { JSDocInfo info = parse("@type {function(number=)}*/"); assertTypeEquals( registry.createFunctionType( UNKNOWN_TYPE, registry.createOptionalParameters(NUMBER_TYPE)), info.getType()); } public void testParseNewline1() throws Exception { JSDocInfo info = parse("@type {string\n* }\n*/"); assertTypeEquals(STRING_TYPE, info.getType()); } public void testParseNewline2() throws Exception { JSDocInfo info = parse("@type !Array.<\n* number\n* > */"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType()); } public void testParseNewline3() throws Exception { JSDocInfo info = parse("@type !Array.<(number,\n* null)>*/"); assertTypeEquals( createTemplatizedType( ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseNewline4() throws Exception { JSDocInfo info = parse("@type !Array.<(number|\n* null)>*/"); assertTypeEquals( createTemplatizedType( ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)), info.getType()); } public void testParseNewline5() throws Exception { JSDocInfo info = parse("@type !Array.<function(\n* )\n* :\n* Date>*/"); assertTypeEquals( createTemplatizedType(ARRAY_TYPE, registry.createFunctionType( createUnionType(DATE_TYPE, NULL_TYPE))), info.getType()); } public void testParseReturnType1() throws Exception { JSDocInfo info = parse("@return {null|string|Array.<boolean>}*/"); assertTypeEquals( createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE, STRING_TYPE), info.getReturnType()); } public void testParseReturnType2() throws Exception { JSDocInfo info = parse("@returns {null|(string,Array.<boolean>)}*/"); assertTypeEquals( createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE, STRING_TYPE), info.getReturnType()); } public void testParseReturnType3() throws Exception { JSDocInfo info = parse("@return {((null||Array.<boolean>,string),boolean)}*/"); assertTypeEquals( createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE, STRING_TYPE, BOOLEAN_TYPE), info.getReturnType()); } public void testParseThisType1() throws Exception { JSDocInfo info = parse("@this {goog.foo.Bar}*/"); assertTypeEquals( registry.createNamedType("goog.foo.Bar", null, -1, -1), info.getThisType()); } public void testParseThisType2() throws Exception { JSDocInfo info = parse("@this goog.foo.Bar*/"); assertTypeEquals( registry.createNamedType("goog.foo.Bar", null, -1, -1), info.getThisType()); } public void testParseThisType3() throws Exception { parse("@type {number}\n@this goog.foo.Bar*/", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testParseThisType4() throws Exception { resolve(parse("@this number*/").getThisType(), "@this must specify an object type"); } public void testParseThisType5() throws Exception { parse("@this {Date|Error}*/"); } public void testParseThisType6() throws Exception { resolve(parse("@this {Date|number}*/").getThisType(), "@this must specify an object type"); } public void testParseParam1() throws Exception { JSDocInfo info = parse("@param {number} index*/"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam2() throws Exception { JSDocInfo info = parse("@param index*/"); assertEquals(1, info.getParameterCount()); assertEquals(null, info.getParameterType("index")); } public void testParseParam3() throws Exception { JSDocInfo info = parse("@param {number} index useful comments*/"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam4() throws Exception { JSDocInfo info = parse("@param index useful comments*/"); assertEquals(1, info.getParameterCount()); assertEquals(null, info.getParameterType("index")); } public void testParseParam5() throws Exception { // Test for multi-line @param. JSDocInfo info = parse("@param {number} \n index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam6() throws Exception { // Test for multi-line @param. JSDocInfo info = parse("@param {number} \n * index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testParseParam7() throws Exception { // Optional @param JSDocInfo info = parse("@param {number=} index */"); assertTypeEquals( registry.createOptionalType(NUMBER_TYPE), info.getParameterType("index")); } public void testParseParam8() throws Exception { // Var args @param JSDocInfo info = parse("@param {...number} index */"); assertTypeEquals( registry.createOptionalType(NUMBER_TYPE), info.getParameterType("index")); } public void testParseParam9() throws Exception { parse("@param {...number=} index */", "Bad type annotation. expected closing }", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParam10() throws Exception { parse("@param {...number index */", "Bad type annotation. expected closing }"); } public void testParseParam11() throws Exception { parse("@param {number= index */", "Bad type annotation. expected closing }"); } public void testParseParam12() throws Exception { JSDocInfo info = parse("@param {...number|string} index */"); assertTypeEquals( registry.createOptionalType( registry.createUnionType(STRING_TYPE, NUMBER_TYPE)), info.getParameterType("index")); } public void testParseParam13() throws Exception { JSDocInfo info = parse("@param {...(number|string)} index */"); assertTypeEquals( registry.createOptionalType( registry.createUnionType(STRING_TYPE, NUMBER_TYPE)), info.getParameterType("index")); } public void testParseParam14() throws Exception { JSDocInfo info = parse("@param {string} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("index")); } public void testParseParam15() throws Exception { JSDocInfo info = parse("@param {string} [index */", "Bad type annotation. missing closing ]"); assertEquals(1, info.getParameterCount()); assertTypeEquals(STRING_TYPE, info.getParameterType("index")); } public void testParseParam16() throws Exception { JSDocInfo info = parse("@param {string} index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals(STRING_TYPE, info.getParameterType("index")); } public void testParseParam17() throws Exception { JSDocInfo info = parse("@param {string=} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("index")); } public void testParseParam18() throws Exception { JSDocInfo info = parse("@param {...string} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("index")); } public void testParseParam19() throws Exception { JSDocInfo info = parse("@param {...} [index] */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(UNKNOWN_TYPE), info.getParameterType("index")); assertTrue(info.getParameterType("index").isVarArgs()); } public void testParseParam20() throws Exception { JSDocInfo info = parse("@param {?=} index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( UNKNOWN_TYPE, info.getParameterType("index")); } public void testParseParam21() throws Exception { JSDocInfo info = parse("@param {...?} index */"); assertEquals(1, info.getParameterCount()); assertTypeEquals( UNKNOWN_TYPE, info.getParameterType("index")); assertTrue(info.getParameterType("index").isVarArgs()); } public void testParseThrows1() throws Exception { JSDocInfo info = parse("@throws {number} Some number */"); assertEquals(1, info.getThrownTypes().size()); assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0)); } public void testParseThrows2() throws Exception { JSDocInfo info = parse("@throws {number} Some number\n " + "*@throws {String} A string */"); assertEquals(2, info.getThrownTypes().size()); assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0)); } public void testParseRecordType1() throws Exception { parseFull("/** @param {{x}} n\n*/"); } public void testParseRecordType2() throws Exception { parseFull("/** @param {{z, y}} n\n*/"); } public void testParseRecordType3() throws Exception { parseFull("/** @param {{z, y, x, q, hello, thisisatest}} n\n*/"); } public void testParseRecordType4() throws Exception { parseFull("/** @param {{a, 'a', 'hello', 2, this, do, while, for}} n\n*/"); } public void testParseRecordType5() throws Exception { parseFull("/** @param {{x : hello}} n\n*/"); } public void testParseRecordType6() throws Exception { parseFull("/** @param {{'x' : hello}} n\n*/"); } public void testParseRecordType7() throws Exception { parseFull("/** @param {{'x' : !hello}} n\n*/"); } public void testParseRecordType8() throws Exception { parseFull("/** @param {{'x' : !hello, y : bar}} n\n*/"); } public void testParseRecordType9() throws Exception { parseFull("/** @param {{'x' : !hello, y : {z : bar, 3 : meh}}} n\n*/"); } public void testParseRecordType10() throws Exception { parseFull("/** @param {{__proto__ : moo}} n\n*/"); } public void testParseRecordType11() throws Exception { parseFull("/** @param {{a : b} n\n*/", "Bad type annotation. expected closing }"); } public void testParseRecordType12() throws Exception { parseFull("/** @param {{!hello : hey}} n\n*/", "Bad type annotation. type not recognized due to syntax error"); } public void testParseRecordType13() throws Exception { parseFull("/** @param {{x}|number} n\n*/"); } public void testParseRecordType14() throws Exception { parseFull("/** @param {{x : y}|number} n\n*/"); } public void testParseRecordType15() throws Exception { parseFull("/** @param {{'x' : y}|number} n\n*/"); } public void testParseRecordType16() throws Exception { parseFull("/** @param {{x, y}|number} n\n*/"); } public void testParseRecordType17() throws Exception { parseFull("/** @param {{x : hello, 'y'}|number} n\n*/"); } public void testParseRecordType18() throws Exception { parseFull("/** @param {number|{x : hello, 'y'}} n\n*/"); } public void testParseRecordType19() throws Exception { parseFull("/** @param {?{x : hello, 'y'}} n\n*/"); } public void testParseRecordType20() throws Exception { parseFull("/** @param {!{x : hello, 'y'}} n\n*/"); } public void testParseRecordType21() throws Exception { parseFull("/** @param {{x : hello, 'y'}|boolean} n\n*/"); } public void testParseRecordType22() throws Exception { parseFull("/** @param {{x : hello, 'y'}|function()} n\n*/"); } public void testParseRecordType23() throws Exception { parseFull("/** @param {{x : function(), 'y'}|function()} n\n*/"); } public void testParseParamError1() throws Exception { parseFull("/** @param\n*/", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError2() throws Exception { parseFull("/** @param {Number}*/", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError3() throws Exception { parseFull("/** @param {Number}\n*/", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError4() throws Exception { parseFull("/** @param {Number}\n* * num */", "Bad type annotation. expecting a variable name in a @param tag"); } public void testParseParamError5() throws Exception { parse("@param {number} x \n * @param {string} x */", "Bad type annotation. duplicate variable name \"x\""); } public void testParseExtends1() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends String*/").getBaseType()); } public void testParseExtends2() throws Exception { JSDocInfo info = parse("@extends com.google.Foo.Bar.Hello.World*/"); assertTypeEquals( registry.createNamedType( "com.google.Foo.Bar.Hello.World", null, -1, -1), info.getBaseType()); } public void testParseExtendsGenerics() throws Exception { JSDocInfo info = parse("@extends com.google.Foo.Bar.Hello.World.<Boolean,number>*/"); assertTypeEquals( registry.createNamedType( "com.google.Foo.Bar.Hello.World", null, -1, -1), info.getBaseType()); } public void testParseImplementsGenerics() throws Exception { // For types that are not templatized, <> annotations are ignored. List<JSTypeExpression> interfaces = parse("@implements {SomeInterface.<*>} */") .getImplementedInterfaces(); assertEquals(1, interfaces.size()); assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1), interfaces.get(0)); } public void testParseExtends4() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends {String}*/").getBaseType()); } public void testParseExtends5() throws Exception { assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends {String*/", "Bad type annotation. expected closing }").getBaseType()); } public void testParseExtends6() throws Exception { // Multi-line extends assertTypeEquals(STRING_OBJECT_TYPE, parse("@extends \n * {String}*/").getBaseType()); } public void testParseExtendsInvalidName() throws Exception { // This looks bad, but for the time being it should be OK, as // we will not find a type with this name in the JS parsed tree. // If this is fixed in the future, change this test to check for a // warning/error message. assertTypeEquals( registry.createNamedType("some_++#%$%_UglyString", null, -1, -1), parse("@extends {some_++#%$%_UglyString} */").getBaseType()); } public void testParseExtendsNullable1() throws Exception { parse("@extends {Base?} */", "Bad type annotation. expected closing }"); } public void testParseExtendsNullable2() throws Exception { parse("@extends Base? */", "Bad type annotation. expected end of line or comment"); } public void testParseEnum1() throws Exception { assertTypeEquals(NUMBER_TYPE, parse("@enum*/").getEnumParameterType()); } public void testParseEnum2() throws Exception { assertTypeEquals(STRING_TYPE, parse("@enum {string}*/").getEnumParameterType()); } public void testParseEnum3() throws Exception { assertTypeEquals(STRING_TYPE, parse("@enum string*/").getEnumParameterType()); } public void testParseDesc1() throws Exception { assertEquals("hello world!", parse("@desc hello world!*/").getDescription()); } public void testParseDesc2() throws Exception { assertEquals("hello world!", parse("@desc hello world!\n*/").getDescription()); } public void testParseDesc3() throws Exception { assertEquals("", parse("@desc*/").getDescription()); } public void testParseDesc4() throws Exception { assertEquals("", parse("@desc\n*/").getDescription()); } public void testParseDesc5() throws Exception { assertEquals("hello world!", parse("@desc hello\nworld!\n*/").getDescription()); } public void testParseDesc6() throws Exception { assertEquals("hello world!", parse("@desc hello\n* world!\n*/").getDescription()); } public void testParseDesc7() throws Exception { assertEquals("a b c", parse("@desc a\n\nb\nc*/").getDescription()); } public void testParseDesc8() throws Exception { assertEquals("a b c d", parse("@desc a\n *b\n\n *c\n\nd*/").getDescription()); } public void testParseDesc9() throws Exception { String comment = "@desc\n.\n,\n{\n)\n}\n|\n.<\n>\n<\n?\n~\n+\n-\n;\n:\n*/"; assertEquals(". , { ) } | .< > < ? ~ + - ; :", parse(comment).getDescription()); } public void testParseDesc10() throws Exception { String comment = "@desc\n?\n?\n?\n?*/"; assertEquals("? ? ? ?", parse(comment).getDescription()); } public void testParseDesc11() throws Exception { String comment = "@desc :[]*/"; assertEquals(":[]", parse(comment).getDescription()); } public void testParseDesc12() throws Exception { String comment = "@desc\n:\n[\n]\n...*/"; assertEquals(": [ ] ...", parse(comment).getDescription()); } public void testParseMeaning1() throws Exception { assertEquals("tigers", parse("@meaning tigers */").getMeaning()); } public void testParseMeaning2() throws Exception { assertEquals("tigers and lions and bears", parse("@meaning tigers\n * and lions\n * and bears */").getMeaning()); } public void testParseMeaning3() throws Exception { JSDocInfo info = parse("@meaning tigers\n * and lions\n * @desc and bears */"); assertEquals("tigers and lions", info.getMeaning()); assertEquals("and bears", info.getDescription()); } public void testParseMeaning4() throws Exception { parse("@meaning tigers\n * @meaning and lions */", "extra @meaning tag"); } public void testParseLends1() throws Exception { JSDocInfo info = parse("@lends {name} */"); assertEquals("name", info.getLendsName()); } public void testParseLends2() throws Exception { JSDocInfo info = parse("@lends foo.bar */"); assertEquals("foo.bar", info.getLendsName()); } public void testParseLends3() throws Exception { parse("@lends {name */", "Bad type annotation. expected closing }"); } public void testParseLends4() throws Exception { parse("@lends {} */", "Bad type annotation. missing object name in @lends tag"); } public void testParseLends5() throws Exception { parse("@lends } */", "Bad type annotation. missing object name in @lends tag"); } public void testParseLends6() throws Exception { parse("@lends {string} \n * @lends {string} */", "Bad type annotation. @lends tag incompatible with other annotations"); } public void testParseLends7() throws Exception { parse("@type {string} \n * @lends {string} */", "Bad type annotation. @lends tag incompatible with other annotations"); } public void testStackedAnnotation() throws Exception { JSDocInfo info = parse("@const @type {string}*/"); assertTrue(info.isConstant()); assertTrue(info.hasType()); assertTypeEquals(STRING_TYPE, info.getType()); } public void testStackedAnnotation2() throws Exception { JSDocInfo info = parse("@type {string} @const */"); assertTrue(info.isConstant()); assertTrue(info.hasType()); assertTypeEquals(STRING_TYPE, info.getType()); } public void testStackedAnnotation3() throws Exception { JSDocInfo info = parse("@const @see {string}*/"); assertTrue(info.isConstant()); assertFalse(info.hasType()); } public void testStackedAnnotation4() throws Exception { JSDocInfo info = parse("@constructor @extends {Foo} @implements {Bar}*/"); assertTrue(info.isConstructor()); assertTrue(info.hasBaseType()); assertEquals(1, info.getImplementedInterfaceCount()); } public void testStackedAnnotation5() throws Exception { JSDocInfo info = parse("@param {number} x @constructor */"); assertTrue(info.hasParameterType("x")); assertTrue(info.isConstructor()); } public void testStackedAnnotation6() throws Exception { JSDocInfo info = parse("@return {number} @constructor */", true); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); info = parse("@return {number} @constructor */", false); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); } public void testStackedAnnotation7() throws Exception { JSDocInfo info = parse("@return @constructor */"); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); } public void testStackedAnnotation8() throws Exception { JSDocInfo info = parse("@throws {number} @constructor */", true); assertTrue(!info.getThrownTypes().isEmpty()); assertTrue(info.isConstructor()); info = parse("@return {number} @constructor */", false); assertTrue(info.hasReturnType()); assertTrue(info.isConstructor()); } public void testParsePreserve() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@preserve Foo\nBar\n\nBaz*/"; parse(comment); assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense()); } public void testParseLicense() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@license Foo\nBar\n\nBaz*/"; parse(comment); assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense()); } public void testParseLicenseAscii() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@license Foo\n * Bar\n\n Baz*/"; parse(comment); assertEquals(" Foo\n Bar\n\n Baz", node.getJSDocInfo().getLicense()); } public void testParseLicenseWithAnnotation() throws Exception { Node node = new Node(1); this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode(); String comment = "@license Foo \n * @author Charlie Brown */"; parse(comment); assertEquals(" Foo \n @author Charlie Brown ", node.getJSDocInfo().getLicense()); } public void testParseDefine1() throws Exception { assertTypeEquals(STRING_TYPE, parse("@define {string}*/").getType()); } public void testParseDefine2() throws Exception { assertTypeEquals(STRING_TYPE, parse("@define {string*/", "Bad type annotation. expected closing }").getType()); } public void testParseDefine3() throws Exception { JSDocInfo info = parse("@define {boolean}*/"); assertTrue(info.isConstant()); assertTrue(info.isDefine()); assertTypeEquals(BOOLEAN_TYPE, info.getType()); } public void testParseDefine4() throws Exception { assertTypeEquals(NUMBER_TYPE, parse("@define {number}*/").getType()); } public void testParseDefine5() throws Exception { assertTypeEquals(createUnionType(NUMBER_TYPE, BOOLEAN_TYPE), parse("@define {number|boolean}*/").getType()); } public void testParseDefineDescription() throws Exception { JSDocInfo doc = parse( "@define {string} description of element \n next line*/", true); Marker defineMarker = doc.getMarkers().iterator().next(); assertEquals("define", defineMarker.getAnnotation().getItem()); assertTrue(defineMarker.getDescription().getItem().contains("description of element")); assertTrue(defineMarker.getDescription().getItem().contains("next line")); } public void testParsePrivateDescription() throws Exception { JSDocInfo doc = parse("@private {string} description \n next line*/", true); Marker defineMarker = doc.getMarkers().iterator().next(); assertEquals("private", defineMarker.getAnnotation().getItem()); assertTrue(defineMarker.getDescription().getItem().contains("description ")); assertTrue(defineMarker.getDescription().getItem().contains("next line")); } public void testParseProtectedDescription() throws Exception { JSDocInfo doc = parse("@protected {string} description \n next line*/", true); Marker defineMarker = doc.getMarkers().iterator().next(); assertEquals("protected", defineMarker.getAnnotation().getItem()); assertTrue(defineMarker.getDescription().getItem().contains("description ")); assertTrue(defineMarker.getDescription().getItem().contains("next line")); } public void testParseDefineErrors1() throws Exception { parse("@enum {string}\n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors2() throws Exception { parse("@define {string}\n @enum {string} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testParseDefineErrors3() throws Exception { parse("@const\n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors4() throws Exception { parse("@type string \n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors5() throws Exception { parse("@return {string}\n @define {string} */", "conflicting @define tag"); } public void testParseDefineErrors7() throws Exception { parse("@define {string}\n @const */", "conflicting @const tag"); } public void testParseDefineErrors8() throws Exception { parse("@define {string}\n @type string */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testParseNoCheck1() throws Exception { assertTrue(parse("@notypecheck*/").isNoTypeCheck()); } public void testParseNoCheck2() throws Exception { parse("@notypecheck\n@notypecheck*/", "extra @notypecheck tag"); } public void testParseOverride1() throws Exception { assertTrue(parse("@override*/").isOverride()); } public void testParseOverride2() throws Exception { parse("@override\n@override*/", "Bad type annotation. extra @override/@inheritDoc tag"); } public void testParseInheritDoc1() throws Exception { assertTrue(parse("@inheritDoc*/").isOverride()); } public void testParseInheritDoc2() throws Exception { parse("@override\n@inheritDoc*/", "Bad type annotation. extra @override/@inheritDoc tag"); } public void testParseInheritDoc3() throws Exception { parse("@inheritDoc\n@inheritDoc*/", "Bad type annotation. extra @override/@inheritDoc tag"); } public void testParseNoAlias1() throws Exception { assertTrue(parse("@noalias*/").isNoAlias()); } public void testParseNoAlias2() throws Exception { parse("@noalias\n@noalias*/", "extra @noalias tag"); } public void testParseDeprecated1() throws Exception { assertTrue(parse("@deprecated*/").isDeprecated()); } public void testParseDeprecated2() throws Exception { parse("@deprecated\n@deprecated*/", "extra @deprecated tag"); } public void testParseExport1() throws Exception { assertTrue(parse("@export*/").isExport()); } public void testParseExport2() throws Exception { parse("@export\n@export*/", "extra @export tag"); } public void testParseExpose1() throws Exception { assertTrue(parse("@expose*/").isExpose()); } public void testParseExpose2() throws Exception { parse("@expose\n@expose*/", "extra @expose tag"); } public void testParseExterns1() throws Exception { assertTrue(parseFileOverview("@externs*/").isExterns()); } public void testParseExterns2() throws Exception { parseFileOverview("@externs\n@externs*/", "extra @externs tag"); } public void testParseExterns3() throws Exception { assertNull(parse("@externs*/")); } public void testParseJavaDispatch1() throws Exception { assertTrue(parse("@javadispatch*/").isJavaDispatch()); } public void testParseJavaDispatch2() throws Exception { parse("@javadispatch\n@javadispatch*/", "extra @javadispatch tag"); } public void testParseJavaDispatch3() throws Exception { assertNull(parseFileOverview("@javadispatch*/")); } public void testParseNoCompile1() throws Exception { assertTrue(parseFileOverview("@nocompile*/").isNoCompile()); } public void testParseNoCompile2() throws Exception { parseFileOverview("@nocompile\n@nocompile*/", "extra @nocompile tag"); } public void testBugAnnotation() throws Exception { parse("@bug */"); } public void testDescriptionAnnotation() throws Exception { parse("@description */"); } public void testRegression1() throws Exception { String comment = " * @param {number} index the index of blah\n" + " * @return {boolean} whatever\n" + " * @private\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); assertTypeEquals(BOOLEAN_TYPE, info.getReturnType()); assertEquals(Visibility.PRIVATE, info.getVisibility()); } public void testRegression2() throws Exception { String comment = " * @return {boolean} whatever\n" + " * but important\n" + " *\n" + " * @param {number} index the index of blah\n" + " * some more comments here\n" + " * @param name the name of the guy\n" + " *\n" + " * @protected\n" + " */"; JSDocInfo info = parse(comment); assertEquals(2, info.getParameterCount()); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); assertEquals(null, info.getParameterType("name")); assertTypeEquals(BOOLEAN_TYPE, info.getReturnType()); assertEquals(Visibility.PROTECTED, info.getVisibility()); } public void testRegression3() throws Exception { String comment = " * @param mediaTag this specified whether the @media tag is ....\n" + " *\n" + "\n" + "@public\n" + " *\n" + "\n" + " **********\n" + " * @final\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertEquals(null, info.getParameterType("mediaTag")); assertEquals(Visibility.PUBLIC, info.getVisibility()); assertTrue(info.isConstant()); } public void testRegression4() throws Exception { String comment = " * @const\n" + " * @hidden\n" + " * @preserveTry\n" + " * @constructor\n" + " */"; JSDocInfo info = parse(comment); assertTrue(info.isConstant()); assertFalse(info.isDefine()); assertTrue(info.isConstructor()); assertTrue(info.isHidden()); assertTrue(info.shouldPreserveTry()); } public void testRegression5() throws Exception { String comment = "@const\n@enum {string}\n@public*/"; JSDocInfo info = parse(comment); assertTrue(info.isConstant()); assertFalse(info.isDefine()); assertTypeEquals(STRING_TYPE, info.getEnumParameterType()); assertEquals(Visibility.PUBLIC, info.getVisibility()); } public void testRegression6() throws Exception { String comment = "@hidden\n@enum\n@public*/"; JSDocInfo info = parse(comment); assertTrue(info.isHidden()); assertTypeEquals(NUMBER_TYPE, info.getEnumParameterType()); assertEquals(Visibility.PUBLIC, info.getVisibility()); } public void testRegression7() throws Exception { String comment = " * @desc description here\n" + " * @param {boolean} flag and some more description\n" + " * nicely formatted\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag")); assertEquals("description here", info.getDescription()); } public void testRegression8() throws Exception { String comment = " * @name random tag here\n" + " * @desc description here\n" + " *\n" + " * @param {boolean} flag and some more description\n" + " * nicely formatted\n" + " */"; JSDocInfo info = parse(comment); assertEquals(1, info.getParameterCount()); assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag")); assertEquals("description here", info.getDescription()); } public void testRegression9() throws Exception { JSDocInfo jsdoc = parse( " * @param {string} p0 blah blah blah\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(1, jsdoc.getParameterCount()); assertTypeEquals(STRING_TYPE, jsdoc.getParameterType("p0")); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression10() throws Exception { JSDocInfo jsdoc = parse( " * @param {!String} p0 blah blah blah\n" + " * @param {boolean} p1 fobar\n" + " * @return {!Date} jksjkash dshad\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(2, jsdoc.getParameterCount()); assertTypeEquals(STRING_OBJECT_TYPE, jsdoc.getParameterType("p0")); assertTypeEquals(BOOLEAN_TYPE, jsdoc.getParameterType("p1")); assertTypeEquals(DATE_TYPE, jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression11() throws Exception { JSDocInfo jsdoc = parse( " * @constructor\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression12() throws Exception { JSDocInfo jsdoc = parse( " * @extends FooBar\n" + " */"); assertTypeEquals(registry.createNamedType("FooBar", null, 0, 0), jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression13() throws Exception { JSDocInfo jsdoc = parse( " * @type {!RegExp}\n" + " * @protected\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertTypeEquals(REGEXP_TYPE, jsdoc.getType()); assertEquals(Visibility.PROTECTED, jsdoc.getVisibility()); } public void testRegression14() throws Exception { JSDocInfo jsdoc = parse( " * @const\n" + " * @private\n" + " */"); assertNull(jsdoc.getBaseType()); assertTrue(jsdoc.isConstant()); assertNull(jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.PRIVATE, jsdoc.getVisibility()); } public void testRegression15() throws Exception { JSDocInfo jsdoc = parse( " * @desc Hello,\n" + " * World!\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertEquals("Hello, World!", jsdoc.getDescription()); assertNull(jsdoc.getEnumParameterType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertNull(jsdoc.getType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); assertFalse(jsdoc.isExport()); } public void testRegression16() throws Exception { JSDocInfo jsdoc = parse( " Email is plp@foo.bar\n" + " @type {string}\n" + " */"); assertNull(jsdoc.getBaseType()); assertFalse(jsdoc.isConstant()); assertTypeEquals(STRING_TYPE, jsdoc.getType()); assertFalse(jsdoc.isHidden()); assertEquals(0, jsdoc.getParameterCount()); assertNull(jsdoc.getReturnType()); assertEquals(Visibility.INHERITED, jsdoc.getVisibility()); } public void testRegression17() throws Exception { // verifying that if no @desc is present the description is empty assertNull(parse("@private*/").getDescription()); } public void testFullRegression1() throws Exception { parseFull("/** @param (string,number) foo*/function bar(foo){}", "Bad type annotation. expecting a variable name in a @param tag"); } public void testFullRegression2() throws Exception { parseFull("/** @param {string,number) foo*/function bar(foo){}", "Bad type annotation. expected closing }", "Bad type annotation. expecting a variable name in a @param tag"); } public void testFullRegression3() throws Exception { parseFull("/**..\n*/"); } public void testBug907488() throws Exception { parse("@type {number,null} */", "Bad type annotation. expected closing }"); } public void testBug907494() throws Exception { parse("@return {Object,undefined} */", "Bad type annotation. expected closing }"); } public void testBug909468() throws Exception { parse("@extends {(x)}*/", "Bad type annotation. expecting a type name"); } public void testParseInterface() throws Exception { assertTrue(parse("@interface*/").isInterface()); } public void testParseImplicitCast1() throws Exception { assertTrue(parse("@type {string} \n * @implicitCast*/").isImplicitCast()); } public void testParseImplicitCast2() throws Exception { assertFalse(parse("@type {string}*/").isImplicitCast()); } public void testParseDuplicateImplicitCast() throws Exception { parse("@type {string} \n * @implicitCast \n * @implicitCast*/", "Bad type annotation. extra @implicitCast tag"); } public void testParseInterfaceDoubled() throws Exception { parse( "* @interface\n" + "* @interface\n" + "*/", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testParseImplements() throws Exception { List<JSTypeExpression> interfaces = parse("@implements {SomeInterface}*/") .getImplementedInterfaces(); assertEquals(1, interfaces.size()); assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1), interfaces.get(0)); } public void testParseImplementsTwo() throws Exception { List<JSTypeExpression> interfaces = parse( "* @implements {SomeInterface1}\n" + "* @implements {SomeInterface2}\n" + "*/") .getImplementedInterfaces(); assertEquals(2, interfaces.size()); assertTypeEquals(registry.createNamedType("SomeInterface1", null, -1, -1), interfaces.get(0)); assertTypeEquals(registry.createNamedType("SomeInterface2", null, -1, -1), interfaces.get(1)); } public void testParseImplementsSameTwice() throws Exception { parse( "* @implements {Smth}\n" + "* @implements {Smth}\n" + "*/", "Bad type annotation. duplicate @implements tag"); } public void testParseImplementsNoName() throws Exception { parse("* @implements {} */", "Bad type annotation. expecting a type name"); } public void testParseImplementsMissingRC() throws Exception { parse("* @implements {Smth */", "Bad type annotation. expected closing }"); } public void testParseImplementsNullable1() throws Exception { parse("@implements {Base?} */", "Bad type annotation. expected closing }"); } public void testParseImplementsNullable2() throws Exception { parse("@implements Base? */", "Bad type annotation. expected end of line or comment"); } public void testInterfaceExtends() throws Exception { JSDocInfo jsdoc = parse( " * @interface \n" + " * @extends {Extended} */"); assertTrue(jsdoc.isInterface()); assertEquals(1, jsdoc.getExtendedInterfacesCount()); List<JSTypeExpression> types = jsdoc.getExtendedInterfaces(); assertTypeEquals(registry.createNamedType("Extended", null, -1, -1), types.get(0)); } public void testInterfaceMultiExtends1() throws Exception { JSDocInfo jsdoc = parse( " * @interface \n" + " * @extends {Extended1} \n" + " * @extends {Extended2} */"); assertTrue(jsdoc.isInterface()); assertNull(jsdoc.getBaseType()); assertEquals(2, jsdoc.getExtendedInterfacesCount()); List<JSTypeExpression> types = jsdoc.getExtendedInterfaces(); assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1), types.get(0)); assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1), types.get(1)); } public void testInterfaceMultiExtends2() throws Exception { JSDocInfo jsdoc = parse( " * @extends {Extended1} \n" + " * @interface \n" + " * @extends {Extended2} \n" + " * @extends {Extended3} */"); assertTrue(jsdoc.isInterface()); assertNull(jsdoc.getBaseType()); assertEquals(3, jsdoc.getExtendedInterfacesCount()); List<JSTypeExpression> types = jsdoc.getExtendedInterfaces(); assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1), types.get(0)); assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1), types.get(1)); assertTypeEquals(registry.createNamedType("Extended3", null, -1, -1), types.get(2)); } public void testBadClassMultiExtends() throws Exception { parse(" * @extends {Extended1} \n" + " * @constructor \n" + " * @extends {Extended2} */", "Bad type annotation. type annotation incompatible with other " + "annotations"); } public void testBadExtendsWithNullable() throws Exception { JSDocInfo jsdoc = parse("@constructor\n * @extends {Object?} */", "Bad type annotation. expected closing }"); assertTrue(jsdoc.isConstructor()); assertTypeEquals(OBJECT_TYPE, jsdoc.getBaseType()); } public void testBadImplementsWithNullable() throws Exception { JSDocInfo jsdoc = parse("@implements {Disposable?}\n * @constructor */", "Bad type annotation. expected closing }"); assertTrue(jsdoc.isConstructor()); assertTypeEquals(registry.createNamedType("Disposable", null, -1, -1), jsdoc.getImplementedInterfaces().get(0)); } public void testBadTypeDefInterfaceAndConstructor1() throws Exception { JSDocInfo jsdoc = parse("@interface\n@constructor*/", "Bad type annotation. cannot be both an interface and a constructor"); assertTrue(jsdoc.isInterface()); } public void testBadTypeDefInterfaceAndConstructor2() throws Exception { JSDocInfo jsdoc = parse("@constructor\n@interface*/", "Bad type annotation. cannot be both an interface and a constructor"); assertTrue(jsdoc.isConstructor()); } public void testDocumentationParameter() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description.*/", true); assertTrue(jsdoc.hasDescriptionForParameter("number42")); assertEquals("This is a description.", jsdoc.getDescriptionForParameter("number42")); } public void testMultilineDocumentationParameter() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description" + "\n* on multiple \n* lines.*/", true); assertTrue(jsdoc.hasDescriptionForParameter("number42")); assertEquals("This is a description on multiple lines.", jsdoc.getDescriptionForParameter("number42")); } public void testDocumentationMultipleParameter() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description." + "\n* @param {Integer} number87 This is another description.*/" , true); assertTrue(jsdoc.hasDescriptionForParameter("number42")); assertEquals("This is a description.", jsdoc.getDescriptionForParameter("number42")); assertTrue(jsdoc.hasDescriptionForParameter("number87")); assertEquals("This is another description.", jsdoc.getDescriptionForParameter("number87")); } public void testDocumentationMultipleParameter2() throws Exception { JSDocInfo jsdoc = parse("@param {number} delta = 0 results in a redraw\n" + " != 0 ..... */", true); assertTrue(jsdoc.hasDescriptionForParameter("delta")); assertEquals("= 0 results in a redraw != 0 .....", jsdoc.getDescriptionForParameter("delta")); } public void testAuthors() throws Exception { JSDocInfo jsdoc = parse("@param {Number} number42 This is a description." + "\n* @param {Integer} number87 This is another description." + "\n* @author a@google.com (A Person)" + "\n* @author b@google.com (B Person)" + "\n* @author c@google.com (C Person)*/" , true); Collection<String> authors = jsdoc.getAuthors(); assertTrue(authors != null); assertTrue(authors.size() == 3); assertContains(authors, "a@google.com (A Person)"); assertContains(authors, "b@google.com (B Person)"); assertContains(authors, "c@google.com (C Person)"); } public void testSuppress1() throws Exception { JSDocInfo info = parse("@suppress {x} */"); assertEquals(Sets.newHashSet("x"), info.getSuppressions()); } public void testSuppress2() throws Exception { JSDocInfo info = parse("@suppress {x|y|x|z} */"); assertEquals(Sets.newHashSet("x", "y", "z"), info.getSuppressions()); } public void testSuppress3() throws Exception { JSDocInfo info = parse("@suppress {x,y} */"); assertEquals(Sets.newHashSet("x", "y"), info.getSuppressions()); } public void testBadSuppress1() throws Exception { parse("@suppress {} */", "malformed @suppress tag"); } public void testBadSuppress2() throws Exception { parse("@suppress {x|} */", "malformed @suppress tag"); } public void testBadSuppress3() throws Exception { parse("@suppress {|x} */", "malformed @suppress tag"); } public void testBadSuppress4() throws Exception { parse("@suppress {x|y */", "malformed @suppress tag"); } public void testBadSuppress6() throws Exception { parse("@suppress {x} \n * @suppress {y} */", "duplicate @suppress tag"); } public void testBadSuppress7() throws Exception { parse("@suppress {impossible} */", "unknown @suppress parameter: impossible"); } public void testModifies1() throws Exception { JSDocInfo info = parse("@modifies {this} */"); assertEquals(Sets.newHashSet("this"), info.getModifies()); } public void testModifies2() throws Exception { JSDocInfo info = parse("@modifies {arguments} */"); assertEquals(Sets.newHashSet("arguments"), info.getModifies()); } public void testModifies3() throws Exception { JSDocInfo info = parse("@modifies {this|arguments} */"); assertEquals(Sets.newHashSet("this", "arguments"), info.getModifies()); } public void testModifies4() throws Exception { JSDocInfo info = parse("@param {*} x\n * @modifies {x} */"); assertEquals(Sets.newHashSet("x"), info.getModifies()); } public void testModifies5() throws Exception { JSDocInfo info = parse( "@param {*} x\n" + " * @param {*} y\n" + " * @modifies {x} */"); assertEquals(Sets.newHashSet("x"), info.getModifies()); } public void testModifies6() throws Exception { JSDocInfo info = parse( "@param {*} x\n" + " * @param {*} y\n" + " * @modifies {x|y} */"); assertEquals(Sets.newHashSet("x", "y"), info.getModifies()); } public void testBadModifies1() throws Exception { parse("@modifies {} */", "malformed @modifies tag"); } public void testBadModifies2() throws Exception { parse("@modifies {this|} */", "malformed @modifies tag"); } public void testBadModifies3() throws Exception { parse("@modifies {|this} */", "malformed @modifies tag"); } public void testBadModifies4() throws Exception { parse("@modifies {this|arguments */", "malformed @modifies tag"); } public void testBadModifies5() throws Exception { parse("@modifies {this,arguments} */", "malformed @modifies tag"); } public void testBadModifies6() throws Exception { parse("@modifies {this} \n * @modifies {this} */", "conflicting @modifies tag"); } public void testBadModifies7() throws Exception { parse("@modifies {impossible} */", "unknown @modifies parameter: impossible"); } public void testBadModifies8() throws Exception { parse("@modifies {this}\n" + "@nosideeffects */", "conflicting @nosideeffects tag"); } public void testBadModifies9() throws Exception { parse("@nosideeffects\n" + "@modifies {this} */", "conflicting @modifies tag"); } //public void testNoParseFileOverview() throws Exception { // JSDocInfo jsdoc = parseFileOverviewWithoutDoc("@fileoverview Hi mom! */"); // assertNull(jsdoc.getFileOverview()); // assertTrue(jsdoc.hasFileOverview()); //} public void testFileOverviewSingleLine() throws Exception { JSDocInfo jsdoc = parseFileOverview("@fileoverview Hi mom! */"); assertEquals("Hi mom!", jsdoc.getFileOverview()); } public void testFileOverviewMultiLine() throws Exception { JSDocInfo jsdoc = parseFileOverview("@fileoverview Pie is \n * good! */"); assertEquals("Pie is\n good!", jsdoc.getFileOverview()); } public void testFileOverviewDuplicate() throws Exception { parseFileOverview( "@fileoverview Pie \n * @fileoverview Cake */", "extra @fileoverview tag"); } public void testReferences() throws Exception { JSDocInfo jsdoc = parse("@see A cool place!" + "\n* @see The world." + "\n* @see SomeClass#SomeMember" + "\n* @see A boring test case*/" , true); Collection<String> references = jsdoc.getReferences(); assertTrue(references != null); assertTrue(references.size() == 4); assertContains(references, "A cool place!"); assertContains(references, "The world."); assertContains(references, "SomeClass#SomeMember"); assertContains(references, "A boring test case"); } public void testSingleTags() throws Exception { JSDocInfo jsdoc = parse("@version Some old version" + "\n* @deprecated In favor of the new one!" + "\n* @return {SomeType} The most important object :-)*/" , true); assertTrue(jsdoc.isDeprecated()); assertEquals("In favor of the new one!", jsdoc.getDeprecationReason()); assertEquals("Some old version", jsdoc.getVersion()); assertEquals("The most important object :-)", jsdoc.getReturnDescription()); } public void testSingleTags2() throws Exception { JSDocInfo jsdoc = parse( "@param {SomeType} a The most important object :-)*/", true); assertEquals("The most important object :-)", jsdoc.getDescriptionForParameter("a")); } public void testSingleTagsReordered() throws Exception { JSDocInfo jsdoc = parse("@deprecated In favor of the new one!" + "\n * @return {SomeType} The most important object :-)" + "\n * @version Some old version*/" , true); assertTrue(jsdoc.isDeprecated()); assertEquals("In favor of the new one!", jsdoc.getDeprecationReason()); assertEquals("Some old version", jsdoc.getVersion()); assertEquals("The most important object :-)", jsdoc.getReturnDescription()); } public void testVersionDuplication() throws Exception { parse("* @version Some old version" + "\n* @version Another version*/", true, "conflicting @version tag"); } public void testVersionMissing() throws Exception { parse("* @version */", true, "@version tag missing version information"); } public void testAuthorMissing() throws Exception { parse("* @author */", true, "@author tag missing author"); } public void testSeeMissing() throws Exception { parse("* @see */", true, "@see tag missing description"); } public void testSourceName() throws Exception { JSDocInfo jsdoc = parse("@deprecated */", true); assertEquals("testcode", jsdoc.getAssociatedNode().getSourceFileName()); } public void testParseBlockComment() throws Exception { JSDocInfo jsdoc = parse("this is a nice comment\n " + "* that is multiline \n" + "* @author abc@google.com */", true); assertEquals("this is a nice comment\nthat is multiline", jsdoc.getBlockDescription()); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 2, 2), "abc@google.com", 9, 2, 23); } public void testParseBlockComment2() throws Exception { JSDocInfo jsdoc = parse("this is a nice comment\n " + "* that is *** multiline \n" + "* @author abc@google.com */", true); assertEquals("this is a nice comment\nthat is *** multiline", jsdoc.getBlockDescription()); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 2, 2), "abc@google.com", 9, 2, 23); } public void testParseBlockComment3() throws Exception { JSDocInfo jsdoc = parse("\n " + "* hello world \n" + "* @author abc@google.com */", true); assertEquals("hello world", jsdoc.getBlockDescription()); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 2, 2), "abc@google.com", 9, 2, 23); } public void testParseWithMarkers1() throws Exception { JSDocInfo jsdoc = parse("@author abc@google.com */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "author", 0, 0), "abc@google.com", 7, 0, 21); } public void testParseWithMarkers2() throws Exception { JSDocInfo jsdoc = parse("@param {Foo} somename abc@google.com */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0), "abc@google.com", 21, 0, 37); } public void testParseWithMarkers3() throws Exception { JSDocInfo jsdoc = parse("@return {Foo} some long \n * multiline" + " \n * description */", true); JSDocInfo.Marker returnDoc = assertAnnotationMarker(jsdoc, "return", 0, 0); assertDocumentationInMarker(returnDoc, "some long multiline description", 14, 2, 15); assertEquals(8, returnDoc.getType().getPositionOnStartLine()); assertEquals(12, returnDoc.getType().getPositionOnEndLine()); } public void testParseWithMarkers4() throws Exception { JSDocInfo jsdoc = parse("@author foobar \n * @param {Foo} somename abc@google.com */", true); assertAnnotationMarker(jsdoc, "author", 0, 0); assertAnnotationMarker(jsdoc, "param", 1, 3); } public void testParseWithMarkers5() throws Exception { JSDocInfo jsdoc = parse("@return some long \n * multiline" + " \n * description */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "return", 0, 0), "some long multiline description", 8, 2, 15); } public void testParseWithMarkers6() throws Exception { JSDocInfo jsdoc = parse("@param x some long \n * multiline" + " \n * description */", true); assertDocumentationInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0), "some long multiline description", 8, 2, 15); } public void testParseWithMarkerNames1() throws Exception { JSDocInfo jsdoc = parse("@param {SomeType} name somedescription */", true); assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0), "name", 0, 18); } public void testParseWithMarkerNames2() throws Exception { JSDocInfo jsdoc = parse("@param {SomeType} name somedescription \n" + "* @param {AnotherType} anothername des */", true); assertTypeInMarker( assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0, 0), "name", 0, 18), "SomeType", 0, 7, 0, 16, true); assertTypeInMarker( assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 1, 2, 1), "anothername", 1, 23), "AnotherType", 1, 9, 1, 21, true); } public void testParseWithMarkerNames3() throws Exception { JSDocInfo jsdoc = parse( "@param {Some.Long.Type.\n * Name} name somedescription */", true); assertTypeInMarker( assertNameInMarker( assertAnnotationMarker(jsdoc, "param", 0, 0, 0), "name", 1, 10), "Some.Long.Type.Name", 0, 7, 1, 8, true); } @SuppressWarnings("deprecation") public void testParseWithoutMarkerName() throws Exception { JSDocInfo jsdoc = parse("@author helloworld*/", true); assertNull(assertAnnotationMarker(jsdoc, "author", 0, 0).getName()); } public void testParseWithMarkerType() throws Exception { JSDocInfo jsdoc = parse("@extends {FooBar}*/", true); assertTypeInMarker( assertAnnotationMarker(jsdoc, "extends", 0, 0), "FooBar", 0, 9, 0, 16, true); } public void testParseWithMarkerType2() throws Exception { JSDocInfo jsdoc = parse("@extends FooBar*/", true); assertTypeInMarker( assertAnnotationMarker(jsdoc, "extends", 0, 0), "FooBar", 0, 9, 0, 15, false); } public void testTypeTagConflict1() throws Exception { parse("@constructor \n * @constructor */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict2() throws Exception { parse("@interface \n * @interface */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict3() throws Exception { parse("@constructor \n * @interface */", "Bad type annotation. cannot be both an interface and a constructor"); } public void testTypeTagConflict4() throws Exception { parse("@interface \n * @constructor */", "Bad type annotation. cannot be both an interface and a constructor"); } public void testTypeTagConflict5() throws Exception { parse("@interface \n * @type {string} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict6() throws Exception { parse("@typedef {string} \n * @type {string} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict7() throws Exception { parse("@typedef {string} \n * @constructor */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict8() throws Exception { parse("@typedef {string} \n * @return {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict9() throws Exception { parse("@enum {string} \n * @return {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict10() throws Exception { parse("@this {Object} \n * @enum {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict11() throws Exception { parse("@param {Object} x \n * @type {boolean} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict12() throws Exception { parse("@typedef {boolean} \n * @param {Object} x */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict13() throws Exception { parse("@typedef {boolean} \n * @extends {Object} */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict14() throws Exception { parse("@return x \n * @return y */", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict15() throws Exception { parse("/**\n" + " * @struct\n" + " * @struct\n" + " */\n" + "function StrStr() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict16() throws Exception { parse("/**\n" + " * @struct\n" + " * @interface\n" + " */\n" + "function StrIntf() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict17() throws Exception { parse("/**\n" + " * @interface\n" + " * @struct\n" + " */\n" + "function StrIntf() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict18() throws Exception { parse("/**\n" + " * @dict\n" + " * @dict\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict19() throws Exception { parse("/**\n" + " * @dict\n" + " * @interface\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict20() throws Exception { parse("/**\n" + " * @interface\n" + " * @dict\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict21() throws Exception { parse("/**\n" + " * @private {string}\n" + " * @type {number}\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict22() throws Exception { parse("/**\n" + " * @protected {string}\n" + " * @param {string} x\n" + " */\n" + "function DictDict(x) {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict23() throws Exception { parse("/**\n" + " * @public {string}\n" + " * @return {string} x\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testTypeTagConflict24() throws Exception { parse("/**\n" + " * @const {string}\n" + " * @return {string} x\n" + " */\n" + "function DictDict() {}", "Bad type annotation. " + "type annotation incompatible with other annotations"); } public void testPrivateType() throws Exception { JSDocInfo jsdoc = parse("@private {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testProtectedType() throws Exception { JSDocInfo jsdoc = parse("@protected {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testPublicType() throws Exception { JSDocInfo jsdoc = parse("@public {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testConstType() throws Exception { JSDocInfo jsdoc = parse("@const {string} */"); assertTypeEquals(STRING_TYPE, jsdoc.getType()); } public void testStableIdGeneratorConflict() throws Exception { parse("/**\n" + " * @stableIdGenerator\n" + " * @stableIdGenerator\n" + " */\n" + "function getId() {}", "extra @stableIdGenerator tag"); } public void testIdGenerator() throws Exception { JSDocInfo info = parse("/**\n" + " * @idGenerator\n" + " */\n" + "function getId() {}"); assertTrue(info.isIdGenerator()); } public void testIdGeneratorConflict() throws Exception { parse("/**\n" + " * @idGenerator\n" + " * @idGenerator\n" + " */\n" + "function getId() {}", "extra @idGenerator tag"); } public void testIdGenerator1() throws Exception { JSDocInfo info = parse("@idGenerator {unique} */"); assertTrue(info.isIdGenerator()); } public void testIdGenerator2() throws Exception { JSDocInfo info = parse("@idGenerator {consistent} */"); assertTrue(info.isConsistentIdGenerator()); } public void testIdGenerator3() throws Exception { JSDocInfo info = parse("@idGenerator {stable} */"); assertTrue(info.isStableIdGenerator()); } public void testIdGenerator4() throws Exception { JSDocInfo info = parse("@idGenerator {mapped} */"); assertTrue(info.isMappedIdGenerator()); } public void testBadIdGenerator1() throws Exception { parse("@idGenerator {} */", "malformed @idGenerator tag"); } public void testBadIdGenerator2() throws Exception { parse("@idGenerator {impossible} */", "unknown @idGenerator parameter: impossible"); } public void testBadIdGenerator3() throws Exception { parse("@idGenerator {unique */", "malformed @idGenerator tag"); } public void testParserWithTemplateTypeNameMissing() { parse("@template */", "Bad type annotation. @template tag missing type name"); } public void testParserWithTemplateDuplicated() { parse("@template T\n@template V */", "Bad type annotation. @template tag at most once"); } public void testParserWithTwoTemplates() { parse("@template T,V */"); } public void testWhitelistedNewAnnotations() { parse("@foobar */", "illegal use of unknown JSDoc tag \"foobar\"; ignoring it"); extraAnnotations.add("foobar"); parse("@foobar */"); } public void testWhitelistedConflictingAnnotation() { extraAnnotations.add("param"); JSDocInfo info = parse("@param {number} index */"); assertTypeEquals(NUMBER_TYPE, info.getParameterType("index")); } public void testNonIdentifierAnnotation() { // Try to whitelist an annotation that is not a valid JS identifier. // It should not work. extraAnnotations.add("123"); parse("@123 */", "illegal use of unknown JSDoc tag \"\"; ignoring it"); } public void testUnsupportedJsDocSyntax1() { JSDocInfo info = parse("@param {string} [accessLevel=\"author\"] The user level */", true); assertEquals(1, info.getParameterCount()); assertTypeEquals( registry.createOptionalType(STRING_TYPE), info.getParameterType("accessLevel")); assertEquals("The user level", info.getDescriptionForParameter("accessLevel")); } public void testUnsupportedJsDocSyntax2() { JSDocInfo info = parse("@param userInfo The user info. \n" + " * @param userInfo.name The name of the user */", true); assertEquals(1, info.getParameterCount()); assertEquals("The user info.", info.getDescriptionForParameter("userInfo")); } public void testWhitelistedAnnotations() { parse( "* @addon \n" + "* @augments \n" + "* @base \n" + "* @borrows \n" + "* @bug \n" + "* @class \n" + "* @config \n" + "* @constructs \n" + "* @default \n" + "* @description \n" + "* @enhance \n" + "* @enhanceable \n" + "* @event \n" + "* @example \n" + "* @exception \n" + "* @exec \n" + "* @externs \n" + "* @field \n" + "* @function \n" + "* @hassoydelcall \n" + "* @hassoydeltemplate \n" + "* @id \n" + "* @ignore \n" + "* @inner \n" + "* @jaggerInject \n" + "* @jaggerModule \n" + "* @jaggerProvide \n" + "* @lends {string} \n" + "* @link \n" + "* @member \n" + "* @memberOf \n" + "* @modName \n" + "* @mods \n" + "* @name \n" + "* @namespace \n" + "* @ngInject \n" + "* @nocompile \n" + "* @property \n" + "* @requirecss \n" + "* @requires \n" + "* @since \n" + "* @static \n" + "* @supported\n" + "* @wizaction \n" + "* @wizmodule \n" + "*/"); } public void testJsDocInfoPosition() throws IOException { SourceFile sourceFile = SourceFile.fromCode("comment-position-test.js", " \n" + " /**\n" + " * A comment\n" + " */\n" + " function double(x) {}"); List<JSDocInfo> jsdocs = parseFull(sourceFile.getCode()); assertEquals(1, jsdocs.size()); assertEquals(6, jsdocs.get(0).getOriginalCommentPosition()); assertEquals(2, sourceFile.getLineOfOffset(jsdocs.get(0).getOriginalCommentPosition())); assertEquals(2, sourceFile.getColumnOfOffset(jsdocs.get(0).getOriginalCommentPosition())); } public void testGetOriginalCommentString() throws Exception { String comment = "* @desc This is a comment */"; JSDocInfo info = parse(comment); assertNull(info.getOriginalCommentString()); info = parse(comment, true /* parseDocumentation */); assertEquals(comment, info.getOriginalCommentString()); } public void testParseNgInject1() throws Exception { assertTrue(parse("@ngInject*/").isNgInject()); } public void testParseNgInject2() throws Exception { parse("@ngInject \n@ngInject*/", "extra @ngInject tag"); } public void testParseJaggerInject() throws Exception { assertTrue(parse("@jaggerInject*/").isJaggerInject()); } public void testParseJaggerInjectExtra() throws Exception { parse("@jaggerInject \n@jaggerInject*/", "extra @jaggerInject tag"); } public void testParseJaggerModule() throws Exception { assertTrue(parse("@jaggerModule*/").isJaggerModule()); } public void testParseJaggerModuleExtra() throws Exception { parse("@jaggerModule \n@jaggerModule*/", "extra @jaggerModule tag"); } public void testParseJaggerProvide() throws Exception { assertTrue(parse("@jaggerProvide*/").isJaggerProvide()); } public void testParseJaggerProvideExtra() throws Exception { parse("@jaggerProvide \n@jaggerProvide*/", "extra @jaggerProvide tag"); } public void testParseWizaction1() throws Exception { assertTrue(parse("@wizaction*/").isWizaction()); } public void testParseWizaction2() throws Exception { parse("@wizaction \n@wizaction*/", "extra @wizaction tag"); } public void testParseDisposes1() throws Exception { assertTrue(parse("@param x \n * @disposes x */").isDisposes()); } public void testParseDisposes2() throws Exception { parse("@param x \n * @disposes */", true, "Bad type annotation. @disposes tag missing parameter name"); } public void testParseDisposes3() throws Exception { assertTrue(parse("@param x \n @param y\n * @disposes x, y */").isDisposes()); } public void testParseDisposesUnknown() throws Exception { parse("@param x \n * @disposes x,y */", true, "Bad type annotation. @disposes parameter unknown or parameter specified multiple times"); } public void testParseDisposesMultiple() throws Exception { parse("@param x \n * @disposes x,x */", true, "Bad type annotation. @disposes parameter unknown or parameter specified multiple times"); } public void testParseDisposesAll1() throws Exception { assertTrue(parse("@param x \n * @disposes * */").isDisposes()); } public void testParseDisposesAll2() throws Exception { assertTrue(parse("@param x \n * @disposes x,* */").isDisposes()); } public void testParseDisposesAll3() throws Exception { parse("@param x \n * @disposes *, * */", true, "Bad type annotation. @disposes parameter unknown or parameter specified multiple times"); } public void testTextExtents() { parse("@return {@code foo} bar \n * baz. */", true, "Bad type annotation. type not recognized due to syntax error"); } /** * Asserts that a documentation field exists on the given marker. * * @param description The text of the documentation field expected. * @param startCharno The starting character of the text. * @param endLineno The ending line of the text. * @param endCharno The ending character of the text. * @return The marker, for chaining purposes. */ private JSDocInfo.Marker assertDocumentationInMarker(JSDocInfo.Marker marker, String description, int startCharno, int endLineno, int endCharno) { assertTrue(marker.getDescription() != null); assertEquals(description, marker.getDescription().getItem()); // Match positional information. assertEquals(marker.getAnnotation().getStartLine(), marker.getDescription().getStartLine()); assertEquals(startCharno, marker.getDescription().getPositionOnStartLine()); assertEquals(endLineno, marker.getDescription().getEndLine()); assertEquals(endCharno, marker.getDescription().getPositionOnEndLine()); return marker; } /** * Asserts that a type field exists on the given marker. * * @param typeName The name of the type expected in the type field. * @param startCharno The starting character of the type declaration. * @param hasBrackets Whether the type in the type field is expected * to have brackets. * @return The marker, for chaining purposes. */ private JSDocInfo.Marker assertTypeInMarker( JSDocInfo.Marker marker, String typeName, int startLineno, int startCharno, int endLineno, int endCharno, boolean hasBrackets) { assertTrue(marker.getType() != null); assertTrue(marker.getType().getItem().isString()); // Match the name and brackets information. String foundName = marker.getType().getItem().getString(); assertEquals(typeName, foundName); assertEquals(hasBrackets, marker.getType().hasBrackets()); // Match position information. assertEquals(startCharno, marker.getType().getPositionOnStartLine()); assertEquals(endCharno, marker.getType().getPositionOnEndLine()); assertEquals(startLineno, marker.getType().getStartLine()); assertEquals(endLineno, marker.getType().getEndLine()); return marker; } /** * Asserts that a name field exists on the given marker. * * @param name The name expected in the name field. * @param startCharno The starting character of the text. * @return The marker, for chaining purposes. */ @SuppressWarnings("deprecation") private JSDocInfo.Marker assertNameInMarker(JSDocInfo.Marker marker, String name, int startLine, int startCharno) { assertTrue(marker.getName() != null); assertEquals(name, marker.getName().getItem()); assertEquals(startCharno, marker.getName().getPositionOnStartLine()); assertEquals(startCharno + name.length(), marker.getName().getPositionOnEndLine()); assertEquals(startLine, marker.getName().getStartLine()); assertEquals(startLine, marker.getName().getEndLine()); return marker; } /** * Asserts that an annotation marker of a given annotation name * is found in the given JSDocInfo. * * @param jsdoc The JSDocInfo in which to search for the annotation marker. * @param annotationName The name/type of the annotation for which to * search. Example: "author" for an "@author" annotation. * @param startLineno The expected starting line number of the marker. * @param startCharno The expected character on the starting line. * @return The marker found, for further testing. */ private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc, String annotationName, int startLineno, int startCharno) { return assertAnnotationMarker(jsdoc, annotationName, startLineno, startCharno, 0); } /** * Asserts that the index-th annotation marker of a given annotation name * is found in the given JSDocInfo. * * @param jsdoc The JSDocInfo in which to search for the annotation marker. * @param annotationName The name/type of the annotation for which to * search. Example: "author" for an "@author" annotation. * @param startLineno The expected starting line number of the marker. * @param startCharno The expected character on the starting line. * @param index The index of the marker. * @return The marker found, for further testing. */ private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc, String annotationName, int startLineno, int startCharno, int index) { Collection<JSDocInfo.Marker> markers = jsdoc.getMarkers(); assertTrue(markers.size() > 0); int counter = 0; for (JSDocInfo.Marker marker : markers) { if (marker.getAnnotation() != null) { if (annotationName.equals(marker.getAnnotation().getItem())) { if (counter == index) { assertEquals(startLineno, marker.getAnnotation().getStartLine()); assertEquals(startCharno, marker.getAnnotation().getPositionOnStartLine()); assertEquals(startLineno, marker.getAnnotation().getEndLine()); assertEquals(startCharno + annotationName.length(), marker.getAnnotation().getPositionOnEndLine()); return marker; } counter++; } } } fail("No marker found"); return null; } private <T> void assertContains(Collection<T> collection, T item) { assertTrue(collection.contains(item)); } private List<JSDocInfo> parseFull(String code, String... warnings) { CompilerEnvirons environment = new CompilerEnvirons(); TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings); environment.setErrorReporter(testErrorReporter); environment.setRecordingComments(true); environment.setRecordingLocalJsDocComments(true); Parser p = new Parser(environment, testErrorReporter); AstRoot script = p.parse(code, null, 0); Config config = new Config(extraAnnotations, extraSuppressions, true, LanguageMode.ECMASCRIPT3, false); List<JSDocInfo> jsdocs = Lists.newArrayList(); for (Comment comment : script.getComments()) { JsDocInfoParser jsdocParser = new JsDocInfoParser( new JsDocTokenStream(comment.getValue().substring(3), comment.getLineno()), comment, null, config, testErrorReporter); jsdocParser.parse(); jsdocs.add(jsdocParser.retrieveAndResetParsedJSDocInfo()); } assertTrue("some expected warnings were not reported", testErrorReporter.hasEncounteredAllWarnings()); return jsdocs; } @SuppressWarnings("unused") private JSDocInfo parseFileOverviewWithoutDoc(String comment, String... warnings) { return parse(comment, false, true, warnings); } private JSDocInfo parseFileOverview(String comment, String... warnings) { return parse(comment, true, true, warnings); } private JSDocInfo parse(String comment, String... warnings) { return parse(comment, false, warnings); } private JSDocInfo parse(String comment, boolean parseDocumentation, String... warnings) { return parse(comment, parseDocumentation, false, warnings); } private JSDocInfo parse(String comment, boolean parseDocumentation, boolean parseFileOverview, String... warnings) { TestErrorReporter errorReporter = new TestErrorReporter(null, warnings); Config config = new Config(extraAnnotations, extraSuppressions, parseDocumentation, LanguageMode.ECMASCRIPT3, false); StaticSourceFile file = new SimpleSourceFile("testcode", false); Node associatedNode = new Node(Token.SCRIPT); associatedNode.setInputId(new InputId(file.getName())); associatedNode.setStaticSourceFile(file); JsDocInfoParser jsdocParser = new JsDocInfoParser( stream(comment), new Comment(0, 0, CommentType.JSDOC, comment), associatedNode, config, errorReporter); if (fileLevelJsDocBuilder != null) { jsdocParser.setFileLevelJsDocBuilder(fileLevelJsDocBuilder); } jsdocParser.parse(); assertTrue("expected warnings were not reported", errorReporter.hasEncounteredAllWarnings()); if (parseFileOverview) { return jsdocParser.getFileOverviewJSDocInfo(); } else { return jsdocParser.retrieveAndResetParsedJSDocInfo(); } } private Node parseType(String typeComment) { return JsDocInfoParser.parseTypeString(typeComment); } private JsDocTokenStream stream(String source) { return new JsDocTokenStream(source, 0); } private void assertTemplatizedTypeEquals(TemplateType key, JSType expected, JSTypeExpression te) { assertEquals( expected, resolve(te).getTemplateTypeMap().getTemplateType(key)); } }
public void testIssue1351() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); assertEquals(aposToQuotes("{}"), mapper.writeValueAsString(new Issue1351Bean(null, (double) 0))); // [databind#1417] assertEquals(aposToQuotes("{}"), mapper.writeValueAsString(new Issue1351NonBean(0))); }
com.fasterxml.jackson.databind.filter.JsonIncludeTest::testIssue1351
src/test/java/com/fasterxml/jackson/databind/filter/JsonIncludeTest.java
321
src/test/java/com/fasterxml/jackson/databind/filter/JsonIncludeTest.java
testIssue1351
package com.fasterxml.jackson.databind.filter; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * Unit tests for checking that alternative settings for * {@link JsonSerialize#include} annotation property work * as expected. */ public class JsonIncludeTest extends BaseMapTest { static class SimpleBean { public String getA() { return "a"; } public String getB() { return null; } } @JsonInclude(JsonInclude.Include.ALWAYS) // just to ensure default static class NoNullsBean { @JsonInclude(JsonInclude.Include.NON_NULL) public String getA() { return null; } public String getB() { return null; } } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class NonDefaultBean { String _a = "a", _b = "b"; NonDefaultBean() { } public String getA() { return _a; } public String getB() { return _b; } } // [databind#998]: Do not require no-arg constructor; but if not, defaults check // has weaker interpretation @JsonPropertyOrder({ "x", "y", "z" }) @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class NonDefaultBeanXYZ { public int x; public int y = 3; public int z = 7; NonDefaultBeanXYZ(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class MixedBean { String _a = "a", _b = "b"; MixedBean() { } public String getA() { return _a; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getB() { return _b; } } // to ensure that default values work for collections as well @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class ListBean { public List<String> strings = new ArrayList<String>(); } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class ArrayBean { public int[] ints = new int[] { 1, 2 }; } // Test to ensure that default exclusion works for fields too @JsonPropertyOrder({ "i1", "i2" }) static class DefaultIntBean { @JsonInclude(JsonInclude.Include.NON_DEFAULT) public int i1; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public Integer i2; public DefaultIntBean(int i1, Integer i2) { this.i1 = i1; this.i2 = i2; } } static class NonEmptyString { @JsonInclude(JsonInclude.Include.NON_EMPTY) public String value; public NonEmptyString(String v) { value = v; } } static class NonEmptyInt { @JsonInclude(JsonInclude.Include.NON_EMPTY) public int value; public NonEmptyInt(int v) { value = v; } } static class NonEmptyDouble { @JsonInclude(JsonInclude.Include.NON_EMPTY) public double value; public NonEmptyDouble(double v) { value = v; } } @JsonPropertyOrder({"list", "map"}) static class EmptyListMapBean { public List<String> list = Collections.emptyList(); public Map<String,String> map = Collections.emptyMap(); } // [databind#1351] static class Issue1351Bean { public final String first; public final double second; public Issue1351Bean(String first, double second) { this.first = first; this.second = second; } } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static abstract class Issue1351NonBeanParent { protected final int num; protected Issue1351NonBeanParent(int num) { this.num = num; } @JsonProperty("num") public int getNum() { return num; } } static class Issue1351NonBean extends Issue1351NonBeanParent { private String str; @JsonCreator public Issue1351NonBean(@JsonProperty("num") int num) { super(num); } public String getStr() { return str; } public void setStr(String str) { this.str = str; } } /* /********************************************************** /* Unit tests /********************************************************** */ final private ObjectMapper MAPPER = new ObjectMapper(); public void testGlobal() throws IOException { Map<String,Object> result = writeAndMap(MAPPER, new SimpleBean()); assertEquals(2, result.size()); assertEquals("a", result.get("a")); assertNull(result.get("b")); assertTrue(result.containsKey("b")); } public void testNonNullByClass() throws IOException { Map<String,Object> result = writeAndMap(MAPPER, new NoNullsBean()); assertEquals(1, result.size()); assertFalse(result.containsKey("a")); assertNull(result.get("a")); assertTrue(result.containsKey("b")); assertNull(result.get("b")); } public void testNonDefaultByClass() throws IOException { NonDefaultBean bean = new NonDefaultBean(); // need to change one of defaults bean._a = "notA"; Map<String,Object> result = writeAndMap(MAPPER, bean); assertEquals(1, result.size()); assertTrue(result.containsKey("a")); assertEquals("notA", result.get("a")); assertFalse(result.containsKey("b")); assertNull(result.get("b")); } // [databind#998] public void testNonDefaultByClassNoCtor() throws IOException { NonDefaultBeanXYZ bean = new NonDefaultBeanXYZ(1, 2, 0); String json = MAPPER.writeValueAsString(bean); assertEquals(aposToQuotes("{'x':1,'y':2}"), json); } public void testMixedMethod() throws IOException { MixedBean bean = new MixedBean(); bean._a = "xyz"; bean._b = null; Map<String,Object> result = writeAndMap(MAPPER, bean); assertEquals(1, result.size()); assertEquals("xyz", result.get("a")); assertFalse(result.containsKey("b")); bean._a = "a"; bean._b = "b"; result = writeAndMap(MAPPER, bean); assertEquals(1, result.size()); assertEquals("b", result.get("b")); assertFalse(result.containsKey("a")); } public void testDefaultForEmptyList() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new ListBean())); } // NON_DEFAULT shoud work for arrays too public void testNonEmptyDefaultArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new ArrayBean())); } public void testDefaultForIntegers() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new DefaultIntBean(0, Integer.valueOf(0)))); assertEquals("{\"i2\":1}", MAPPER.writeValueAsString(new DefaultIntBean(0, Integer.valueOf(1)))); assertEquals("{\"i1\":3}", MAPPER.writeValueAsString(new DefaultIntBean(3, Integer.valueOf(0)))); } public void testEmptyInclusionScalars() throws IOException { ObjectMapper defMapper = MAPPER; ObjectMapper inclMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY); // First, Strings StringWrapper str = new StringWrapper(""); assertEquals("{\"str\":\"\"}", defMapper.writeValueAsString(str)); assertEquals("{}", inclMapper.writeValueAsString(str)); assertEquals("{}", inclMapper.writeValueAsString(new StringWrapper())); assertEquals("{\"value\":\"x\"}", defMapper.writeValueAsString(new NonEmptyString("x"))); assertEquals("{}", defMapper.writeValueAsString(new NonEmptyString(""))); // Then numbers // 11-Nov-2015, tatu: As of Jackson 2.7, scalars should NOT be considered empty, // except for wrappers if they are `null` assertEquals("{\"value\":12}", defMapper.writeValueAsString(new NonEmptyInt(12))); assertEquals("{\"value\":0}", defMapper.writeValueAsString(new NonEmptyInt(0))); assertEquals("{\"value\":1.25}", defMapper.writeValueAsString(new NonEmptyDouble(1.25))); assertEquals("{\"value\":0.0}", defMapper.writeValueAsString(new NonEmptyDouble(0.0))); IntWrapper zero = new IntWrapper(0); assertEquals("{\"i\":0}", defMapper.writeValueAsString(zero)); assertEquals("{\"i\":0}", inclMapper.writeValueAsString(zero)); } public void testPropConfigOverridesForInclude() throws IOException { // First, with defaults, both included: EmptyListMapBean empty = new EmptyListMapBean(); assertEquals(aposToQuotes("{'list':[],'map':{}}"), MAPPER.writeValueAsString(empty)); ObjectMapper mapper; // and then change inclusion criteria for either mapper = new ObjectMapper(); mapper.configOverride(Map.class) .setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null)); assertEquals(aposToQuotes("{'list':[]}"), mapper.writeValueAsString(empty)); mapper = new ObjectMapper(); mapper.configOverride(List.class) .setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null)); assertEquals(aposToQuotes("{'map':{}}"), mapper.writeValueAsString(empty)); } // [databind#1351], [databind#1417] public void testIssue1351() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); assertEquals(aposToQuotes("{}"), mapper.writeValueAsString(new Issue1351Bean(null, (double) 0))); // [databind#1417] assertEquals(aposToQuotes("{}"), mapper.writeValueAsString(new Issue1351NonBean(0))); } }
// You are a professional Java test case writer, please create a test case named `testIssue1351` for the issue `JacksonDatabind-1417`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1417 // // ## Issue-Title: // Further issues with @JsonInclude with NON_DEFAULT // // ## Issue-Description: // (follow-up to [#1351](https://github.com/FasterXML/jackson-databind/issues/1351)) // // // Looks like there are still cases where class annotation like: // // // // ``` // @JsonInclude(JsonInclude.Include.NON_DEFAULT) // // ``` // // does not work for default `null` value suppression for `String` type (at least). // // // // public void testIssue1351() throws Exception {
321
// [databind#1351], [databind#1417]
64
312
src/test/java/com/fasterxml/jackson/databind/filter/JsonIncludeTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1417 ## Issue-Title: Further issues with @JsonInclude with NON_DEFAULT ## Issue-Description: (follow-up to [#1351](https://github.com/FasterXML/jackson-databind/issues/1351)) Looks like there are still cases where class annotation like: ``` @JsonInclude(JsonInclude.Include.NON_DEFAULT) ``` does not work for default `null` value suppression for `String` type (at least). ``` You are a professional Java test case writer, please create a test case named `testIssue1351` for the issue `JacksonDatabind-1417`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1351() throws Exception { ```
312
[ "com.fasterxml.jackson.databind.ser.PropertyBuilder" ]
ef5d2c377980a049322b51532e7dac0efcd94f7ccc3ef792a7294f03fa766cce
public void testIssue1351() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue1351` for the issue `JacksonDatabind-1417`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1417 // // ## Issue-Title: // Further issues with @JsonInclude with NON_DEFAULT // // ## Issue-Description: // (follow-up to [#1351](https://github.com/FasterXML/jackson-databind/issues/1351)) // // // Looks like there are still cases where class annotation like: // // // // ``` // @JsonInclude(JsonInclude.Include.NON_DEFAULT) // // ``` // // does not work for default `null` value suppression for `String` type (at least). // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.filter; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * Unit tests for checking that alternative settings for * {@link JsonSerialize#include} annotation property work * as expected. */ public class JsonIncludeTest extends BaseMapTest { static class SimpleBean { public String getA() { return "a"; } public String getB() { return null; } } @JsonInclude(JsonInclude.Include.ALWAYS) // just to ensure default static class NoNullsBean { @JsonInclude(JsonInclude.Include.NON_NULL) public String getA() { return null; } public String getB() { return null; } } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class NonDefaultBean { String _a = "a", _b = "b"; NonDefaultBean() { } public String getA() { return _a; } public String getB() { return _b; } } // [databind#998]: Do not require no-arg constructor; but if not, defaults check // has weaker interpretation @JsonPropertyOrder({ "x", "y", "z" }) @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class NonDefaultBeanXYZ { public int x; public int y = 3; public int z = 7; NonDefaultBeanXYZ(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class MixedBean { String _a = "a", _b = "b"; MixedBean() { } public String getA() { return _a; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getB() { return _b; } } // to ensure that default values work for collections as well @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class ListBean { public List<String> strings = new ArrayList<String>(); } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static class ArrayBean { public int[] ints = new int[] { 1, 2 }; } // Test to ensure that default exclusion works for fields too @JsonPropertyOrder({ "i1", "i2" }) static class DefaultIntBean { @JsonInclude(JsonInclude.Include.NON_DEFAULT) public int i1; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public Integer i2; public DefaultIntBean(int i1, Integer i2) { this.i1 = i1; this.i2 = i2; } } static class NonEmptyString { @JsonInclude(JsonInclude.Include.NON_EMPTY) public String value; public NonEmptyString(String v) { value = v; } } static class NonEmptyInt { @JsonInclude(JsonInclude.Include.NON_EMPTY) public int value; public NonEmptyInt(int v) { value = v; } } static class NonEmptyDouble { @JsonInclude(JsonInclude.Include.NON_EMPTY) public double value; public NonEmptyDouble(double v) { value = v; } } @JsonPropertyOrder({"list", "map"}) static class EmptyListMapBean { public List<String> list = Collections.emptyList(); public Map<String,String> map = Collections.emptyMap(); } // [databind#1351] static class Issue1351Bean { public final String first; public final double second; public Issue1351Bean(String first, double second) { this.first = first; this.second = second; } } @JsonInclude(JsonInclude.Include.NON_DEFAULT) static abstract class Issue1351NonBeanParent { protected final int num; protected Issue1351NonBeanParent(int num) { this.num = num; } @JsonProperty("num") public int getNum() { return num; } } static class Issue1351NonBean extends Issue1351NonBeanParent { private String str; @JsonCreator public Issue1351NonBean(@JsonProperty("num") int num) { super(num); } public String getStr() { return str; } public void setStr(String str) { this.str = str; } } /* /********************************************************** /* Unit tests /********************************************************** */ final private ObjectMapper MAPPER = new ObjectMapper(); public void testGlobal() throws IOException { Map<String,Object> result = writeAndMap(MAPPER, new SimpleBean()); assertEquals(2, result.size()); assertEquals("a", result.get("a")); assertNull(result.get("b")); assertTrue(result.containsKey("b")); } public void testNonNullByClass() throws IOException { Map<String,Object> result = writeAndMap(MAPPER, new NoNullsBean()); assertEquals(1, result.size()); assertFalse(result.containsKey("a")); assertNull(result.get("a")); assertTrue(result.containsKey("b")); assertNull(result.get("b")); } public void testNonDefaultByClass() throws IOException { NonDefaultBean bean = new NonDefaultBean(); // need to change one of defaults bean._a = "notA"; Map<String,Object> result = writeAndMap(MAPPER, bean); assertEquals(1, result.size()); assertTrue(result.containsKey("a")); assertEquals("notA", result.get("a")); assertFalse(result.containsKey("b")); assertNull(result.get("b")); } // [databind#998] public void testNonDefaultByClassNoCtor() throws IOException { NonDefaultBeanXYZ bean = new NonDefaultBeanXYZ(1, 2, 0); String json = MAPPER.writeValueAsString(bean); assertEquals(aposToQuotes("{'x':1,'y':2}"), json); } public void testMixedMethod() throws IOException { MixedBean bean = new MixedBean(); bean._a = "xyz"; bean._b = null; Map<String,Object> result = writeAndMap(MAPPER, bean); assertEquals(1, result.size()); assertEquals("xyz", result.get("a")); assertFalse(result.containsKey("b")); bean._a = "a"; bean._b = "b"; result = writeAndMap(MAPPER, bean); assertEquals(1, result.size()); assertEquals("b", result.get("b")); assertFalse(result.containsKey("a")); } public void testDefaultForEmptyList() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new ListBean())); } // NON_DEFAULT shoud work for arrays too public void testNonEmptyDefaultArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new ArrayBean())); } public void testDefaultForIntegers() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new DefaultIntBean(0, Integer.valueOf(0)))); assertEquals("{\"i2\":1}", MAPPER.writeValueAsString(new DefaultIntBean(0, Integer.valueOf(1)))); assertEquals("{\"i1\":3}", MAPPER.writeValueAsString(new DefaultIntBean(3, Integer.valueOf(0)))); } public void testEmptyInclusionScalars() throws IOException { ObjectMapper defMapper = MAPPER; ObjectMapper inclMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY); // First, Strings StringWrapper str = new StringWrapper(""); assertEquals("{\"str\":\"\"}", defMapper.writeValueAsString(str)); assertEquals("{}", inclMapper.writeValueAsString(str)); assertEquals("{}", inclMapper.writeValueAsString(new StringWrapper())); assertEquals("{\"value\":\"x\"}", defMapper.writeValueAsString(new NonEmptyString("x"))); assertEquals("{}", defMapper.writeValueAsString(new NonEmptyString(""))); // Then numbers // 11-Nov-2015, tatu: As of Jackson 2.7, scalars should NOT be considered empty, // except for wrappers if they are `null` assertEquals("{\"value\":12}", defMapper.writeValueAsString(new NonEmptyInt(12))); assertEquals("{\"value\":0}", defMapper.writeValueAsString(new NonEmptyInt(0))); assertEquals("{\"value\":1.25}", defMapper.writeValueAsString(new NonEmptyDouble(1.25))); assertEquals("{\"value\":0.0}", defMapper.writeValueAsString(new NonEmptyDouble(0.0))); IntWrapper zero = new IntWrapper(0); assertEquals("{\"i\":0}", defMapper.writeValueAsString(zero)); assertEquals("{\"i\":0}", inclMapper.writeValueAsString(zero)); } public void testPropConfigOverridesForInclude() throws IOException { // First, with defaults, both included: EmptyListMapBean empty = new EmptyListMapBean(); assertEquals(aposToQuotes("{'list':[],'map':{}}"), MAPPER.writeValueAsString(empty)); ObjectMapper mapper; // and then change inclusion criteria for either mapper = new ObjectMapper(); mapper.configOverride(Map.class) .setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null)); assertEquals(aposToQuotes("{'list':[]}"), mapper.writeValueAsString(empty)); mapper = new ObjectMapper(); mapper.configOverride(List.class) .setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null)); assertEquals(aposToQuotes("{'map':{}}"), mapper.writeValueAsString(empty)); } // [databind#1351], [databind#1417] public void testIssue1351() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); assertEquals(aposToQuotes("{}"), mapper.writeValueAsString(new Issue1351Bean(null, (double) 0))); // [databind#1417] assertEquals(aposToQuotes("{}"), mapper.writeValueAsString(new Issue1351NonBean(0))); } }
public void testRecursiveTypeVariablesResolve12() throws Exception { TypeAdapter<TestType2> adapter = new Gson().getAdapter(TestType2.class); assertNotNull(adapter); }
com.google.gson.internal.bind.RecursiveTypesResolveTest::testRecursiveTypeVariablesResolve12
gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java
109
gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java
testRecursiveTypeVariablesResolve12
/* * Copyright (C) 2017 Gson Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.internal.$Gson$Types; import junit.framework.TestCase; import java.io.PrintStream; import java.lang.ref.WeakReference; /** * Test fixes for infinite recursion on {@link $Gson$Types#resolve(java.lang.reflect.Type, Class, * java.lang.reflect.Type)}, described at <a href="https://github.com/google/gson/issues/440">Issue #440</a> * and similar issues. * <p> * These tests originally caused {@link StackOverflowError} because of infinite recursion on attempts to * resolve generics on types, with an intermediate types like 'Foo2&lt;? extends ? super ? extends ... ? extends A&gt;' */ public class RecursiveTypesResolveTest extends TestCase { private static class Foo1<A> { public Foo2<? extends A> foo2; } private static class Foo2<B> { public Foo1<? super B> foo1; } /** * Test simplest case of recursion. */ public void testRecursiveResolveSimple() { TypeAdapter<Foo1> adapter = new Gson().getAdapter(Foo1.class); assertNotNull(adapter); } // // Real-world samples, found in Issues #603 and #440. // public void testIssue603PrintStream() { TypeAdapter<PrintStream> adapter = new Gson().getAdapter(PrintStream.class); assertNotNull(adapter); } public void testIssue440WeakReference() throws Exception { TypeAdapter<WeakReference> adapter = new Gson().getAdapter(WeakReference.class); assertNotNull(adapter); } // // Tests belows check the behaviour of the methods changed for the fix // public void testDoubleSupertype() { assertEquals($Gson$Types.supertypeOf(Number.class), $Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class))); } public void testDoubleSubtype() { assertEquals($Gson$Types.subtypeOf(Number.class), $Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class))); } public void testSuperSubtype() { assertEquals($Gson$Types.subtypeOf(Object.class), $Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class))); } public void testSubSupertype() { assertEquals($Gson$Types.subtypeOf(Object.class), $Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class))); } // // tests for recursion while resolving type variables // private static class TestType<X> { TestType<? super X> superType; } private static class TestType2<X, Y> { TestType2<? super Y, ? super X> superReversedType; } public void testRecursiveTypeVariablesResolve1() throws Exception { TypeAdapter<TestType> adapter = new Gson().getAdapter(TestType.class); assertNotNull(adapter); } public void testRecursiveTypeVariablesResolve12() throws Exception { TypeAdapter<TestType2> adapter = new Gson().getAdapter(TestType2.class); assertNotNull(adapter); } }
// You are a professional Java test case writer, please create a test case named `testRecursiveTypeVariablesResolve12` for the issue `Gson-1128`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-1128 // // ## Issue-Title: // Fix StackOverflowError on resolving types with TypeVariable recursion // // ## Issue-Description: // Sample failing code: // // private static class TestType { // // TestType<? super X> superType; // // } // // ... // // new Gson().getAdapter(TestType.class); // // // // public void testRecursiveTypeVariablesResolve12() throws Exception {
109
16
106
gson/src/test/java/com/google/gson/internal/bind/RecursiveTypesResolveTest.java
gson/src/test/java
```markdown ## Issue-ID: Gson-1128 ## Issue-Title: Fix StackOverflowError on resolving types with TypeVariable recursion ## Issue-Description: Sample failing code: private static class TestType { TestType<? super X> superType; } ... new Gson().getAdapter(TestType.class); ``` You are a professional Java test case writer, please create a test case named `testRecursiveTypeVariablesResolve12` for the issue `Gson-1128`, utilizing the provided issue report information and the following function signature. ```java public void testRecursiveTypeVariablesResolve12() throws Exception { ```
106
[ "com.google.gson.internal.$Gson$Types" ]
efe15fbfc20d65cf79a1cc91778b573b1c6a88b0cd70c4abc9ff5dd17a6ec4b9
public void testRecursiveTypeVariablesResolve12() throws Exception
// You are a professional Java test case writer, please create a test case named `testRecursiveTypeVariablesResolve12` for the issue `Gson-1128`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-1128 // // ## Issue-Title: // Fix StackOverflowError on resolving types with TypeVariable recursion // // ## Issue-Description: // Sample failing code: // // private static class TestType { // // TestType<? super X> superType; // // } // // ... // // new Gson().getAdapter(TestType.class); // // // //
Gson
/* * Copyright (C) 2017 Gson Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.internal.$Gson$Types; import junit.framework.TestCase; import java.io.PrintStream; import java.lang.ref.WeakReference; /** * Test fixes for infinite recursion on {@link $Gson$Types#resolve(java.lang.reflect.Type, Class, * java.lang.reflect.Type)}, described at <a href="https://github.com/google/gson/issues/440">Issue #440</a> * and similar issues. * <p> * These tests originally caused {@link StackOverflowError} because of infinite recursion on attempts to * resolve generics on types, with an intermediate types like 'Foo2&lt;? extends ? super ? extends ... ? extends A&gt;' */ public class RecursiveTypesResolveTest extends TestCase { private static class Foo1<A> { public Foo2<? extends A> foo2; } private static class Foo2<B> { public Foo1<? super B> foo1; } /** * Test simplest case of recursion. */ public void testRecursiveResolveSimple() { TypeAdapter<Foo1> adapter = new Gson().getAdapter(Foo1.class); assertNotNull(adapter); } // // Real-world samples, found in Issues #603 and #440. // public void testIssue603PrintStream() { TypeAdapter<PrintStream> adapter = new Gson().getAdapter(PrintStream.class); assertNotNull(adapter); } public void testIssue440WeakReference() throws Exception { TypeAdapter<WeakReference> adapter = new Gson().getAdapter(WeakReference.class); assertNotNull(adapter); } // // Tests belows check the behaviour of the methods changed for the fix // public void testDoubleSupertype() { assertEquals($Gson$Types.supertypeOf(Number.class), $Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class))); } public void testDoubleSubtype() { assertEquals($Gson$Types.subtypeOf(Number.class), $Gson$Types.subtypeOf($Gson$Types.subtypeOf(Number.class))); } public void testSuperSubtype() { assertEquals($Gson$Types.subtypeOf(Object.class), $Gson$Types.supertypeOf($Gson$Types.subtypeOf(Number.class))); } public void testSubSupertype() { assertEquals($Gson$Types.subtypeOf(Object.class), $Gson$Types.subtypeOf($Gson$Types.supertypeOf(Number.class))); } // // tests for recursion while resolving type variables // private static class TestType<X> { TestType<? super X> superType; } private static class TestType2<X, Y> { TestType2<? super Y, ? super X> superReversedType; } public void testRecursiveTypeVariablesResolve1() throws Exception { TypeAdapter<TestType> adapter = new Gson().getAdapter(TestType.class); assertNotNull(adapter); } public void testRecursiveTypeVariablesResolve12() throws Exception { TypeAdapter<TestType2> adapter = new Gson().getAdapter(TestType2.class); assertNotNull(adapter); } }
public void testParseOctalInvalid() throws Exception{ byte [] buffer; buffer=new byte[0]; // empty byte array try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - should be at least 2 bytes long"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{0}; // 1-byte array try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - should be at least 2 bytes long"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{0,0,' '}; // not all NULs try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - not all NULs"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{' ',0,0,0}; // not all NULs try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - not all NULs"); } catch (IllegalArgumentException expected) { } buffer = "abcdef ".getBytes("UTF-8"); // Invalid input try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } buffer = "77777777777".getBytes("UTF-8"); // Invalid input - no trailer try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - no trailer"); } catch (IllegalArgumentException expected) { } buffer = " 0 07 ".getBytes("UTF-8"); // Invalid - embedded space try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded space"); } catch (IllegalArgumentException expected) { } buffer = " 0\00007 ".getBytes("UTF-8"); // Invalid - embedded NUL try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded NUL"); } catch (IllegalArgumentException expected) { } }
org.apache.commons.compress.archivers.tar.TarUtilsTest::testParseOctalInvalid
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
110
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
testParseOctalInvalid
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.tar; import junit.framework.TestCase; public class TarUtilsTest extends TestCase { public void testName(){ byte [] buff = new byte[20]; String sb1 = "abcdefghijklmnopqrstuvwxyz"; int off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length-1); assertEquals(off, 20); String sb2 = TarUtils.parseName(buff, 1, 10); assertEquals(sb2,sb1.substring(0,10)); sb2 = TarUtils.parseName(buff, 1, 19); assertEquals(sb2,sb1.substring(0,19)); buff = new byte[30]; off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length-1); assertEquals(off, 30); sb2 = TarUtils.parseName(buff, 1, buff.length-1); assertEquals(sb1, sb2); } public void testParseOctal() throws Exception{ long value; byte [] buffer; final long MAX_OCTAL = 077777777777L; // Allowed 11 digits final String maxOctal = "77777777777 "; // Maximum valid octal buffer = maxOctal.getBytes("UTF-8"); value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL, value); buffer[buffer.length-1]=0; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL, value); buffer=new byte[]{0,0}; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(0, value); buffer=new byte[]{0,' '}; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(0, value); } public void testParseOctalInvalid() throws Exception{ byte [] buffer; buffer=new byte[0]; // empty byte array try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - should be at least 2 bytes long"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{0}; // 1-byte array try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - should be at least 2 bytes long"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{0,0,' '}; // not all NULs try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - not all NULs"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{' ',0,0,0}; // not all NULs try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - not all NULs"); } catch (IllegalArgumentException expected) { } buffer = "abcdef ".getBytes("UTF-8"); // Invalid input try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } buffer = "77777777777".getBytes("UTF-8"); // Invalid input - no trailer try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - no trailer"); } catch (IllegalArgumentException expected) { } buffer = " 0 07 ".getBytes("UTF-8"); // Invalid - embedded space try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded space"); } catch (IllegalArgumentException expected) { } buffer = " 0\00007 ".getBytes("UTF-8"); // Invalid - embedded NUL try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded NUL"); } catch (IllegalArgumentException expected) { } } private void checkRoundTripOctal(final long value) { byte [] buffer = new byte[12]; long parseValue; TarUtils.formatLongOctalBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(value,parseValue); } public void testRoundTripOctal() { checkRoundTripOctal(0); checkRoundTripOctal(1); // checkRoundTripOctal(-1); // TODO What should this do? checkRoundTripOctal(077777777777L); // checkRoundTripOctal(0100000000000L); // TODO What should this do? } // Check correct trailing bytes are generated public void testTrailers() { byte [] buffer = new byte[12]; TarUtils.formatLongOctalBytes(123, buffer, 0, buffer.length); assertEquals(' ', buffer[buffer.length-1]); assertEquals('3', buffer[buffer.length-2]); // end of number TarUtils.formatOctalBytes(123, buffer, 0, buffer.length); assertEquals(0 , buffer[buffer.length-1]); assertEquals(' ', buffer[buffer.length-2]); assertEquals('3', buffer[buffer.length-3]); // end of number TarUtils.formatCheckSumOctalBytes(123, buffer, 0, buffer.length); assertEquals(' ', buffer[buffer.length-1]); assertEquals(0 , buffer[buffer.length-2]); assertEquals('3', buffer[buffer.length-3]); // end of number } public void testNegative() { byte [] buffer = new byte[22]; TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length); assertEquals("1777777777777777777777", new String(buffer)); } public void testOverflow() { byte [] buffer = new byte[8-1]; // a lot of the numbers have 8-byte buffers (nul term) TarUtils.formatUnsignedOctalString(07777777L, buffer, 0, buffer.length); assertEquals("7777777", new String(buffer)); try { TarUtils.formatUnsignedOctalString(017777777L, buffer, 0, buffer.length); fail("Should have cause IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testRoundTripNames(){ checkName(""); checkName("The quick brown fox\n"); checkName("\177"); // checkName("\0"); // does not work, because NUL is ignored // COMPRESS-114 checkName("0302-0601-3±±±F06±W220±ZB±LALALA±±±±±±±±±±CAN±±DC±±±04±060302±MOE.model"); } private void checkName(String string) { byte buff[] = new byte[100]; int len = TarUtils.formatNameBytes(string, buff, 0, buff.length); assertEquals(string, TarUtils.parseName(buff, 0, len)); } }
// You are a professional Java test case writer, please create a test case named `testParseOctalInvalid` for the issue `Compress-COMPRESS-113`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-113 // // ## Issue-Title: // TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size // // ## Issue-Description: // // TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size. // // // Although the size field in the header is 12 bytes, the last byte is supposed to be space or NUL - i.e. only 11 octal digits are allowed for the size. // // // // // public void testParseOctalInvalid() throws Exception {
110
8
60
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-113 ## Issue-Title: TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size ## Issue-Description: TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size. Although the size field in the header is 12 bytes, the last byte is supposed to be space or NUL - i.e. only 11 octal digits are allowed for the size. ``` You are a professional Java test case writer, please create a test case named `testParseOctalInvalid` for the issue `Compress-COMPRESS-113`, utilizing the provided issue report information and the following function signature. ```java public void testParseOctalInvalid() throws Exception { ```
60
[ "org.apache.commons.compress.archivers.tar.TarUtils" ]
efeec0f7ab742cf8cdcd7d80e93f26c004d443e2ae0a6732cd79c7910cc964f0
public void testParseOctalInvalid() throws Exception
// You are a professional Java test case writer, please create a test case named `testParseOctalInvalid` for the issue `Compress-COMPRESS-113`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-113 // // ## Issue-Title: // TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size // // ## Issue-Description: // // TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size. // // // Although the size field in the header is 12 bytes, the last byte is supposed to be space or NUL - i.e. only 11 octal digits are allowed for the size. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.tar; import junit.framework.TestCase; public class TarUtilsTest extends TestCase { public void testName(){ byte [] buff = new byte[20]; String sb1 = "abcdefghijklmnopqrstuvwxyz"; int off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length-1); assertEquals(off, 20); String sb2 = TarUtils.parseName(buff, 1, 10); assertEquals(sb2,sb1.substring(0,10)); sb2 = TarUtils.parseName(buff, 1, 19); assertEquals(sb2,sb1.substring(0,19)); buff = new byte[30]; off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length-1); assertEquals(off, 30); sb2 = TarUtils.parseName(buff, 1, buff.length-1); assertEquals(sb1, sb2); } public void testParseOctal() throws Exception{ long value; byte [] buffer; final long MAX_OCTAL = 077777777777L; // Allowed 11 digits final String maxOctal = "77777777777 "; // Maximum valid octal buffer = maxOctal.getBytes("UTF-8"); value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL, value); buffer[buffer.length-1]=0; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL, value); buffer=new byte[]{0,0}; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(0, value); buffer=new byte[]{0,' '}; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(0, value); } public void testParseOctalInvalid() throws Exception{ byte [] buffer; buffer=new byte[0]; // empty byte array try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - should be at least 2 bytes long"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{0}; // 1-byte array try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - should be at least 2 bytes long"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{0,0,' '}; // not all NULs try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - not all NULs"); } catch (IllegalArgumentException expected) { } buffer=new byte[]{' ',0,0,0}; // not all NULs try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - not all NULs"); } catch (IllegalArgumentException expected) { } buffer = "abcdef ".getBytes("UTF-8"); // Invalid input try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } buffer = "77777777777".getBytes("UTF-8"); // Invalid input - no trailer try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - no trailer"); } catch (IllegalArgumentException expected) { } buffer = " 0 07 ".getBytes("UTF-8"); // Invalid - embedded space try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded space"); } catch (IllegalArgumentException expected) { } buffer = " 0\00007 ".getBytes("UTF-8"); // Invalid - embedded NUL try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded NUL"); } catch (IllegalArgumentException expected) { } } private void checkRoundTripOctal(final long value) { byte [] buffer = new byte[12]; long parseValue; TarUtils.formatLongOctalBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(value,parseValue); } public void testRoundTripOctal() { checkRoundTripOctal(0); checkRoundTripOctal(1); // checkRoundTripOctal(-1); // TODO What should this do? checkRoundTripOctal(077777777777L); // checkRoundTripOctal(0100000000000L); // TODO What should this do? } // Check correct trailing bytes are generated public void testTrailers() { byte [] buffer = new byte[12]; TarUtils.formatLongOctalBytes(123, buffer, 0, buffer.length); assertEquals(' ', buffer[buffer.length-1]); assertEquals('3', buffer[buffer.length-2]); // end of number TarUtils.formatOctalBytes(123, buffer, 0, buffer.length); assertEquals(0 , buffer[buffer.length-1]); assertEquals(' ', buffer[buffer.length-2]); assertEquals('3', buffer[buffer.length-3]); // end of number TarUtils.formatCheckSumOctalBytes(123, buffer, 0, buffer.length); assertEquals(' ', buffer[buffer.length-1]); assertEquals(0 , buffer[buffer.length-2]); assertEquals('3', buffer[buffer.length-3]); // end of number } public void testNegative() { byte [] buffer = new byte[22]; TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length); assertEquals("1777777777777777777777", new String(buffer)); } public void testOverflow() { byte [] buffer = new byte[8-1]; // a lot of the numbers have 8-byte buffers (nul term) TarUtils.formatUnsignedOctalString(07777777L, buffer, 0, buffer.length); assertEquals("7777777", new String(buffer)); try { TarUtils.formatUnsignedOctalString(017777777L, buffer, 0, buffer.length); fail("Should have cause IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testRoundTripNames(){ checkName(""); checkName("The quick brown fox\n"); checkName("\177"); // checkName("\0"); // does not work, because NUL is ignored // COMPRESS-114 checkName("0302-0601-3±±±F06±W220±ZB±LALALA±±±±±±±±±±CAN±±DC±±±04±060302±MOE.model"); } private void checkName(String string) { byte buff[] = new byte[100]; int len = TarUtils.formatNameBytes(string, buff, 0, buff.length); assertEquals(string, TarUtils.parseName(buff, 0, len)); } }
@Test public void testIssue942() { List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>(); list.add(new Pair<Object, Double>(new Object() {}, new Double(0))); list.add(new Pair<Object, Double>(new Object() {}, new Double(1))); Assert.assertEquals(1, new DiscreteDistribution<Object>(list).sample(1).length); }
org.apache.commons.math3.distribution.DiscreteRealDistributionTest::testIssue942
src/test/java/org/apache/commons/math3/distribution/DiscreteRealDistributionTest.java
212
src/test/java/org/apache/commons/math3/distribution/DiscreteRealDistributionTest.java
testIssue942
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.distribution; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathArithmeticException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Pair; import org.junit.Assert; import org.junit.Test; /** * Test class for {@link DiscreteRealDistribution}. * * @version $Id: DiscreteRealDistributionTest.java 161 2013-03-07 09:47:32Z wydrych $ */ public class DiscreteRealDistributionTest { /** * The distribution object used for testing. */ private final DiscreteRealDistribution testDistribution; /** * Creates the default distribution object uded for testing. */ public DiscreteRealDistributionTest() { // Non-sorted singleton array with duplicates should be allowed. // Values with zero-probability do not extend the support. testDistribution = new DiscreteRealDistribution( new double[]{3.0, -1.0, 3.0, 7.0, -2.0, 8.0}, new double[]{0.2, 0.2, 0.3, 0.3, 0.0, 0.0}); } /** * Tests if the {@link DiscreteRealDistribution} constructor throws * exceptions for ivalid data. */ @Test public void testExceptions() { DiscreteRealDistribution invalid = null; try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0}); Assert.fail("Expected DimensionMismatchException"); } catch (DimensionMismatchException e) { } try{ invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, -1.0}); Assert.fail("Expected NotPositiveException"); } catch (NotPositiveException e) { } try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, 0.0}); Assert.fail("Expected MathArithmeticException"); } catch (MathArithmeticException e) { } try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, Double.NaN}); Assert.fail("Expected MathArithmeticException"); } catch (MathArithmeticException e) { } try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, Double.POSITIVE_INFINITY}); Assert.fail("Expected MathIllegalArgumentException"); } catch (MathIllegalArgumentException e) { } Assert.assertNull("Expected non-initialized DiscreteRealDistribution", invalid); } /** * Tests if the distribution returns proper probability values. */ @Test public void testProbability() { double[] points = new double[]{-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; double[] results = new double[]{0, 0.2, 0, 0, 0, 0.5, 0, 0, 0, 0.3, 0}; for (int p = 0; p < points.length; p++) { double density = testDistribution.probability(points[p]); Assert.assertEquals(results[p], density, 0.0); } } /** * Tests if the distribution returns proper density values. */ @Test public void testDensity() { double[] points = new double[]{-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; double[] results = new double[]{0, 0.2, 0, 0, 0, 0.5, 0, 0, 0, 0.3, 0}; for (int p = 0; p < points.length; p++) { double density = testDistribution.density(points[p]); Assert.assertEquals(results[p], density, 0.0); } } /** * Tests if the distribution returns proper cumulative probability values. */ @Test public void testCumulativeProbability() { double[] points = new double[]{-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; double[] results = new double[]{0, 0.2, 0.2, 0.2, 0.2, 0.7, 0.7, 0.7, 0.7, 1.0, 1.0}; for (int p = 0; p < points.length; p++) { double probability = testDistribution.cumulativeProbability(points[p]); Assert.assertEquals(results[p], probability, 1e-10); } } /** * Tests if the distribution returns proper mean value. */ @Test public void testGetNumericalMean() { Assert.assertEquals(3.4, testDistribution.getNumericalMean(), 1e-10); } /** * Tests if the distribution returns proper variance. */ @Test public void testGetNumericalVariance() { Assert.assertEquals(7.84, testDistribution.getNumericalVariance(), 1e-10); } /** * Tests if the distribution returns proper lower bound. */ @Test public void testGetSupportLowerBound() { Assert.assertEquals(-1, testDistribution.getSupportLowerBound(), 0); } /** * Tests if the distribution returns proper upper bound. */ @Test public void testGetSupportUpperBound() { Assert.assertEquals(7, testDistribution.getSupportUpperBound(), 0); } /** * Tests if the distribution returns properly that the support includes the * lower bound. */ @Test public void testIsSupportLowerBoundInclusive() { Assert.assertTrue(testDistribution.isSupportLowerBoundInclusive()); } /** * Tests if the distribution returns properly that the support includes the * upper bound. */ @Test public void testIsSupportUpperBoundInclusive() { Assert.assertTrue(testDistribution.isSupportUpperBoundInclusive()); } /** * Tests if the distribution returns properly that the support is connected. */ @Test public void testIsSupportConnected() { Assert.assertTrue(testDistribution.isSupportConnected()); } /** * Tests sampling. */ @Test public void testSample() { final int n = 1000000; testDistribution.reseedRandomGenerator(-334759360); // fixed seed final double[] samples = testDistribution.sample(n); Assert.assertEquals(n, samples.length); double sum = 0; double sumOfSquares = 0; for (int i = 0; i < samples.length; i++) { sum += samples[i]; sumOfSquares += samples[i] * samples[i]; } Assert.assertEquals(testDistribution.getNumericalMean(), sum / n, 1e-2); Assert.assertEquals(testDistribution.getNumericalVariance(), sumOfSquares / n - FastMath.pow(sum / n, 2), 1e-2); } @Test public void testIssue942() { List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>(); list.add(new Pair<Object, Double>(new Object() {}, new Double(0))); list.add(new Pair<Object, Double>(new Object() {}, new Double(1))); Assert.assertEquals(1, new DiscreteDistribution<Object>(list).sample(1).length); } }
// You are a professional Java test case writer, please create a test case named `testIssue942` for the issue `Math-MATH-942`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-942 // // ## Issue-Title: // DiscreteDistribution.sample(int) may throw an exception if first element of singletons of sub-class type // // ## Issue-Description: // // Creating an array with Array.newInstance(singletons.get(0).getClass(), sampleSize) in DiscreteDistribution.sample(int) is risky. An exception will be thrown if: // // // * singleons.get(0) is of type T1, an sub-class of T, and // * DiscreteDistribution.sample() returns an object which is of type T, but not of type T1. // // // To reproduce: // // // // // ``` // List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>(); // list.add(new Pair<Object, Double>(new Object() {}, new Double(0))); // list.add(new Pair<Object, Double>(new Object() {}, new Double(1))); // new DiscreteDistribution<Object>(list).sample(1); // // ``` // // // Attaching a patch. // // // // // @Test public void testIssue942() {
212
8
206
src/test/java/org/apache/commons/math3/distribution/DiscreteRealDistributionTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-942 ## Issue-Title: DiscreteDistribution.sample(int) may throw an exception if first element of singletons of sub-class type ## Issue-Description: Creating an array with Array.newInstance(singletons.get(0).getClass(), sampleSize) in DiscreteDistribution.sample(int) is risky. An exception will be thrown if: * singleons.get(0) is of type T1, an sub-class of T, and * DiscreteDistribution.sample() returns an object which is of type T, but not of type T1. To reproduce: ``` List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>(); list.add(new Pair<Object, Double>(new Object() {}, new Double(0))); list.add(new Pair<Object, Double>(new Object() {}, new Double(1))); new DiscreteDistribution<Object>(list).sample(1); ``` Attaching a patch. ``` You are a professional Java test case writer, please create a test case named `testIssue942` for the issue `Math-MATH-942`, utilizing the provided issue report information and the following function signature. ```java @Test public void testIssue942() { ```
206
[ "org.apache.commons.math3.distribution.DiscreteDistribution" ]
f0b708410a3bf7a2d2d37cf581931ae6f59d3a12463ed1b1e42c19abaf5b5f2b
@Test public void testIssue942()
// You are a professional Java test case writer, please create a test case named `testIssue942` for the issue `Math-MATH-942`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-942 // // ## Issue-Title: // DiscreteDistribution.sample(int) may throw an exception if first element of singletons of sub-class type // // ## Issue-Description: // // Creating an array with Array.newInstance(singletons.get(0).getClass(), sampleSize) in DiscreteDistribution.sample(int) is risky. An exception will be thrown if: // // // * singleons.get(0) is of type T1, an sub-class of T, and // * DiscreteDistribution.sample() returns an object which is of type T, but not of type T1. // // // To reproduce: // // // // // ``` // List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>(); // list.add(new Pair<Object, Double>(new Object() {}, new Double(0))); // list.add(new Pair<Object, Double>(new Object() {}, new Double(1))); // new DiscreteDistribution<Object>(list).sample(1); // // ``` // // // Attaching a patch. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.distribution; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathArithmeticException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Pair; import org.junit.Assert; import org.junit.Test; /** * Test class for {@link DiscreteRealDistribution}. * * @version $Id: DiscreteRealDistributionTest.java 161 2013-03-07 09:47:32Z wydrych $ */ public class DiscreteRealDistributionTest { /** * The distribution object used for testing. */ private final DiscreteRealDistribution testDistribution; /** * Creates the default distribution object uded for testing. */ public DiscreteRealDistributionTest() { // Non-sorted singleton array with duplicates should be allowed. // Values with zero-probability do not extend the support. testDistribution = new DiscreteRealDistribution( new double[]{3.0, -1.0, 3.0, 7.0, -2.0, 8.0}, new double[]{0.2, 0.2, 0.3, 0.3, 0.0, 0.0}); } /** * Tests if the {@link DiscreteRealDistribution} constructor throws * exceptions for ivalid data. */ @Test public void testExceptions() { DiscreteRealDistribution invalid = null; try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0}); Assert.fail("Expected DimensionMismatchException"); } catch (DimensionMismatchException e) { } try{ invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, -1.0}); Assert.fail("Expected NotPositiveException"); } catch (NotPositiveException e) { } try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, 0.0}); Assert.fail("Expected MathArithmeticException"); } catch (MathArithmeticException e) { } try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, Double.NaN}); Assert.fail("Expected MathArithmeticException"); } catch (MathArithmeticException e) { } try { invalid = new DiscreteRealDistribution(new double[]{1.0, 2.0}, new double[]{0.0, Double.POSITIVE_INFINITY}); Assert.fail("Expected MathIllegalArgumentException"); } catch (MathIllegalArgumentException e) { } Assert.assertNull("Expected non-initialized DiscreteRealDistribution", invalid); } /** * Tests if the distribution returns proper probability values. */ @Test public void testProbability() { double[] points = new double[]{-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; double[] results = new double[]{0, 0.2, 0, 0, 0, 0.5, 0, 0, 0, 0.3, 0}; for (int p = 0; p < points.length; p++) { double density = testDistribution.probability(points[p]); Assert.assertEquals(results[p], density, 0.0); } } /** * Tests if the distribution returns proper density values. */ @Test public void testDensity() { double[] points = new double[]{-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; double[] results = new double[]{0, 0.2, 0, 0, 0, 0.5, 0, 0, 0, 0.3, 0}; for (int p = 0; p < points.length; p++) { double density = testDistribution.density(points[p]); Assert.assertEquals(results[p], density, 0.0); } } /** * Tests if the distribution returns proper cumulative probability values. */ @Test public void testCumulativeProbability() { double[] points = new double[]{-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; double[] results = new double[]{0, 0.2, 0.2, 0.2, 0.2, 0.7, 0.7, 0.7, 0.7, 1.0, 1.0}; for (int p = 0; p < points.length; p++) { double probability = testDistribution.cumulativeProbability(points[p]); Assert.assertEquals(results[p], probability, 1e-10); } } /** * Tests if the distribution returns proper mean value. */ @Test public void testGetNumericalMean() { Assert.assertEquals(3.4, testDistribution.getNumericalMean(), 1e-10); } /** * Tests if the distribution returns proper variance. */ @Test public void testGetNumericalVariance() { Assert.assertEquals(7.84, testDistribution.getNumericalVariance(), 1e-10); } /** * Tests if the distribution returns proper lower bound. */ @Test public void testGetSupportLowerBound() { Assert.assertEquals(-1, testDistribution.getSupportLowerBound(), 0); } /** * Tests if the distribution returns proper upper bound. */ @Test public void testGetSupportUpperBound() { Assert.assertEquals(7, testDistribution.getSupportUpperBound(), 0); } /** * Tests if the distribution returns properly that the support includes the * lower bound. */ @Test public void testIsSupportLowerBoundInclusive() { Assert.assertTrue(testDistribution.isSupportLowerBoundInclusive()); } /** * Tests if the distribution returns properly that the support includes the * upper bound. */ @Test public void testIsSupportUpperBoundInclusive() { Assert.assertTrue(testDistribution.isSupportUpperBoundInclusive()); } /** * Tests if the distribution returns properly that the support is connected. */ @Test public void testIsSupportConnected() { Assert.assertTrue(testDistribution.isSupportConnected()); } /** * Tests sampling. */ @Test public void testSample() { final int n = 1000000; testDistribution.reseedRandomGenerator(-334759360); // fixed seed final double[] samples = testDistribution.sample(n); Assert.assertEquals(n, samples.length); double sum = 0; double sumOfSquares = 0; for (int i = 0; i < samples.length; i++) { sum += samples[i]; sumOfSquares += samples[i] * samples[i]; } Assert.assertEquals(testDistribution.getNumericalMean(), sum / n, 1e-2); Assert.assertEquals(testDistribution.getNumericalVariance(), sumOfSquares / n - FastMath.pow(sum / n, 2), 1e-2); } @Test public void testIssue942() { List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>(); list.add(new Pair<Object, Double>(new Object() {}, new Double(0))); list.add(new Pair<Object, Double>(new Object() {}, new Double(1))); Assert.assertEquals(1, new DiscreteDistribution<Object>(list).sample(1).length); } }
public void testIssue701() { // Check ASCII art in license comments. String ascii = "/**\n" + " * @preserve\n" + " This\n" + " is\n" + " ASCII ART\n" + "*/"; String result = "/*\n\n" + " This\n" + " is\n" + " ASCII ART\n" + "*/\n"; testSame(createCompilerOptions(), ascii); assertEquals(result, lastCompiler.toSource()); }
com.google.javascript.jscomp.IntegrationTest::testIssue701
test/com/google/javascript/jscomp/IntegrationTest.java
1,674
test/com/google/javascript/jscomp/IntegrationTest.java
testIssue701
/* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; import java.util.List; /** * Tests for {@link PassFactory}. * * @author nicksantos@google.com (Nick Santos) */ public class IntegrationTest extends TestCase { /** Externs for the test */ private final List<SourceFile> DEFAULT_EXTERNS = ImmutableList.of( SourceFile.fromCode("externs", "var arguments;\n" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {string} */ Window.prototype.offsetWidth;\n" + "/** @type {Window} */ var window;\n" + "/** @nosideeffects */ function noSideEffects() {}\n" + "/** @constructor\n * @nosideeffects */ function Widget() {}\n" + "/** @modifies {this} */ Widget.prototype.go = function() {};\n" + "/** @return {string} */ var widgetToken = function() {};\n")); private List<SourceFile> externs = DEFAULT_EXTERNS; private static final String CLOSURE_BOILERPLATE = "/** @define {boolean} */ var COMPILED = false; var goog = {};" + "goog.exportSymbol = function() {};"; private static final String CLOSURE_COMPILED = "var COMPILED = true; var goog$exportSymbol = function() {};"; // The most recently used compiler. private Compiler lastCompiler; @Override public void setUp() { externs = DEFAULT_EXTERNS; lastCompiler = null; } public void testBug1949424() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO'); FOO.bar = 3;", CLOSURE_COMPILED + "var FOO$bar = 3;"); } public void testBug1949424_v2() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO.BAR'); FOO.BAR = 3;", CLOSURE_COMPILED + "var FOO$BAR = 3;"); } public void testBug1956277() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.inlineVariables = true; test(options, "var CONST = {}; CONST.bar = null;" + "function f(url) { CONST.bar = url; }", "var CONST$bar = null; function f(url) { CONST$bar = url; }"); } public void testBug1962380() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.inlineVariables = true; options.generateExports = true; test(options, CLOSURE_BOILERPLATE + "/** @export */ goog.CONSTANT = 1;" + "var x = goog.CONSTANT;", "(function() {})('goog.CONSTANT', 1);" + "var x = 1;"); } public void testBug2410122() { CompilerOptions options = createCompilerOptions(); options.generateExports = true; options.closurePass = true; test(options, "var goog = {};" + "function F() {}" + "/** @export */ function G() { goog.base(this); } " + "goog.inherits(G, F);", "var goog = {};" + "function F() {}" + "function G() { F.call(this); } " + "goog.inherits(G, F); goog.exportSymbol('G', G);"); } public void testIssue90() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; options.inlineVariables = true; options.removeDeadCode = true; test(options, "var x; x && alert(1);", ""); } public void testClosurePassOff() { CompilerOptions options = createCompilerOptions(); options.closurePass = false; testSame( options, "var goog = {}; goog.require = function(x) {}; goog.require('foo');"); testSame( options, "var goog = {}; goog.getCssName = function(x) {};" + "goog.getCssName('foo');"); } public void testClosurePassOn() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; test( options, "var goog = {}; goog.require = function(x) {}; goog.require('foo');", ProcessClosurePrimitives.MISSING_PROVIDE_ERROR); test( options, "/** @define {boolean} */ var COMPILED = false;" + "var goog = {}; goog.getCssName = function(x) {};" + "goog.getCssName('foo');", "var COMPILED = true;" + "var goog = {}; goog.getCssName = function(x) {};" + "'foo';"); } public void testCssNameCheck() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.checkMissingGetCssNameLevel = CheckLevel.ERROR; options.checkMissingGetCssNameBlacklist = "foo"; test(options, "var x = 'foo';", CheckMissingGetCssName.MISSING_GETCSSNAME); } public void testBug2592659() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.checkTypes = true; options.checkMissingGetCssNameLevel = CheckLevel.WARNING; options.checkMissingGetCssNameBlacklist = "foo"; test(options, "var goog = {};\n" + "/**\n" + " * @param {string} className\n" + " * @param {string=} opt_modifier\n" + " * @return {string}\n" + "*/\n" + "goog.getCssName = function(className, opt_modifier) {}\n" + "var x = goog.getCssName(123, 'a');", TypeValidator.TYPE_MISMATCH_WARNING); } public void testTypedefBeforeOwner1() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; test(options, "goog.provide('foo.Bar.Type');\n" + "goog.provide('foo.Bar');\n" + "/** @typedef {number} */ foo.Bar.Type;\n" + "foo.Bar = function() {};", "var foo = {}; foo.Bar.Type; foo.Bar = function() {};"); } public void testTypedefBeforeOwner2() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.collapseProperties = true; test(options, "goog.provide('foo.Bar.Type');\n" + "goog.provide('foo.Bar');\n" + "/** @typedef {number} */ foo.Bar.Type;\n" + "foo.Bar = function() {};", "var foo$Bar$Type; var foo$Bar = function() {};"); } public void testExportedNames() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.variableRenaming = VariableRenamingPolicy.ALL; test(options, "/** @define {boolean} */ var COMPILED = false;" + "var goog = {}; goog.exportSymbol('b', goog);", "var a = true; var c = {}; c.exportSymbol('b', c);"); test(options, "/** @define {boolean} */ var COMPILED = false;" + "var goog = {}; goog.exportSymbol('a', goog);", "var b = true; var c = {}; c.exportSymbol('a', c);"); } public void testCheckGlobalThisOn() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = true; options.checkGlobalThisLevel = CheckLevel.ERROR; test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testSusiciousCodeOff() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = false; options.checkGlobalThisLevel = CheckLevel.ERROR; test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOff() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = true; options.checkGlobalThisLevel = CheckLevel.OFF; testSame(options, "function f() { this.y = 3; }"); } public void testCheckRequiresAndCheckProvidesOff() { testSame(createCompilerOptions(), new String[] { "/** @constructor */ function Foo() {}", "new Foo();" }); } public void testCheckRequiresOn() { CompilerOptions options = createCompilerOptions(); options.checkRequires = CheckLevel.ERROR; test(options, new String[] { "/** @constructor */ function Foo() {}", "new Foo();" }, CheckRequiresForConstructors.MISSING_REQUIRE_WARNING); } public void testCheckProvidesOn() { CompilerOptions options = createCompilerOptions(); options.checkProvides = CheckLevel.ERROR; test(options, new String[] { "/** @constructor */ function Foo() {}", "new Foo();" }, CheckProvides.MISSING_PROVIDE_WARNING); } public void testGenerateExportsOff() { testSame(createCompilerOptions(), "/** @export */ function f() {}"); } public void testGenerateExportsOn() { CompilerOptions options = createCompilerOptions(); options.generateExports = true; test(options, "/** @export */ function f() {}", "/** @export */ function f() {} goog.exportSymbol('f', f);"); } public void testExportTestFunctionsOff() { testSame(createCompilerOptions(), "function testFoo() {}"); } public void testExportTestFunctionsOn() { CompilerOptions options = createCompilerOptions(); options.exportTestFunctions = true; test(options, "function testFoo() {}", "/** @export */ function testFoo() {}" + "goog.exportSymbol('testFoo', testFoo);"); } public void testExpose() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); test(options, "var x = {eeny: 1, /** @expose */ meeny: 2};" + "/** @constructor */ var Foo = function() {};" + "/** @expose */ Foo.prototype.miny = 3;" + "Foo.prototype.moe = 4;" + "function moe(a, b) { return a.meeny + b.miny; }" + "window['x'] = x;" + "window['Foo'] = Foo;" + "window['moe'] = moe;", "function a(){}" + "a.prototype.miny=3;" + "window.x={a:1,meeny:2};" + "window.Foo=a;" + "window.moe=function(b,c){" + " return b.meeny+c.miny" + "}"); } public void testCheckSymbolsOff() { CompilerOptions options = createCompilerOptions(); testSame(options, "x = 3;"); } public void testCheckSymbolsOn() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = true; test(options, "x = 3;", VarCheck.UNDEFINED_VAR_ERROR); } public void testCheckReferencesOff() { CompilerOptions options = createCompilerOptions(); testSame(options, "x = 3; var x = 5;"); } public void testCheckReferencesOn() { CompilerOptions options = createCompilerOptions(); options.aggressiveVarCheck = CheckLevel.ERROR; test(options, "x = 3; var x = 5;", VariableReferenceCheck.UNDECLARED_REFERENCE); } public void testInferTypes() { CompilerOptions options = createCompilerOptions(); options.inferTypes = true; options.checkTypes = false; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('Foo'); /** @enum */ Foo = {a: 3};", TypeCheck.ENUM_NOT_CONSTANT); assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0); // This does not generate a warning. test(options, "/** @type {number} */ var n = window.name;", "var n = window.name;"); assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0); } public void testTypeCheckAndInference() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; test(options, "/** @type {number} */ var n = window.name;", TypeValidator.TYPE_MISMATCH_WARNING); assertTrue(lastCompiler.getErrorManager().getTypedPercent() > 0); } public void testTypeNameParser() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; test(options, "/** @type {n} */ var n = window.name;", RhinoErrorReporter.TYPE_PARSE_ERROR); } // This tests that the TypedScopeCreator is memoized so that it only creates a // Scope object once for each scope. If, when type inference requests a scope, // it creates a new one, then multiple JSType objects end up getting created // for the same local type, and ambiguate will rename the last statement to // o.a(o.a, o.a), which is bad. public void testMemoizedTypedScopeCreator() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.ambiguateProperties = true; options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED; test(options, "function someTest() {\n" + " /** @constructor */\n" + " function Foo() { this.instProp = 3; }\n" + " Foo.prototype.protoProp = function(a, b) {};\n" + " /** @constructor\n @extends Foo */\n" + " function Bar() {}\n" + " goog.inherits(Bar, Foo);\n" + " var o = new Bar();\n" + " o.protoProp(o.protoProp, o.instProp);\n" + "}", "function someTest() {\n" + " function Foo() { this.b = 3; }\n" + " Foo.prototype.a = function(a, b) {};\n" + " function Bar() {}\n" + " goog.c(Bar, Foo);\n" + " var o = new Bar();\n" + " o.a(o.a, o.b);\n" + "}"); } public void testCheckTypes() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; test(options, "var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testReplaceCssNames() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.gatherCssNames = true; test(options, "/** @define {boolean} */\n" + "var COMPILED = false;\n" + "goog.setCssNameMapping({'foo':'bar'});\n" + "function getCss() {\n" + " return goog.getCssName('foo');\n" + "}", "var COMPILED = true;\n" + "function getCss() {\n" + " return \"bar\";" + "}"); assertEquals( ImmutableMap.of("foo", new Integer(1)), lastCompiler.getPassConfig().getIntermediateState().cssNames); } public void testRemoveClosureAsserts() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; testSame(options, "var goog = {};" + "goog.asserts.assert(goog);"); options.removeClosureAsserts = true; test(options, "var goog = {};" + "goog.asserts.assert(goog);", "var goog = {};"); } public void testDeprecation() { String code = "/** @deprecated */ function f() { } function g() { f(); }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.setWarningLevel(DiagnosticGroups.DEPRECATED, CheckLevel.ERROR); testSame(options, code); options.checkTypes = true; test(options, code, CheckAccessControls.DEPRECATED_NAME); } public void testVisibility() { String[] code = { "/** @private */ function f() { }", "function g() { f(); }" }; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.setWarningLevel(DiagnosticGroups.VISIBILITY, CheckLevel.ERROR); testSame(options, code); options.checkTypes = true; test(options, code, CheckAccessControls.BAD_PRIVATE_GLOBAL_ACCESS); } public void testUnreachableCode() { String code = "function f() { return \n 3; }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.checkUnreachableCode = CheckLevel.ERROR; test(options, code, CheckUnreachableCode.UNREACHABLE_CODE); } public void testMissingReturn() { String code = "/** @return {number} */ function f() { if (f) { return 3; } }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.checkMissingReturn = CheckLevel.ERROR; testSame(options, code); options.checkTypes = true; test(options, code, CheckMissingReturn.MISSING_RETURN_STATEMENT); } public void testIdGenerators() { String code = "function f() {} f('id');"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.idGenerators = Sets.newHashSet("f"); test(options, code, "function f() {} 'a';"); } public void testOptimizeArgumentsArray() { String code = "function f() { return arguments[0]; }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.optimizeArgumentsArray = true; String argName = "JSCompiler_OptimizeArgumentsArray_p0"; test(options, code, "function f(" + argName + ") { return " + argName + "; }"); } public void testOptimizeParameters() { String code = "function f(a) { return a; } f(true);"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.optimizeParameters = true; test(options, code, "function f() { var a = true; return a;} f();"); } public void testOptimizeReturns() { String code = "function f(a) { return a; } f(true);"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.optimizeReturns = true; test(options, code, "function f(a) {return;} f(true);"); } public void testRemoveAbstractMethods() { String code = CLOSURE_BOILERPLATE + "var x = {}; x.foo = goog.abstractMethod; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.closurePass = true; options.collapseProperties = true; test(options, code, CLOSURE_COMPILED + " var x$bar = 3;"); } public void testCollapseProperties1() { String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseProperties = true; test(options, code, "var x$FOO = 5; var x$bar = 3;"); } public void testCollapseProperties2() { String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseProperties = true; options.collapseObjectLiterals = true; test(options, code, "var x$FOO = 5; var x$bar = 3;"); } public void testCollapseObjectLiteral1() { // Verify collapseObjectLiterals does nothing in global scope String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseObjectLiterals = true; testSame(options, code); } public void testCollapseObjectLiteral2() { String code = "function f() {var x = {}; x.FOO = 5; x.bar = 3;}"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseObjectLiterals = true; test(options, code, "function f(){" + "var JSCompiler_object_inline_FOO_0;" + "var JSCompiler_object_inline_bar_1;" + "JSCompiler_object_inline_FOO_0=5;" + "JSCompiler_object_inline_bar_1=3}"); } public void testTightenTypesWithoutTypeCheck() { CompilerOptions options = createCompilerOptions(); options.tightenTypes = true; test(options, "", DefaultPassConfig.TIGHTEN_TYPES_WITHOUT_TYPE_CHECK); } public void testDisambiguateProperties() { String code = "/** @constructor */ function Foo(){} Foo.prototype.bar = 3;" + "/** @constructor */ function Baz(){} Baz.prototype.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.disambiguateProperties = true; options.checkTypes = true; test(options, code, "function Foo(){} Foo.prototype.Foo_prototype$bar = 3;" + "function Baz(){} Baz.prototype.Baz_prototype$bar = 3;"); } public void testMarkPureCalls() { String testCode = "function foo() {} foo();"; CompilerOptions options = createCompilerOptions(); options.removeDeadCode = true; testSame(options, testCode); options.computeFunctionSideEffects = true; test(options, testCode, "function foo() {}"); } public void testMarkNoSideEffects() { String testCode = "noSideEffects();"; CompilerOptions options = createCompilerOptions(); options.removeDeadCode = true; testSame(options, testCode); options.markNoSideEffectCalls = true; test(options, testCode, ""); } public void testChainedCalls() { CompilerOptions options = createCompilerOptions(); options.chainCalls = true; test( options, "/** @constructor */ function Foo() {} " + "Foo.prototype.bar = function() { return this; }; " + "var f = new Foo();" + "f.bar(); " + "f.bar(); ", "function Foo() {} " + "Foo.prototype.bar = function() { return this; }; " + "var f = new Foo();" + "f.bar().bar();"); } public void testExtraAnnotationNames() { CompilerOptions options = createCompilerOptions(); options.setExtraAnnotationNames(Sets.newHashSet("TagA", "TagB")); test( options, "/** @TagA */ var f = new Foo(); /** @TagB */ f.bar();", "var f = new Foo(); f.bar();"); } public void testDevirtualizePrototypeMethods() { CompilerOptions options = createCompilerOptions(); options.devirtualizePrototypeMethods = true; test( options, "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.bar = function() {};" + "(new Foo()).bar();", "var Foo = function() {};" + "var JSCompiler_StaticMethods_bar = " + " function(JSCompiler_StaticMethods_bar$self) {};" + "JSCompiler_StaticMethods_bar(new Foo());"); } public void testCheckConsts() { CompilerOptions options = createCompilerOptions(); options.inlineConstantVars = true; test(options, "var FOO = true; FOO = false", ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testAllChecksOn() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = true; options.checkControlStructures = true; options.checkRequires = CheckLevel.ERROR; options.checkProvides = CheckLevel.ERROR; options.generateExports = true; options.exportTestFunctions = true; options.closurePass = true; options.checkMissingGetCssNameLevel = CheckLevel.ERROR; options.checkMissingGetCssNameBlacklist = "goog"; options.syntheticBlockStartMarker = "synStart"; options.syntheticBlockEndMarker = "synEnd"; options.checkSymbols = true; options.aggressiveVarCheck = CheckLevel.ERROR; options.processObjectPropertyString = true; options.collapseProperties = true; test(options, CLOSURE_BOILERPLATE, CLOSURE_COMPILED); } public void testTypeCheckingWithSyntheticBlocks() { CompilerOptions options = createCompilerOptions(); options.syntheticBlockStartMarker = "synStart"; options.syntheticBlockEndMarker = "synEnd"; options.checkTypes = true; // We used to have a bug where the CFG drew an // edge straight from synStart to f(progress). // If that happens, then progress will get type {number|undefined}. testSame( options, "/** @param {number} x */ function f(x) {}" + "function g() {" + " synStart('foo');" + " var progress = 1;" + " f(progress);" + " synEnd('foo');" + "}"); } public void testCompilerDoesNotBlowUpIfUndefinedSymbols() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = true; // Disable the undefined variable check. options.setWarningLevel( DiagnosticGroup.forType(VarCheck.UNDEFINED_VAR_ERROR), CheckLevel.OFF); // The compiler used to throw an IllegalStateException on this. testSame(options, "var x = {foo: y};"); } // Make sure that if we change variables which are constant to have // $$constant appended to their names, we remove that tag before // we finish. public void testConstantTagsMustAlwaysBeRemoved() { CompilerOptions options = createCompilerOptions(); options.variableRenaming = VariableRenamingPolicy.LOCAL; String originalText = "var G_GEO_UNKNOWN_ADDRESS=1;\n" + "function foo() {" + " var localVar = 2;\n" + " if (G_GEO_UNKNOWN_ADDRESS == localVar) {\n" + " alert(\"A\"); }}"; String expectedText = "var G_GEO_UNKNOWN_ADDRESS=1;" + "function foo(){var a=2;if(G_GEO_UNKNOWN_ADDRESS==a){alert(\"A\")}}"; test(options, originalText, expectedText); } public void testClosurePassPreservesJsDoc() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('Foo'); /** @constructor */ Foo = function() {};" + "var x = new Foo();", "var COMPILED=true;var goog={};goog.exportSymbol=function(){};" + "var Foo=function(){};var x=new Foo"); test(options, CLOSURE_BOILERPLATE + "goog.provide('Foo'); /** @enum */ Foo = {a: 3};", TypeCheck.ENUM_NOT_CONSTANT); } public void testProvidedNamespaceIsConst() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo'); " + "function f() { foo = {};}", "var foo = {}; function f() { foo = {}; }", ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testProvidedNamespaceIsConst2() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo.bar'); " + "function f() { foo.bar = {};}", "var foo$bar = {};" + "function f() { foo$bar = {}; }", ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testProvidedNamespaceIsConst3() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; " + "goog.provide('foo.bar'); goog.provide('foo.bar.baz'); " + "/** @constructor */ foo.bar = function() {};" + "/** @constructor */ foo.bar.baz = function() {};", "var foo$bar = function(){};" + "var foo$bar$baz = function(){};"); } public void testProvidedNamespaceIsConst4() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo.Bar'); " + "var foo = {}; foo.Bar = {};", "var foo = {}; var foo = {}; foo.Bar = {};"); } public void testProvidedNamespaceIsConst5() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo.Bar'); " + "foo = {}; foo.Bar = {};", "var foo = {}; foo = {}; foo.Bar = {};"); } public void testProcessDefinesAlwaysOn() { test(createCompilerOptions(), "/** @define {boolean} */ var HI = true; HI = false;", "var HI = false;false;"); } public void testProcessDefinesAdditionalReplacements() { CompilerOptions options = createCompilerOptions(); options.setDefineToBooleanLiteral("HI", false); test(options, "/** @define {boolean} */ var HI = true;", "var HI = false;"); } public void testReplaceMessages() { CompilerOptions options = createCompilerOptions(); String prefix = "var goog = {}; goog.getMsg = function() {};"; testSame(options, prefix + "var MSG_HI = goog.getMsg('hi');"); options.messageBundle = new EmptyMessageBundle(); test(options, prefix + "/** @desc xyz */ var MSG_HI = goog.getMsg('hi');", prefix + "var MSG_HI = 'hi';"); } public void testCheckGlobalNames() { CompilerOptions options = createCompilerOptions(); options.checkGlobalNamesLevel = CheckLevel.ERROR; test(options, "var x = {}; var y = x.z;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testInlineGetters() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() {} Foo.prototype.bar = function() { return 3; };" + "var x = new Foo(); x.bar();"; testSame(options, code); options.inlineGetters = true; test(options, code, "function Foo() {} Foo.prototype.bar = function() { return 3 };" + "var x = new Foo(); 3;"); } public void testInlineGettersWithAmbiguate() { CompilerOptions options = createCompilerOptions(); String code = "/** @constructor */" + "function Foo() {}" + "/** @type {number} */ Foo.prototype.field;" + "Foo.prototype.getField = function() { return this.field; };" + "/** @constructor */" + "function Bar() {}" + "/** @type {string} */ Bar.prototype.field;" + "Bar.prototype.getField = function() { return this.field; };" + "new Foo().getField();" + "new Bar().getField();"; testSame(options, code); options.inlineGetters = true; test(options, code, "function Foo() {}" + "Foo.prototype.field;" + "Foo.prototype.getField = function() { return this.field; };" + "function Bar() {}" + "Bar.prototype.field;" + "Bar.prototype.getField = function() { return this.field; };" + "new Foo().field;" + "new Bar().field;"); options.checkTypes = true; options.ambiguateProperties = true; // Propagating the wrong type information may cause ambiguate properties // to generate bad code. testSame(options, code); } public void testInlineVariables() { CompilerOptions options = createCompilerOptions(); String code = "function foo() {} var x = 3; foo(x);"; testSame(options, code); options.inlineVariables = true; test(options, code, "(function foo() {})(3);"); options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC; test(options, code, DefaultPassConfig.CANNOT_USE_PROTOTYPE_AND_VAR); } public void testInlineConstants() { CompilerOptions options = createCompilerOptions(); String code = "function foo() {} var x = 3; foo(x); var YYY = 4; foo(YYY);"; testSame(options, code); options.inlineConstantVars = true; test(options, code, "function foo() {} var x = 3; foo(x); foo(4);"); } public void testMinimizeExits() { CompilerOptions options = createCompilerOptions(); String code = "function f() {" + " if (window.foo) return; window.h(); " + "}"; testSame(options, code); options.foldConstants = true; test( options, code, "function f() {" + " window.foo || window.h(); " + "}"); } public void testFoldConstants() { CompilerOptions options = createCompilerOptions(); String code = "if (true) { window.foo(); }"; testSame(options, code); options.foldConstants = true; test(options, code, "window.foo();"); } public void testRemoveUnreachableCode() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return; f(); }"; testSame(options, code); options.removeDeadCode = true; test(options, code, "function f() {}"); } public void testRemoveUnusedPrototypeProperties1() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() {} " + "Foo.prototype.bar = function() { return new Foo(); };"; testSame(options, code); options.removeUnusedPrototypeProperties = true; test(options, code, "function Foo() {}"); } public void testRemoveUnusedPrototypeProperties2() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() {} " + "Foo.prototype.bar = function() { return new Foo(); };" + "function f(x) { x.bar(); }"; testSame(options, code); options.removeUnusedPrototypeProperties = true; testSame(options, code); options.removeUnusedVars = true; test(options, code, ""); } public void testSmartNamePass() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() { this.bar(); } " + "Foo.prototype.bar = function() { return Foo(); };"; testSame(options, code); options.smartNameRemoval = true; test(options, code, ""); } public void testDeadAssignmentsElimination() { CompilerOptions options = createCompilerOptions(); String code = "function f() { var x = 3; 4; x = 5; return x; } f(); "; testSame(options, code); options.deadAssignmentElimination = true; testSame(options, code); options.removeUnusedVars = true; test(options, code, "function f() { var x = 3; 4; x = 5; return x; } f();"); } public void testInlineFunctions() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return 3; } f(); "; testSame(options, code); options.inlineFunctions = true; test(options, code, "3;"); } public void testRemoveUnusedVars1() { CompilerOptions options = createCompilerOptions(); String code = "function f(x) {} f();"; testSame(options, code); options.removeUnusedVars = true; test(options, code, "function f() {} f();"); } public void testRemoveUnusedVars2() { CompilerOptions options = createCompilerOptions(); String code = "(function f(x) {})();var g = function() {}; g();"; testSame(options, code); options.removeUnusedVars = true; test(options, code, "(function() {})();var g = function() {}; g();"); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED; test(options, code, "(function f() {})();var g = function $g$() {}; g();"); } public void testCrossModuleCodeMotion() { CompilerOptions options = createCompilerOptions(); String[] code = new String[] { "var x = 1;", "x;", }; testSame(options, code); options.crossModuleCodeMotion = true; test(options, code, new String[] { "", "var x = 1; x;", }); } public void testCrossModuleMethodMotion() { CompilerOptions options = createCompilerOptions(); String[] code = new String[] { "var Foo = function() {}; Foo.prototype.bar = function() {};" + "var x = new Foo();", "x.bar();", }; testSame(options, code); options.crossModuleMethodMotion = true; test(options, code, new String[] { CrossModuleMethodMotion.STUB_DECLARATIONS + "var Foo = function() {};" + "Foo.prototype.bar=JSCompiler_stubMethod(0); var x=new Foo;", "Foo.prototype.bar=JSCompiler_unstubMethod(0,function(){}); x.bar()", }); } public void testFlowSensitiveInlineVariables1() { CompilerOptions options = createCompilerOptions(); String code = "function f() { var x = 3; x = 5; return x; }"; testSame(options, code); options.flowSensitiveInlineVariables = true; test(options, code, "function f() { var x = 3; return 5; }"); String unusedVar = "function f() { var x; x = 5; return x; } f()"; test(options, unusedVar, "function f() { var x; return 5; } f()"); options.removeUnusedVars = true; test(options, unusedVar, "function f() { return 5; } f()"); } public void testFlowSensitiveInlineVariables2() { CompilerOptions options = createCompilerOptions(); CompilationLevel.SIMPLE_OPTIMIZATIONS .setOptionsForCompilationLevel(options); test(options, "function f () {\n" + " var ab = 0;\n" + " ab += '-';\n" + " alert(ab);\n" + "}", "function f () {\n" + " alert('0-');\n" + "}"); } public void testCollapseAnonymousFunctions() { CompilerOptions options = createCompilerOptions(); String code = "var f = function() {};"; testSame(options, code); options.collapseAnonymousFunctions = true; test(options, code, "function f() {}"); } public void testMoveFunctionDeclarations() { CompilerOptions options = createCompilerOptions(); String code = "var x = f(); function f() { return 3; }"; testSame(options, code); options.moveFunctionDeclarations = true; test(options, code, "function f() { return 3; } var x = f();"); } public void testNameAnonymousFunctions() { CompilerOptions options = createCompilerOptions(); String code = "var f = function() {};"; testSame(options, code); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.MAPPED; test(options, code, "var f = function $() {}"); assertNotNull(lastCompiler.getResult().namedAnonFunctionMap); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED; test(options, code, "var f = function $f$() {}"); assertNull(lastCompiler.getResult().namedAnonFunctionMap); } public void testExtractPrototypeMemberDeclarations() { CompilerOptions options = createCompilerOptions(); String code = "var f = function() {};"; String expected = "var a; var b = function() {}; a = b.prototype;"; for (int i = 0; i < 10; i++) { code += "f.prototype.a = " + i + ";"; expected += "a.a = " + i + ";"; } testSame(options, code); options.extractPrototypeMemberDeclarations = true; options.variableRenaming = VariableRenamingPolicy.ALL; test(options, code, expected); options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC; options.variableRenaming = VariableRenamingPolicy.OFF; testSame(options, code); } public void testDevirtualizationAndExtractPrototypeMemberDeclarations() { CompilerOptions options = createCompilerOptions(); options.devirtualizePrototypeMethods = true; options.collapseAnonymousFunctions = true; options.extractPrototypeMemberDeclarations = true; options.variableRenaming = VariableRenamingPolicy.ALL; String code = "var f = function() {};"; String expected = "var a; function b() {} a = b.prototype;"; for (int i = 0; i < 10; i++) { code += "f.prototype.argz = function() {arguments};"; code += "f.prototype.devir" + i + " = function() {};"; char letter = (char) ('d' + i); expected += "a.argz = function() {arguments};"; expected += "function " + letter + "(c){}"; } code += "var F = new f(); F.argz();"; expected += "var n = new b(); n.argz();"; for (int i = 0; i < 10; i++) { code += "F.devir" + i + "();"; char letter = (char) ('d' + i); expected += letter + "(n);"; } test(options, code, expected); } public void testCoalesceVariableNames() { CompilerOptions options = createCompilerOptions(); String code = "function f() {var x = 3; var y = x; var z = y; return z;}"; testSame(options, code); options.coalesceVariableNames = true; test(options, code, "function f() {var x = 3; x = x; x = x; return x;}"); } public void testPropertyRenaming() { CompilerOptions options = createCompilerOptions(); options.propertyAffinity = true; String code = "function f() { return this.foo + this['bar'] + this.Baz; }" + "f.prototype.bar = 3; f.prototype.Baz = 3;"; String heuristic = "function f() { return this.foo + this['bar'] + this.a; }" + "f.prototype.bar = 3; f.prototype.a = 3;"; String aggHeuristic = "function f() { return this.foo + this['b'] + this.a; } " + "f.prototype.b = 3; f.prototype.a = 3;"; String all = "function f() { return this.b + this['bar'] + this.a; }" + "f.prototype.c = 3; f.prototype.a = 3;"; testSame(options, code); options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC; test(options, code, heuristic); options.propertyRenaming = PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC; test(options, code, aggHeuristic); options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED; test(options, code, all); } public void testConvertToDottedProperties() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return this['bar']; } f.prototype.bar = 3;"; String expected = "function f() { return this.bar; } f.prototype.a = 3;"; testSame(options, code); options.convertToDottedProperties = true; options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED; test(options, code, expected); } public void testRewriteFunctionExpressions() { CompilerOptions options = createCompilerOptions(); String code = "var a = function() {};"; String expected = "function JSCompiler_emptyFn(){return function(){}} " + "var a = JSCompiler_emptyFn();"; for (int i = 0; i < 10; i++) { code += "a = function() {};"; expected += "a = JSCompiler_emptyFn();"; } testSame(options, code); options.rewriteFunctionExpressions = true; test(options, code, expected); } public void testAliasAllStrings() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return 'a'; }"; String expected = "var $$S_a = 'a'; function f() { return $$S_a; }"; testSame(options, code); options.aliasAllStrings = true; test(options, code, expected); } public void testAliasExterns() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return window + window + window + window; }"; String expected = "var GLOBAL_window = window;" + "function f() { return GLOBAL_window + GLOBAL_window + " + " GLOBAL_window + GLOBAL_window; }"; testSame(options, code); options.aliasExternals = true; test(options, code, expected); } public void testAliasKeywords() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return true + true + true + true + true + true; }"; String expected = "var JSCompiler_alias_TRUE = true;" + "function f() { return JSCompiler_alias_TRUE + " + " JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " + " JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " + " JSCompiler_alias_TRUE; }"; testSame(options, code); options.aliasKeywords = true; test(options, code, expected); } public void testRenameVars1() { CompilerOptions options = createCompilerOptions(); String code = "var abc = 3; function f() { var xyz = 5; return abc + xyz; }"; String local = "var abc = 3; function f() { var a = 5; return abc + a; }"; String all = "var a = 3; function c() { var b = 5; return a + b; }"; testSame(options, code); options.variableRenaming = VariableRenamingPolicy.LOCAL; test(options, code, local); options.variableRenaming = VariableRenamingPolicy.ALL; test(options, code, all); options.reserveRawExports = true; } public void testRenameVars2() { CompilerOptions options = createCompilerOptions(); options.variableRenaming = VariableRenamingPolicy.ALL; String code = "var abc = 3; function f() { window['a'] = 5; }"; String noexport = "var a = 3; function b() { window['a'] = 5; }"; String export = "var b = 3; function c() { window['a'] = 5; }"; options.reserveRawExports = false; test(options, code, noexport); options.reserveRawExports = true; test(options, code, export); } public void testShadowVaribles() { CompilerOptions options = createCompilerOptions(); options.variableRenaming = VariableRenamingPolicy.LOCAL; options.shadowVariables = true; String code = "var f = function(x) { return function(y) {}}"; String expected = "var f = function(a) { return function(a) {}}"; test(options, code, expected); } public void testRenameLabels() { CompilerOptions options = createCompilerOptions(); String code = "longLabel: while (true) { break longLabel; }"; String expected = "a: while (true) { break a; }"; testSame(options, code); options.labelRenaming = true; test(options, code, expected); } public void testBadBreakStatementInIdeMode() { // Ensure that type-checking doesn't crash, even if the CFG is malformed. // This can happen in IDE mode. CompilerOptions options = createCompilerOptions(); options.ideMode = true; options.checkTypes = true; test(options, "function f() { try { } catch(e) { break; } }", RhinoErrorReporter.PARSE_ERROR); } public void testIssue63SourceMap() { CompilerOptions options = createCompilerOptions(); String code = "var a;"; options.skipAllPasses = true; options.sourceMapOutputPath = "./src.map"; Compiler compiler = compile(options, code); compiler.toSource(); } public void testRegExp1() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "/(a)/.test(\"a\");"; testSame(options, code); options.computeFunctionSideEffects = true; String expected = ""; test(options, code, expected); } public void testRegExp2() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "/(a)/.test(\"a\");var a = RegExp.$1"; testSame(options, code); options.computeFunctionSideEffects = true; test(options, code, CheckRegExp.REGEXP_REFERENCE); options.setWarningLevel(DiagnosticGroups.CHECK_REGEXP, CheckLevel.OFF); testSame(options, code); } public void testFoldLocals1() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; // An external object, whose constructor has no side-effects, // and whose method "go" only modifies the object. String code = "new Widget().go();"; testSame(options, code); options.computeFunctionSideEffects = true; test(options, code, ""); } public void testFoldLocals2() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; options.checkTypes = true; // An external function that returns a local object that the // method "go" that only modifies the object. String code = "widgetToken().go();"; testSame(options, code); options.computeFunctionSideEffects = true; test(options, code, "widgetToken()"); } public void testFoldLocals3() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; // A function "f" who returns a known local object, and a method that // modifies only modifies that. String definition = "function f(){return new Widget()}"; String call = "f().go();"; String code = definition + call; testSame(options, code); options.computeFunctionSideEffects = true; // BROKEN //test(options, code, definition); testSame(options, code); } public void testFoldLocals4() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "/** @constructor */\n" + "function InternalWidget(){this.x = 1;}" + "InternalWidget.prototype.internalGo = function (){this.x = 2};" + "new InternalWidget().internalGo();"; testSame(options, code); options.computeFunctionSideEffects = true; String optimized = "" + "function InternalWidget(){this.x = 1;}" + "InternalWidget.prototype.internalGo = function (){this.x = 2};"; test(options, code, optimized); } public void testFoldLocals5() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "" + "function fn(){var a={};a.x={};return a}" + "fn().x.y = 1;"; // "fn" returns a unescaped local object, we should be able to fold it, // but we don't currently. String result = "" + "function fn(){var a={x:{}};return a}" + "fn().x.y = 1;"; test(options, code, result); options.computeFunctionSideEffects = true; test(options, code, result); } public void testFoldLocals6() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "" + "function fn(){return {}}" + "fn().x.y = 1;"; testSame(options, code); options.computeFunctionSideEffects = true; testSame(options, code); } public void testFoldLocals7() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "" + "function InternalWidget(){return [];}" + "Array.prototype.internalGo = function (){this.x = 2};" + "InternalWidget().internalGo();"; testSame(options, code); options.computeFunctionSideEffects = true; String optimized = "" + "function InternalWidget(){return [];}" + "Array.prototype.internalGo = function (){this.x = 2};"; test(options, code, optimized); } public void testVarDeclarationsIntoFor() { CompilerOptions options = createCompilerOptions(); options.collapseVariableDeclarations = false; String code = "var a = 1; for (var b = 2; ;) {}"; testSame(options, code); options.collapseVariableDeclarations = false; test(options, code, "for (var a = 1, b = 2; ;) {}"); } public void testExploitAssigns() { CompilerOptions options = createCompilerOptions(); options.collapseVariableDeclarations = false; String code = "a = 1; b = a; c = b"; testSame(options, code); options.collapseVariableDeclarations = true; test(options, code, "c=b=a=1"); } public void testRecoverOnBadExterns() throws Exception { // This test is for a bug in a very narrow set of circumstances: // 1) externs validation has to be off. // 2) aliasExternals has to be on. // 3) The user has to reference a "normal" variable in externs. // This case is handled at checking time by injecting a // synthetic extern variable, and adding a "@suppress {duplicate}" to // the normal code at compile time. But optimizations may remove that // annotation, so we need to make sure that the variable declarations // are de-duped before that happens. CompilerOptions options = createCompilerOptions(); options.aliasExternals = true; externs = ImmutableList.of( SourceFile.fromCode("externs", "extern.foo")); test(options, "var extern; " + "function f() { return extern + extern + extern + extern; }", "var extern; " + "function f() { return extern + extern + extern + extern; }", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); } public void testDuplicateVariablesInExterns() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = true; externs = ImmutableList.of( SourceFile.fromCode("externs", "var externs = {}; /** @suppress {duplicate} */ var externs = {};")); testSame(options, ""); } public void testLanguageMode() { CompilerOptions options = createCompilerOptions(); options.setLanguageIn(LanguageMode.ECMASCRIPT3); String code = "var a = {get f(){}}"; Compiler compiler = compile(options, code); checkUnexpectedErrorsOrWarnings(compiler, 1); assertEquals( "JSC_PARSE_ERROR. Parse error. " + "getters are not supported in Internet Explorer " + "at i0 line 1 : 0", compiler.getErrors()[0].toString()); options.setLanguageIn(LanguageMode.ECMASCRIPT5); testSame(options, code); options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT); testSame(options, code); } public void testLanguageMode2() { CompilerOptions options = createCompilerOptions(); options.setLanguageIn(LanguageMode.ECMASCRIPT3); options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.OFF); String code = "var a = 2; delete a;"; testSame(options, code); options.setLanguageIn(LanguageMode.ECMASCRIPT5); testSame(options, code); options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT); test(options, code, code, StrictModeCheck.DELETE_VARIABLE); } public void testIssue598() { CompilerOptions options = createCompilerOptions(); options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT); WarningLevel.VERBOSE.setOptionsForWarningLevel(options); options.setLanguageIn(LanguageMode.ECMASCRIPT5); String code = "'use strict';\n" + "function App() {}\n" + "App.prototype = {\n" + " get appData() { return this.appData_; },\n" + " set appData(data) { this.appData_ = data; }\n" + "};"; Compiler compiler = compile(options, code); testSame(options, code); } public void testIssue701() { // Check ASCII art in license comments. String ascii = "/**\n" + " * @preserve\n" + " This\n" + " is\n" + " ASCII ART\n" + "*/"; String result = "/*\n\n" + " This\n" + " is\n" + " ASCII ART\n" + "*/\n"; testSame(createCompilerOptions(), ascii); assertEquals(result, lastCompiler.toSource()); } public void testCoaleseVariables() { CompilerOptions options = createCompilerOptions(); options.foldConstants = false; options.coalesceVariableNames = true; String code = "function f(a) {" + " if (a) {" + " return a;" + " } else {" + " var b = a;" + " return b;" + " }" + " return a;" + "}"; String expected = "function f(a) {" + " if (a) {" + " return a;" + " } else {" + " a = a;" + " return a;" + " }" + " return a;" + "}"; test(options, code, expected); options.foldConstants = true; options.coalesceVariableNames = false; code = "function f(a) {" + " if (a) {" + " return a;" + " } else {" + " var b = a;" + " return b;" + " }" + " return a;" + "}"; expected = "function f(a) {" + " if (!a) {" + " var b = a;" + " return b;" + " }" + " return a;" + "}"; test(options, code, expected); options.foldConstants = true; options.coalesceVariableNames = true; expected = "function f(a) {" + " return a;" + "}"; test(options, code, expected); } public void testLateStatementFusion() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; test(options, "while(a){a();if(b){b();b()}}", "for(;a;)a(),b&&(b(),b())"); } public void testLateConstantReordering() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; test(options, "if (x < 1 || x > 1 || 1 < x || 1 > x) { alert(x) }", " (1 > x || 1 < x || 1 < x || 1 > x) && alert(x) "); } public void testsyntheticBlockOnDeadAssignments() { CompilerOptions options = createCompilerOptions(); options.deadAssignmentElimination = true; options.removeUnusedVars = true; options.syntheticBlockStartMarker = "START"; options.syntheticBlockEndMarker = "END"; test(options, "var x; x = 1; START(); x = 1;END();x()", "var x; x = 1;{START();{x = 1}END()}x()"); } public void testBug4152835() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; options.syntheticBlockStartMarker = "START"; options.syntheticBlockEndMarker = "END"; test(options, "START();END()", "{START();{}END()}"); } public void testBug5786871() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; test(options, "function () {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue378() { CompilerOptions options = createCompilerOptions(); options.inlineVariables = true; options.flowSensitiveInlineVariables = true; testSame(options, "function f(c) {var f = c; arguments[0] = this;" + " f.apply(this, arguments); return this;}"); } public void testIssue550() { CompilerOptions options = createCompilerOptions(); CompilationLevel.SIMPLE_OPTIMIZATIONS .setOptionsForCompilationLevel(options); options.foldConstants = true; options.inlineVariables = true; options.flowSensitiveInlineVariables = true; test(options, "function f(h) {\n" + " var a = h;\n" + " a = a + 'x';\n" + " a = a + 'y';\n" + " return a;\n" + "}", "function f(a) {return a + 'xy'}"); } public void testIssue284() { CompilerOptions options = createCompilerOptions(); options.smartNameRemoval = true; test(options, "var goog = {};" + "goog.inherits = function(x, y) {};" + "var ns = {};" + "/** @constructor */" + "ns.PageSelectionModel = function() {};" + "/** @constructor */" + "ns.PageSelectionModel.FooEvent = function() {};" + "/** @constructor */" + "ns.PageSelectionModel.SelectEvent = function() {};" + "goog.inherits(ns.PageSelectionModel.ChangeEvent," + " ns.PageSelectionModel.FooEvent);", ""); } public void testCodingConvention() { Compiler compiler = new Compiler(); compiler.initOptions(new CompilerOptions()); assertEquals( compiler.getCodingConvention().getClass().toString(), ClosureCodingConvention.class.toString()); } public void testJQueryStringSplitLoops() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; test(options, "var x=['1','2','3','4','5','6','7']", "var x='1,2,3,4,5,6,7'.split(',')"); options = createCompilerOptions(); options.foldConstants = true; options.computeFunctionSideEffects = false; options.removeUnusedVars = true; // If we do splits too early, it would add a sideeffect to x. test(options, "var x=['1','2','3','4','5','6','7']", ""); } public void testAlwaysRunSafetyCheck() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = false; options.customPasses = ArrayListMultimap.create(); options.customPasses.put( CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, new CompilerPass() { @Override public void process(Node externs, Node root) { Node var = root.getLastChild().getFirstChild(); assertEquals(Token.VAR, var.getType()); var.detachFromParent(); } }); try { test(options, "var x = 3; function f() { return x + z; }", "function f() { return x + z; }"); fail("Expected runtime exception"); } catch (RuntimeException e) { assertTrue(e.getMessage().indexOf("Unexpected variable x") != -1); } } public void testSuppressEs5StrictWarning() { CompilerOptions options = createCompilerOptions(); options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.WARNING); testSame(options, "/** @suppress{es5Strict} */\n" + "function f() { var arguments; }"); } public void testCheckProvidesWarning() { CompilerOptions options = createCompilerOptions(); options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING); options.setCheckProvides(CheckLevel.WARNING); test(options, "/** @constructor */\n" + "function f() { var arguments; }", DiagnosticType.warning("JSC_MISSING_PROVIDE", "missing goog.provide(''{0}'')")); } public void testSuppressCheckProvidesWarning() { CompilerOptions options = createCompilerOptions(); options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING); options.setCheckProvides(CheckLevel.WARNING); testSame(options, "/** @constructor\n" + " * @suppress{checkProvides} */\n" + "function f() { var arguments; }"); } public void testRenamePrefixNamespace() { String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseProperties = true; options.renamePrefixNamespace = "_"; test(options, code, "_.x$FOO = 5; _.x$bar = 3;"); } public void testRenamePrefixNamespaceActivatesMoveFunctionDeclarations() { CompilerOptions options = createCompilerOptions(); String code = "var x = f; function f() { return 3; }"; testSame(options, code); assertFalse(options.moveFunctionDeclarations); options.renamePrefixNamespace = "_"; test(options, code, "_.f = function() { return 3; }; _.x = _.f;"); } public void testBrokenNameSpace() { CompilerOptions options = createCompilerOptions(); String code = "var goog; goog.provide('i.am.on.a.Horse');" + "i.am.on.a.Horse = function() {};" + "i.am.on.a.Horse.prototype.x = function() {};" + "i.am.on.a.Boat.prototype.y = function() {}"; options.closurePass = true; options.collapseProperties = true; options.smartNameRemoval = true; test(options, code, ""); } public void testNamelessParameter() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); String code = "var impl_0;" + "$load($init());" + "function $load(){" + " window['f'] = impl_0;" + "}" + "function $init() {" + " impl_0 = {};" + "}"; String result = "window.f = {};"; test(options, code, result); } public void testHiddenSideEffect() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); options.setAliasExternals(true); String code = "window.offsetWidth;"; String result = "window.offsetWidth;"; test(options, code, result); } public void testNegativeZero() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); test(options, "function bar(x) { return x; }\n" + "function foo(x) { print(x / bar(0));\n" + " print(x / bar(-0)); }\n" + "foo(3);", "print(3/0);print(3/-0);"); } public void testSingletonGetter1() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); options.setCodingConvention(new ClosureCodingConvention()); test(options, "/** @const */\n" + "var goog = goog || {};\n" + "goog.addSingletonGetter = function(ctor) {\n" + " ctor.getInstance = function() {\n" + " return ctor.instance_ || (ctor.instance_ = new ctor());\n" + " };\n" + "};" + "function Foo() {}\n" + "goog.addSingletonGetter(Foo);" + "Foo.prototype.bar = 1;" + "function Bar() {}\n" + "goog.addSingletonGetter(Bar);" + "Bar.prototype.bar = 1;", ""); } public void testIncompleteFunction1() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; DiagnosticType[] warnings = new DiagnosticType[]{ RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR}; test(options, new String[] { "var foo = {bar: function(e) }" }, new String[] { "var foo = {bar: function(e){}};" }, warnings ); } public void testIncompleteFunction2() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; DiagnosticType[] warnings = new DiagnosticType[]{ RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR}; test(options, new String[] { "function hi" }, new String[] { "function hi() {}" }, warnings ); } public void testSortingOff() { CompilerOptions options = new CompilerOptions(); options.closurePass = true; options.setCodingConvention(new ClosureCodingConvention()); test(options, new String[] { "goog.require('goog.beer');", "goog.provide('goog.beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testUnboundedArrayLiteralInfiniteLoop() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; test(options, "var x = [1, 2", "var x = [1, 2]", RhinoErrorReporter.PARSE_ERROR); } public void testProvideRequireSameFile() throws Exception { CompilerOptions options = createCompilerOptions(); options.setDependencyOptions( new DependencyOptions() .setDependencySorting(true)); options.closurePass = true; test( options, "goog.provide('x');\ngoog.require('x');", "var x = {};"); } public void testStrictWarningsGuard() throws Exception { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.addWarningsGuard(new StrictWarningsGuard()); Compiler compiler = compile(options, "/** @return {number} */ function f() { return true; }"); assertEquals(1, compiler.getErrors().length); assertEquals(0, compiler.getWarnings().length); } public void testStrictWarningsGuardEmergencyMode() throws Exception { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.addWarningsGuard(new StrictWarningsGuard()); options.useEmergencyFailSafe(); Compiler compiler = compile(options, "/** @return {number} */ function f() { return true; }"); assertEquals(0, compiler.getErrors().length); assertEquals(1, compiler.getWarnings().length); } private void testSame(CompilerOptions options, String original) { testSame(options, new String[] { original }); } private void testSame(CompilerOptions options, String[] original) { test(options, original, original); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(CompilerOptions options, String original, String compiled) { test(options, new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(CompilerOptions options, String[] original, String[] compiled) { Compiler compiler = compile(options, original); assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); Node root = compiler.getRoot().getLastChild(); Node expectedRoot = parse(compiled, options); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } /** * Asserts that when compiling with the given compiler options, * there is an error or warning. */ private void test(CompilerOptions options, String original, DiagnosticType warning) { test(options, new String[] { original }, warning); } private void test(CompilerOptions options, String original, String compiled, DiagnosticType warning) { test(options, new String[] { original }, new String[] { compiled }, warning); } private void test(CompilerOptions options, String[] original, DiagnosticType warning) { test(options, original, null, warning); } /** * Asserts that when compiling with the given compiler options, * there is an error or warning. */ private void test(CompilerOptions options, String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(options, original); checkUnexpectedErrorsOrWarnings(compiler, 1); assertEquals("Expected exactly one warning or error", 1, compiler.getErrors().length + compiler.getWarnings().length); if (compiler.getErrors().length > 0) { assertEquals(warning, compiler.getErrors()[0].getType()); } else { assertEquals(warning, compiler.getWarnings()[0].getType()); } if (compiled != null) { Node root = compiler.getRoot().getLastChild(); Node expectedRoot = parse(compiled, options); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling with the given compiler options, * there is an error or warning. */ private void test(CompilerOptions options, String[] original, String[] compiled, DiagnosticType[] warnings) { Compiler compiler = compile(options, original); checkUnexpectedErrorsOrWarnings(compiler, warnings.length); if (compiled != null) { Node root = compiler.getRoot().getLastChild(); Node expectedRoot = parse(compiled, options); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } private void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } private Compiler compile(CompilerOptions options, String original) { return compile(options, new String[] { original }); } private Compiler compile(CompilerOptions options, String[] original) { Compiler compiler = lastCompiler = new Compiler(); List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode("input" + i, original[i])); } compiler.compileModules( externs, Lists.newArrayList(CompilerTestCase.createModuleChain(original)), options); return compiler; } private Node parse(String[] original, CompilerOptions options) { Compiler compiler = new Compiler(); List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode("input" + i, original[i])); } compiler.init(externs, inputs, options); checkUnexpectedErrorsOrWarnings(compiler, 0); Node all = compiler.parseInputs(); checkUnexpectedErrorsOrWarnings(compiler, 0); Node n = all.getLastChild(); Node externs = all.getFirstChild(); (new CreateSyntheticBlocks( compiler, "synStart", "synEnd")).process(externs, n); (new Normalize(compiler, false)).process(externs, n); (MakeDeclaredNamesUnique.getContextualRenameInverter(compiler)).process( externs, n); (new Denormalize(compiler)).process(externs, n); return n; } /** Creates a CompilerOptions object with google coding conventions. */ private CompilerOptions createCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new GoogleCodingConvention()); return options; } }
// You are a professional Java test case writer, please create a test case named `testIssue701` for the issue `Closure-701`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-701 // // ## Issue-Title: // Preserve doesn't preserve whitespace at start of line // // ## Issue-Description: // **What steps will reproduce the problem?** // // Code such as: // /\*\* // \* @preserve // // This // was // ASCII // Art // // \*/ // // **What is the expected output? What do you see instead?** // // The words line up on the left: // /\* // This // was // ASCII // Art // \*/ // // // **What version of the product are you using? On what operating system?** // // Live web verison. // // // **Please provide any additional information below.** // // public void testIssue701() {
1,674
32
1,659
test/com/google/javascript/jscomp/IntegrationTest.java
test
```markdown ## Issue-ID: Closure-701 ## Issue-Title: Preserve doesn't preserve whitespace at start of line ## Issue-Description: **What steps will reproduce the problem?** Code such as: /\*\* \* @preserve This was ASCII Art \*/ **What is the expected output? What do you see instead?** The words line up on the left: /\* This was ASCII Art \*/ **What version of the product are you using? On what operating system?** Live web verison. **Please provide any additional information below.** ``` You are a professional Java test case writer, please create a test case named `testIssue701` for the issue `Closure-701`, utilizing the provided issue report information and the following function signature. ```java public void testIssue701() { ```
1,659
[ "com.google.javascript.jscomp.parsing.JsDocInfoParser" ]
f1900fd309e8b96b735507fc9388967988ccadc68eea2606437250bf30acc903
public void testIssue701()
// You are a professional Java test case writer, please create a test case named `testIssue701` for the issue `Closure-701`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-701 // // ## Issue-Title: // Preserve doesn't preserve whitespace at start of line // // ## Issue-Description: // **What steps will reproduce the problem?** // // Code such as: // /\*\* // \* @preserve // // This // was // ASCII // Art // // \*/ // // **What is the expected output? What do you see instead?** // // The words line up on the left: // /\* // This // was // ASCII // Art // \*/ // // // **What version of the product are you using? On what operating system?** // // Live web verison. // // // **Please provide any additional information below.** // //
Closure
/* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; import java.util.List; /** * Tests for {@link PassFactory}. * * @author nicksantos@google.com (Nick Santos) */ public class IntegrationTest extends TestCase { /** Externs for the test */ private final List<SourceFile> DEFAULT_EXTERNS = ImmutableList.of( SourceFile.fromCode("externs", "var arguments;\n" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {string} */ Window.prototype.offsetWidth;\n" + "/** @type {Window} */ var window;\n" + "/** @nosideeffects */ function noSideEffects() {}\n" + "/** @constructor\n * @nosideeffects */ function Widget() {}\n" + "/** @modifies {this} */ Widget.prototype.go = function() {};\n" + "/** @return {string} */ var widgetToken = function() {};\n")); private List<SourceFile> externs = DEFAULT_EXTERNS; private static final String CLOSURE_BOILERPLATE = "/** @define {boolean} */ var COMPILED = false; var goog = {};" + "goog.exportSymbol = function() {};"; private static final String CLOSURE_COMPILED = "var COMPILED = true; var goog$exportSymbol = function() {};"; // The most recently used compiler. private Compiler lastCompiler; @Override public void setUp() { externs = DEFAULT_EXTERNS; lastCompiler = null; } public void testBug1949424() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO'); FOO.bar = 3;", CLOSURE_COMPILED + "var FOO$bar = 3;"); } public void testBug1949424_v2() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('FOO.BAR'); FOO.BAR = 3;", CLOSURE_COMPILED + "var FOO$BAR = 3;"); } public void testBug1956277() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.inlineVariables = true; test(options, "var CONST = {}; CONST.bar = null;" + "function f(url) { CONST.bar = url; }", "var CONST$bar = null; function f(url) { CONST$bar = url; }"); } public void testBug1962380() { CompilerOptions options = createCompilerOptions(); options.collapseProperties = true; options.inlineVariables = true; options.generateExports = true; test(options, CLOSURE_BOILERPLATE + "/** @export */ goog.CONSTANT = 1;" + "var x = goog.CONSTANT;", "(function() {})('goog.CONSTANT', 1);" + "var x = 1;"); } public void testBug2410122() { CompilerOptions options = createCompilerOptions(); options.generateExports = true; options.closurePass = true; test(options, "var goog = {};" + "function F() {}" + "/** @export */ function G() { goog.base(this); } " + "goog.inherits(G, F);", "var goog = {};" + "function F() {}" + "function G() { F.call(this); } " + "goog.inherits(G, F); goog.exportSymbol('G', G);"); } public void testIssue90() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; options.inlineVariables = true; options.removeDeadCode = true; test(options, "var x; x && alert(1);", ""); } public void testClosurePassOff() { CompilerOptions options = createCompilerOptions(); options.closurePass = false; testSame( options, "var goog = {}; goog.require = function(x) {}; goog.require('foo');"); testSame( options, "var goog = {}; goog.getCssName = function(x) {};" + "goog.getCssName('foo');"); } public void testClosurePassOn() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; test( options, "var goog = {}; goog.require = function(x) {}; goog.require('foo');", ProcessClosurePrimitives.MISSING_PROVIDE_ERROR); test( options, "/** @define {boolean} */ var COMPILED = false;" + "var goog = {}; goog.getCssName = function(x) {};" + "goog.getCssName('foo');", "var COMPILED = true;" + "var goog = {}; goog.getCssName = function(x) {};" + "'foo';"); } public void testCssNameCheck() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.checkMissingGetCssNameLevel = CheckLevel.ERROR; options.checkMissingGetCssNameBlacklist = "foo"; test(options, "var x = 'foo';", CheckMissingGetCssName.MISSING_GETCSSNAME); } public void testBug2592659() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.checkTypes = true; options.checkMissingGetCssNameLevel = CheckLevel.WARNING; options.checkMissingGetCssNameBlacklist = "foo"; test(options, "var goog = {};\n" + "/**\n" + " * @param {string} className\n" + " * @param {string=} opt_modifier\n" + " * @return {string}\n" + "*/\n" + "goog.getCssName = function(className, opt_modifier) {}\n" + "var x = goog.getCssName(123, 'a');", TypeValidator.TYPE_MISMATCH_WARNING); } public void testTypedefBeforeOwner1() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; test(options, "goog.provide('foo.Bar.Type');\n" + "goog.provide('foo.Bar');\n" + "/** @typedef {number} */ foo.Bar.Type;\n" + "foo.Bar = function() {};", "var foo = {}; foo.Bar.Type; foo.Bar = function() {};"); } public void testTypedefBeforeOwner2() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.collapseProperties = true; test(options, "goog.provide('foo.Bar.Type');\n" + "goog.provide('foo.Bar');\n" + "/** @typedef {number} */ foo.Bar.Type;\n" + "foo.Bar = function() {};", "var foo$Bar$Type; var foo$Bar = function() {};"); } public void testExportedNames() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.variableRenaming = VariableRenamingPolicy.ALL; test(options, "/** @define {boolean} */ var COMPILED = false;" + "var goog = {}; goog.exportSymbol('b', goog);", "var a = true; var c = {}; c.exportSymbol('b', c);"); test(options, "/** @define {boolean} */ var COMPILED = false;" + "var goog = {}; goog.exportSymbol('a', goog);", "var b = true; var c = {}; c.exportSymbol('a', c);"); } public void testCheckGlobalThisOn() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = true; options.checkGlobalThisLevel = CheckLevel.ERROR; test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testSusiciousCodeOff() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = false; options.checkGlobalThisLevel = CheckLevel.ERROR; test(options, "function f() { this.y = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOff() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = true; options.checkGlobalThisLevel = CheckLevel.OFF; testSame(options, "function f() { this.y = 3; }"); } public void testCheckRequiresAndCheckProvidesOff() { testSame(createCompilerOptions(), new String[] { "/** @constructor */ function Foo() {}", "new Foo();" }); } public void testCheckRequiresOn() { CompilerOptions options = createCompilerOptions(); options.checkRequires = CheckLevel.ERROR; test(options, new String[] { "/** @constructor */ function Foo() {}", "new Foo();" }, CheckRequiresForConstructors.MISSING_REQUIRE_WARNING); } public void testCheckProvidesOn() { CompilerOptions options = createCompilerOptions(); options.checkProvides = CheckLevel.ERROR; test(options, new String[] { "/** @constructor */ function Foo() {}", "new Foo();" }, CheckProvides.MISSING_PROVIDE_WARNING); } public void testGenerateExportsOff() { testSame(createCompilerOptions(), "/** @export */ function f() {}"); } public void testGenerateExportsOn() { CompilerOptions options = createCompilerOptions(); options.generateExports = true; test(options, "/** @export */ function f() {}", "/** @export */ function f() {} goog.exportSymbol('f', f);"); } public void testExportTestFunctionsOff() { testSame(createCompilerOptions(), "function testFoo() {}"); } public void testExportTestFunctionsOn() { CompilerOptions options = createCompilerOptions(); options.exportTestFunctions = true; test(options, "function testFoo() {}", "/** @export */ function testFoo() {}" + "goog.exportSymbol('testFoo', testFoo);"); } public void testExpose() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); test(options, "var x = {eeny: 1, /** @expose */ meeny: 2};" + "/** @constructor */ var Foo = function() {};" + "/** @expose */ Foo.prototype.miny = 3;" + "Foo.prototype.moe = 4;" + "function moe(a, b) { return a.meeny + b.miny; }" + "window['x'] = x;" + "window['Foo'] = Foo;" + "window['moe'] = moe;", "function a(){}" + "a.prototype.miny=3;" + "window.x={a:1,meeny:2};" + "window.Foo=a;" + "window.moe=function(b,c){" + " return b.meeny+c.miny" + "}"); } public void testCheckSymbolsOff() { CompilerOptions options = createCompilerOptions(); testSame(options, "x = 3;"); } public void testCheckSymbolsOn() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = true; test(options, "x = 3;", VarCheck.UNDEFINED_VAR_ERROR); } public void testCheckReferencesOff() { CompilerOptions options = createCompilerOptions(); testSame(options, "x = 3; var x = 5;"); } public void testCheckReferencesOn() { CompilerOptions options = createCompilerOptions(); options.aggressiveVarCheck = CheckLevel.ERROR; test(options, "x = 3; var x = 5;", VariableReferenceCheck.UNDECLARED_REFERENCE); } public void testInferTypes() { CompilerOptions options = createCompilerOptions(); options.inferTypes = true; options.checkTypes = false; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('Foo'); /** @enum */ Foo = {a: 3};", TypeCheck.ENUM_NOT_CONSTANT); assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0); // This does not generate a warning. test(options, "/** @type {number} */ var n = window.name;", "var n = window.name;"); assertTrue(lastCompiler.getErrorManager().getTypedPercent() == 0); } public void testTypeCheckAndInference() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; test(options, "/** @type {number} */ var n = window.name;", TypeValidator.TYPE_MISMATCH_WARNING); assertTrue(lastCompiler.getErrorManager().getTypedPercent() > 0); } public void testTypeNameParser() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; test(options, "/** @type {n} */ var n = window.name;", RhinoErrorReporter.TYPE_PARSE_ERROR); } // This tests that the TypedScopeCreator is memoized so that it only creates a // Scope object once for each scope. If, when type inference requests a scope, // it creates a new one, then multiple JSType objects end up getting created // for the same local type, and ambiguate will rename the last statement to // o.a(o.a, o.a), which is bad. public void testMemoizedTypedScopeCreator() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.ambiguateProperties = true; options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED; test(options, "function someTest() {\n" + " /** @constructor */\n" + " function Foo() { this.instProp = 3; }\n" + " Foo.prototype.protoProp = function(a, b) {};\n" + " /** @constructor\n @extends Foo */\n" + " function Bar() {}\n" + " goog.inherits(Bar, Foo);\n" + " var o = new Bar();\n" + " o.protoProp(o.protoProp, o.instProp);\n" + "}", "function someTest() {\n" + " function Foo() { this.b = 3; }\n" + " Foo.prototype.a = function(a, b) {};\n" + " function Bar() {}\n" + " goog.c(Bar, Foo);\n" + " var o = new Bar();\n" + " o.a(o.a, o.b);\n" + "}"); } public void testCheckTypes() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; test(options, "var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testReplaceCssNames() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.gatherCssNames = true; test(options, "/** @define {boolean} */\n" + "var COMPILED = false;\n" + "goog.setCssNameMapping({'foo':'bar'});\n" + "function getCss() {\n" + " return goog.getCssName('foo');\n" + "}", "var COMPILED = true;\n" + "function getCss() {\n" + " return \"bar\";" + "}"); assertEquals( ImmutableMap.of("foo", new Integer(1)), lastCompiler.getPassConfig().getIntermediateState().cssNames); } public void testRemoveClosureAsserts() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; testSame(options, "var goog = {};" + "goog.asserts.assert(goog);"); options.removeClosureAsserts = true; test(options, "var goog = {};" + "goog.asserts.assert(goog);", "var goog = {};"); } public void testDeprecation() { String code = "/** @deprecated */ function f() { } function g() { f(); }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.setWarningLevel(DiagnosticGroups.DEPRECATED, CheckLevel.ERROR); testSame(options, code); options.checkTypes = true; test(options, code, CheckAccessControls.DEPRECATED_NAME); } public void testVisibility() { String[] code = { "/** @private */ function f() { }", "function g() { f(); }" }; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.setWarningLevel(DiagnosticGroups.VISIBILITY, CheckLevel.ERROR); testSame(options, code); options.checkTypes = true; test(options, code, CheckAccessControls.BAD_PRIVATE_GLOBAL_ACCESS); } public void testUnreachableCode() { String code = "function f() { return \n 3; }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.checkUnreachableCode = CheckLevel.ERROR; test(options, code, CheckUnreachableCode.UNREACHABLE_CODE); } public void testMissingReturn() { String code = "/** @return {number} */ function f() { if (f) { return 3; } }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.checkMissingReturn = CheckLevel.ERROR; testSame(options, code); options.checkTypes = true; test(options, code, CheckMissingReturn.MISSING_RETURN_STATEMENT); } public void testIdGenerators() { String code = "function f() {} f('id');"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.idGenerators = Sets.newHashSet("f"); test(options, code, "function f() {} 'a';"); } public void testOptimizeArgumentsArray() { String code = "function f() { return arguments[0]; }"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.optimizeArgumentsArray = true; String argName = "JSCompiler_OptimizeArgumentsArray_p0"; test(options, code, "function f(" + argName + ") { return " + argName + "; }"); } public void testOptimizeParameters() { String code = "function f(a) { return a; } f(true);"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.optimizeParameters = true; test(options, code, "function f() { var a = true; return a;} f();"); } public void testOptimizeReturns() { String code = "function f(a) { return a; } f(true);"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.optimizeReturns = true; test(options, code, "function f(a) {return;} f(true);"); } public void testRemoveAbstractMethods() { String code = CLOSURE_BOILERPLATE + "var x = {}; x.foo = goog.abstractMethod; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.closurePass = true; options.collapseProperties = true; test(options, code, CLOSURE_COMPILED + " var x$bar = 3;"); } public void testCollapseProperties1() { String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseProperties = true; test(options, code, "var x$FOO = 5; var x$bar = 3;"); } public void testCollapseProperties2() { String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseProperties = true; options.collapseObjectLiterals = true; test(options, code, "var x$FOO = 5; var x$bar = 3;"); } public void testCollapseObjectLiteral1() { // Verify collapseObjectLiterals does nothing in global scope String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseObjectLiterals = true; testSame(options, code); } public void testCollapseObjectLiteral2() { String code = "function f() {var x = {}; x.FOO = 5; x.bar = 3;}"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseObjectLiterals = true; test(options, code, "function f(){" + "var JSCompiler_object_inline_FOO_0;" + "var JSCompiler_object_inline_bar_1;" + "JSCompiler_object_inline_FOO_0=5;" + "JSCompiler_object_inline_bar_1=3}"); } public void testTightenTypesWithoutTypeCheck() { CompilerOptions options = createCompilerOptions(); options.tightenTypes = true; test(options, "", DefaultPassConfig.TIGHTEN_TYPES_WITHOUT_TYPE_CHECK); } public void testDisambiguateProperties() { String code = "/** @constructor */ function Foo(){} Foo.prototype.bar = 3;" + "/** @constructor */ function Baz(){} Baz.prototype.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.disambiguateProperties = true; options.checkTypes = true; test(options, code, "function Foo(){} Foo.prototype.Foo_prototype$bar = 3;" + "function Baz(){} Baz.prototype.Baz_prototype$bar = 3;"); } public void testMarkPureCalls() { String testCode = "function foo() {} foo();"; CompilerOptions options = createCompilerOptions(); options.removeDeadCode = true; testSame(options, testCode); options.computeFunctionSideEffects = true; test(options, testCode, "function foo() {}"); } public void testMarkNoSideEffects() { String testCode = "noSideEffects();"; CompilerOptions options = createCompilerOptions(); options.removeDeadCode = true; testSame(options, testCode); options.markNoSideEffectCalls = true; test(options, testCode, ""); } public void testChainedCalls() { CompilerOptions options = createCompilerOptions(); options.chainCalls = true; test( options, "/** @constructor */ function Foo() {} " + "Foo.prototype.bar = function() { return this; }; " + "var f = new Foo();" + "f.bar(); " + "f.bar(); ", "function Foo() {} " + "Foo.prototype.bar = function() { return this; }; " + "var f = new Foo();" + "f.bar().bar();"); } public void testExtraAnnotationNames() { CompilerOptions options = createCompilerOptions(); options.setExtraAnnotationNames(Sets.newHashSet("TagA", "TagB")); test( options, "/** @TagA */ var f = new Foo(); /** @TagB */ f.bar();", "var f = new Foo(); f.bar();"); } public void testDevirtualizePrototypeMethods() { CompilerOptions options = createCompilerOptions(); options.devirtualizePrototypeMethods = true; test( options, "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.bar = function() {};" + "(new Foo()).bar();", "var Foo = function() {};" + "var JSCompiler_StaticMethods_bar = " + " function(JSCompiler_StaticMethods_bar$self) {};" + "JSCompiler_StaticMethods_bar(new Foo());"); } public void testCheckConsts() { CompilerOptions options = createCompilerOptions(); options.inlineConstantVars = true; test(options, "var FOO = true; FOO = false", ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testAllChecksOn() { CompilerOptions options = createCompilerOptions(); options.checkSuspiciousCode = true; options.checkControlStructures = true; options.checkRequires = CheckLevel.ERROR; options.checkProvides = CheckLevel.ERROR; options.generateExports = true; options.exportTestFunctions = true; options.closurePass = true; options.checkMissingGetCssNameLevel = CheckLevel.ERROR; options.checkMissingGetCssNameBlacklist = "goog"; options.syntheticBlockStartMarker = "synStart"; options.syntheticBlockEndMarker = "synEnd"; options.checkSymbols = true; options.aggressiveVarCheck = CheckLevel.ERROR; options.processObjectPropertyString = true; options.collapseProperties = true; test(options, CLOSURE_BOILERPLATE, CLOSURE_COMPILED); } public void testTypeCheckingWithSyntheticBlocks() { CompilerOptions options = createCompilerOptions(); options.syntheticBlockStartMarker = "synStart"; options.syntheticBlockEndMarker = "synEnd"; options.checkTypes = true; // We used to have a bug where the CFG drew an // edge straight from synStart to f(progress). // If that happens, then progress will get type {number|undefined}. testSame( options, "/** @param {number} x */ function f(x) {}" + "function g() {" + " synStart('foo');" + " var progress = 1;" + " f(progress);" + " synEnd('foo');" + "}"); } public void testCompilerDoesNotBlowUpIfUndefinedSymbols() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = true; // Disable the undefined variable check. options.setWarningLevel( DiagnosticGroup.forType(VarCheck.UNDEFINED_VAR_ERROR), CheckLevel.OFF); // The compiler used to throw an IllegalStateException on this. testSame(options, "var x = {foo: y};"); } // Make sure that if we change variables which are constant to have // $$constant appended to their names, we remove that tag before // we finish. public void testConstantTagsMustAlwaysBeRemoved() { CompilerOptions options = createCompilerOptions(); options.variableRenaming = VariableRenamingPolicy.LOCAL; String originalText = "var G_GEO_UNKNOWN_ADDRESS=1;\n" + "function foo() {" + " var localVar = 2;\n" + " if (G_GEO_UNKNOWN_ADDRESS == localVar) {\n" + " alert(\"A\"); }}"; String expectedText = "var G_GEO_UNKNOWN_ADDRESS=1;" + "function foo(){var a=2;if(G_GEO_UNKNOWN_ADDRESS==a){alert(\"A\")}}"; test(options, originalText, expectedText); } public void testClosurePassPreservesJsDoc() { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.closurePass = true; test(options, CLOSURE_BOILERPLATE + "goog.provide('Foo'); /** @constructor */ Foo = function() {};" + "var x = new Foo();", "var COMPILED=true;var goog={};goog.exportSymbol=function(){};" + "var Foo=function(){};var x=new Foo"); test(options, CLOSURE_BOILERPLATE + "goog.provide('Foo'); /** @enum */ Foo = {a: 3};", TypeCheck.ENUM_NOT_CONSTANT); } public void testProvidedNamespaceIsConst() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo'); " + "function f() { foo = {};}", "var foo = {}; function f() { foo = {}; }", ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testProvidedNamespaceIsConst2() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo.bar'); " + "function f() { foo.bar = {};}", "var foo$bar = {};" + "function f() { foo$bar = {}; }", ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testProvidedNamespaceIsConst3() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; " + "goog.provide('foo.bar'); goog.provide('foo.bar.baz'); " + "/** @constructor */ foo.bar = function() {};" + "/** @constructor */ foo.bar.baz = function() {};", "var foo$bar = function(){};" + "var foo$bar$baz = function(){};"); } public void testProvidedNamespaceIsConst4() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo.Bar'); " + "var foo = {}; foo.Bar = {};", "var foo = {}; var foo = {}; foo.Bar = {};"); } public void testProvidedNamespaceIsConst5() { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.inlineConstantVars = true; options.collapseProperties = true; test(options, "var goog = {}; goog.provide('foo.Bar'); " + "foo = {}; foo.Bar = {};", "var foo = {}; foo = {}; foo.Bar = {};"); } public void testProcessDefinesAlwaysOn() { test(createCompilerOptions(), "/** @define {boolean} */ var HI = true; HI = false;", "var HI = false;false;"); } public void testProcessDefinesAdditionalReplacements() { CompilerOptions options = createCompilerOptions(); options.setDefineToBooleanLiteral("HI", false); test(options, "/** @define {boolean} */ var HI = true;", "var HI = false;"); } public void testReplaceMessages() { CompilerOptions options = createCompilerOptions(); String prefix = "var goog = {}; goog.getMsg = function() {};"; testSame(options, prefix + "var MSG_HI = goog.getMsg('hi');"); options.messageBundle = new EmptyMessageBundle(); test(options, prefix + "/** @desc xyz */ var MSG_HI = goog.getMsg('hi');", prefix + "var MSG_HI = 'hi';"); } public void testCheckGlobalNames() { CompilerOptions options = createCompilerOptions(); options.checkGlobalNamesLevel = CheckLevel.ERROR; test(options, "var x = {}; var y = x.z;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testInlineGetters() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() {} Foo.prototype.bar = function() { return 3; };" + "var x = new Foo(); x.bar();"; testSame(options, code); options.inlineGetters = true; test(options, code, "function Foo() {} Foo.prototype.bar = function() { return 3 };" + "var x = new Foo(); 3;"); } public void testInlineGettersWithAmbiguate() { CompilerOptions options = createCompilerOptions(); String code = "/** @constructor */" + "function Foo() {}" + "/** @type {number} */ Foo.prototype.field;" + "Foo.prototype.getField = function() { return this.field; };" + "/** @constructor */" + "function Bar() {}" + "/** @type {string} */ Bar.prototype.field;" + "Bar.prototype.getField = function() { return this.field; };" + "new Foo().getField();" + "new Bar().getField();"; testSame(options, code); options.inlineGetters = true; test(options, code, "function Foo() {}" + "Foo.prototype.field;" + "Foo.prototype.getField = function() { return this.field; };" + "function Bar() {}" + "Bar.prototype.field;" + "Bar.prototype.getField = function() { return this.field; };" + "new Foo().field;" + "new Bar().field;"); options.checkTypes = true; options.ambiguateProperties = true; // Propagating the wrong type information may cause ambiguate properties // to generate bad code. testSame(options, code); } public void testInlineVariables() { CompilerOptions options = createCompilerOptions(); String code = "function foo() {} var x = 3; foo(x);"; testSame(options, code); options.inlineVariables = true; test(options, code, "(function foo() {})(3);"); options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC; test(options, code, DefaultPassConfig.CANNOT_USE_PROTOTYPE_AND_VAR); } public void testInlineConstants() { CompilerOptions options = createCompilerOptions(); String code = "function foo() {} var x = 3; foo(x); var YYY = 4; foo(YYY);"; testSame(options, code); options.inlineConstantVars = true; test(options, code, "function foo() {} var x = 3; foo(x); foo(4);"); } public void testMinimizeExits() { CompilerOptions options = createCompilerOptions(); String code = "function f() {" + " if (window.foo) return; window.h(); " + "}"; testSame(options, code); options.foldConstants = true; test( options, code, "function f() {" + " window.foo || window.h(); " + "}"); } public void testFoldConstants() { CompilerOptions options = createCompilerOptions(); String code = "if (true) { window.foo(); }"; testSame(options, code); options.foldConstants = true; test(options, code, "window.foo();"); } public void testRemoveUnreachableCode() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return; f(); }"; testSame(options, code); options.removeDeadCode = true; test(options, code, "function f() {}"); } public void testRemoveUnusedPrototypeProperties1() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() {} " + "Foo.prototype.bar = function() { return new Foo(); };"; testSame(options, code); options.removeUnusedPrototypeProperties = true; test(options, code, "function Foo() {}"); } public void testRemoveUnusedPrototypeProperties2() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() {} " + "Foo.prototype.bar = function() { return new Foo(); };" + "function f(x) { x.bar(); }"; testSame(options, code); options.removeUnusedPrototypeProperties = true; testSame(options, code); options.removeUnusedVars = true; test(options, code, ""); } public void testSmartNamePass() { CompilerOptions options = createCompilerOptions(); String code = "function Foo() { this.bar(); } " + "Foo.prototype.bar = function() { return Foo(); };"; testSame(options, code); options.smartNameRemoval = true; test(options, code, ""); } public void testDeadAssignmentsElimination() { CompilerOptions options = createCompilerOptions(); String code = "function f() { var x = 3; 4; x = 5; return x; } f(); "; testSame(options, code); options.deadAssignmentElimination = true; testSame(options, code); options.removeUnusedVars = true; test(options, code, "function f() { var x = 3; 4; x = 5; return x; } f();"); } public void testInlineFunctions() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return 3; } f(); "; testSame(options, code); options.inlineFunctions = true; test(options, code, "3;"); } public void testRemoveUnusedVars1() { CompilerOptions options = createCompilerOptions(); String code = "function f(x) {} f();"; testSame(options, code); options.removeUnusedVars = true; test(options, code, "function f() {} f();"); } public void testRemoveUnusedVars2() { CompilerOptions options = createCompilerOptions(); String code = "(function f(x) {})();var g = function() {}; g();"; testSame(options, code); options.removeUnusedVars = true; test(options, code, "(function() {})();var g = function() {}; g();"); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED; test(options, code, "(function f() {})();var g = function $g$() {}; g();"); } public void testCrossModuleCodeMotion() { CompilerOptions options = createCompilerOptions(); String[] code = new String[] { "var x = 1;", "x;", }; testSame(options, code); options.crossModuleCodeMotion = true; test(options, code, new String[] { "", "var x = 1; x;", }); } public void testCrossModuleMethodMotion() { CompilerOptions options = createCompilerOptions(); String[] code = new String[] { "var Foo = function() {}; Foo.prototype.bar = function() {};" + "var x = new Foo();", "x.bar();", }; testSame(options, code); options.crossModuleMethodMotion = true; test(options, code, new String[] { CrossModuleMethodMotion.STUB_DECLARATIONS + "var Foo = function() {};" + "Foo.prototype.bar=JSCompiler_stubMethod(0); var x=new Foo;", "Foo.prototype.bar=JSCompiler_unstubMethod(0,function(){}); x.bar()", }); } public void testFlowSensitiveInlineVariables1() { CompilerOptions options = createCompilerOptions(); String code = "function f() { var x = 3; x = 5; return x; }"; testSame(options, code); options.flowSensitiveInlineVariables = true; test(options, code, "function f() { var x = 3; return 5; }"); String unusedVar = "function f() { var x; x = 5; return x; } f()"; test(options, unusedVar, "function f() { var x; return 5; } f()"); options.removeUnusedVars = true; test(options, unusedVar, "function f() { return 5; } f()"); } public void testFlowSensitiveInlineVariables2() { CompilerOptions options = createCompilerOptions(); CompilationLevel.SIMPLE_OPTIMIZATIONS .setOptionsForCompilationLevel(options); test(options, "function f () {\n" + " var ab = 0;\n" + " ab += '-';\n" + " alert(ab);\n" + "}", "function f () {\n" + " alert('0-');\n" + "}"); } public void testCollapseAnonymousFunctions() { CompilerOptions options = createCompilerOptions(); String code = "var f = function() {};"; testSame(options, code); options.collapseAnonymousFunctions = true; test(options, code, "function f() {}"); } public void testMoveFunctionDeclarations() { CompilerOptions options = createCompilerOptions(); String code = "var x = f(); function f() { return 3; }"; testSame(options, code); options.moveFunctionDeclarations = true; test(options, code, "function f() { return 3; } var x = f();"); } public void testNameAnonymousFunctions() { CompilerOptions options = createCompilerOptions(); String code = "var f = function() {};"; testSame(options, code); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.MAPPED; test(options, code, "var f = function $() {}"); assertNotNull(lastCompiler.getResult().namedAnonFunctionMap); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED; test(options, code, "var f = function $f$() {}"); assertNull(lastCompiler.getResult().namedAnonFunctionMap); } public void testExtractPrototypeMemberDeclarations() { CompilerOptions options = createCompilerOptions(); String code = "var f = function() {};"; String expected = "var a; var b = function() {}; a = b.prototype;"; for (int i = 0; i < 10; i++) { code += "f.prototype.a = " + i + ";"; expected += "a.a = " + i + ";"; } testSame(options, code); options.extractPrototypeMemberDeclarations = true; options.variableRenaming = VariableRenamingPolicy.ALL; test(options, code, expected); options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC; options.variableRenaming = VariableRenamingPolicy.OFF; testSame(options, code); } public void testDevirtualizationAndExtractPrototypeMemberDeclarations() { CompilerOptions options = createCompilerOptions(); options.devirtualizePrototypeMethods = true; options.collapseAnonymousFunctions = true; options.extractPrototypeMemberDeclarations = true; options.variableRenaming = VariableRenamingPolicy.ALL; String code = "var f = function() {};"; String expected = "var a; function b() {} a = b.prototype;"; for (int i = 0; i < 10; i++) { code += "f.prototype.argz = function() {arguments};"; code += "f.prototype.devir" + i + " = function() {};"; char letter = (char) ('d' + i); expected += "a.argz = function() {arguments};"; expected += "function " + letter + "(c){}"; } code += "var F = new f(); F.argz();"; expected += "var n = new b(); n.argz();"; for (int i = 0; i < 10; i++) { code += "F.devir" + i + "();"; char letter = (char) ('d' + i); expected += letter + "(n);"; } test(options, code, expected); } public void testCoalesceVariableNames() { CompilerOptions options = createCompilerOptions(); String code = "function f() {var x = 3; var y = x; var z = y; return z;}"; testSame(options, code); options.coalesceVariableNames = true; test(options, code, "function f() {var x = 3; x = x; x = x; return x;}"); } public void testPropertyRenaming() { CompilerOptions options = createCompilerOptions(); options.propertyAffinity = true; String code = "function f() { return this.foo + this['bar'] + this.Baz; }" + "f.prototype.bar = 3; f.prototype.Baz = 3;"; String heuristic = "function f() { return this.foo + this['bar'] + this.a; }" + "f.prototype.bar = 3; f.prototype.a = 3;"; String aggHeuristic = "function f() { return this.foo + this['b'] + this.a; } " + "f.prototype.b = 3; f.prototype.a = 3;"; String all = "function f() { return this.b + this['bar'] + this.a; }" + "f.prototype.c = 3; f.prototype.a = 3;"; testSame(options, code); options.propertyRenaming = PropertyRenamingPolicy.HEURISTIC; test(options, code, heuristic); options.propertyRenaming = PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC; test(options, code, aggHeuristic); options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED; test(options, code, all); } public void testConvertToDottedProperties() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return this['bar']; } f.prototype.bar = 3;"; String expected = "function f() { return this.bar; } f.prototype.a = 3;"; testSame(options, code); options.convertToDottedProperties = true; options.propertyRenaming = PropertyRenamingPolicy.ALL_UNQUOTED; test(options, code, expected); } public void testRewriteFunctionExpressions() { CompilerOptions options = createCompilerOptions(); String code = "var a = function() {};"; String expected = "function JSCompiler_emptyFn(){return function(){}} " + "var a = JSCompiler_emptyFn();"; for (int i = 0; i < 10; i++) { code += "a = function() {};"; expected += "a = JSCompiler_emptyFn();"; } testSame(options, code); options.rewriteFunctionExpressions = true; test(options, code, expected); } public void testAliasAllStrings() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return 'a'; }"; String expected = "var $$S_a = 'a'; function f() { return $$S_a; }"; testSame(options, code); options.aliasAllStrings = true; test(options, code, expected); } public void testAliasExterns() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return window + window + window + window; }"; String expected = "var GLOBAL_window = window;" + "function f() { return GLOBAL_window + GLOBAL_window + " + " GLOBAL_window + GLOBAL_window; }"; testSame(options, code); options.aliasExternals = true; test(options, code, expected); } public void testAliasKeywords() { CompilerOptions options = createCompilerOptions(); String code = "function f() { return true + true + true + true + true + true; }"; String expected = "var JSCompiler_alias_TRUE = true;" + "function f() { return JSCompiler_alias_TRUE + " + " JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " + " JSCompiler_alias_TRUE + JSCompiler_alias_TRUE + " + " JSCompiler_alias_TRUE; }"; testSame(options, code); options.aliasKeywords = true; test(options, code, expected); } public void testRenameVars1() { CompilerOptions options = createCompilerOptions(); String code = "var abc = 3; function f() { var xyz = 5; return abc + xyz; }"; String local = "var abc = 3; function f() { var a = 5; return abc + a; }"; String all = "var a = 3; function c() { var b = 5; return a + b; }"; testSame(options, code); options.variableRenaming = VariableRenamingPolicy.LOCAL; test(options, code, local); options.variableRenaming = VariableRenamingPolicy.ALL; test(options, code, all); options.reserveRawExports = true; } public void testRenameVars2() { CompilerOptions options = createCompilerOptions(); options.variableRenaming = VariableRenamingPolicy.ALL; String code = "var abc = 3; function f() { window['a'] = 5; }"; String noexport = "var a = 3; function b() { window['a'] = 5; }"; String export = "var b = 3; function c() { window['a'] = 5; }"; options.reserveRawExports = false; test(options, code, noexport); options.reserveRawExports = true; test(options, code, export); } public void testShadowVaribles() { CompilerOptions options = createCompilerOptions(); options.variableRenaming = VariableRenamingPolicy.LOCAL; options.shadowVariables = true; String code = "var f = function(x) { return function(y) {}}"; String expected = "var f = function(a) { return function(a) {}}"; test(options, code, expected); } public void testRenameLabels() { CompilerOptions options = createCompilerOptions(); String code = "longLabel: while (true) { break longLabel; }"; String expected = "a: while (true) { break a; }"; testSame(options, code); options.labelRenaming = true; test(options, code, expected); } public void testBadBreakStatementInIdeMode() { // Ensure that type-checking doesn't crash, even if the CFG is malformed. // This can happen in IDE mode. CompilerOptions options = createCompilerOptions(); options.ideMode = true; options.checkTypes = true; test(options, "function f() { try { } catch(e) { break; } }", RhinoErrorReporter.PARSE_ERROR); } public void testIssue63SourceMap() { CompilerOptions options = createCompilerOptions(); String code = "var a;"; options.skipAllPasses = true; options.sourceMapOutputPath = "./src.map"; Compiler compiler = compile(options, code); compiler.toSource(); } public void testRegExp1() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "/(a)/.test(\"a\");"; testSame(options, code); options.computeFunctionSideEffects = true; String expected = ""; test(options, code, expected); } public void testRegExp2() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "/(a)/.test(\"a\");var a = RegExp.$1"; testSame(options, code); options.computeFunctionSideEffects = true; test(options, code, CheckRegExp.REGEXP_REFERENCE); options.setWarningLevel(DiagnosticGroups.CHECK_REGEXP, CheckLevel.OFF); testSame(options, code); } public void testFoldLocals1() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; // An external object, whose constructor has no side-effects, // and whose method "go" only modifies the object. String code = "new Widget().go();"; testSame(options, code); options.computeFunctionSideEffects = true; test(options, code, ""); } public void testFoldLocals2() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; options.checkTypes = true; // An external function that returns a local object that the // method "go" that only modifies the object. String code = "widgetToken().go();"; testSame(options, code); options.computeFunctionSideEffects = true; test(options, code, "widgetToken()"); } public void testFoldLocals3() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; // A function "f" who returns a known local object, and a method that // modifies only modifies that. String definition = "function f(){return new Widget()}"; String call = "f().go();"; String code = definition + call; testSame(options, code); options.computeFunctionSideEffects = true; // BROKEN //test(options, code, definition); testSame(options, code); } public void testFoldLocals4() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "/** @constructor */\n" + "function InternalWidget(){this.x = 1;}" + "InternalWidget.prototype.internalGo = function (){this.x = 2};" + "new InternalWidget().internalGo();"; testSame(options, code); options.computeFunctionSideEffects = true; String optimized = "" + "function InternalWidget(){this.x = 1;}" + "InternalWidget.prototype.internalGo = function (){this.x = 2};"; test(options, code, optimized); } public void testFoldLocals5() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "" + "function fn(){var a={};a.x={};return a}" + "fn().x.y = 1;"; // "fn" returns a unescaped local object, we should be able to fold it, // but we don't currently. String result = "" + "function fn(){var a={x:{}};return a}" + "fn().x.y = 1;"; test(options, code, result); options.computeFunctionSideEffects = true; test(options, code, result); } public void testFoldLocals6() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "" + "function fn(){return {}}" + "fn().x.y = 1;"; testSame(options, code); options.computeFunctionSideEffects = true; testSame(options, code); } public void testFoldLocals7() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; String code = "" + "function InternalWidget(){return [];}" + "Array.prototype.internalGo = function (){this.x = 2};" + "InternalWidget().internalGo();"; testSame(options, code); options.computeFunctionSideEffects = true; String optimized = "" + "function InternalWidget(){return [];}" + "Array.prototype.internalGo = function (){this.x = 2};"; test(options, code, optimized); } public void testVarDeclarationsIntoFor() { CompilerOptions options = createCompilerOptions(); options.collapseVariableDeclarations = false; String code = "var a = 1; for (var b = 2; ;) {}"; testSame(options, code); options.collapseVariableDeclarations = false; test(options, code, "for (var a = 1, b = 2; ;) {}"); } public void testExploitAssigns() { CompilerOptions options = createCompilerOptions(); options.collapseVariableDeclarations = false; String code = "a = 1; b = a; c = b"; testSame(options, code); options.collapseVariableDeclarations = true; test(options, code, "c=b=a=1"); } public void testRecoverOnBadExterns() throws Exception { // This test is for a bug in a very narrow set of circumstances: // 1) externs validation has to be off. // 2) aliasExternals has to be on. // 3) The user has to reference a "normal" variable in externs. // This case is handled at checking time by injecting a // synthetic extern variable, and adding a "@suppress {duplicate}" to // the normal code at compile time. But optimizations may remove that // annotation, so we need to make sure that the variable declarations // are de-duped before that happens. CompilerOptions options = createCompilerOptions(); options.aliasExternals = true; externs = ImmutableList.of( SourceFile.fromCode("externs", "extern.foo")); test(options, "var extern; " + "function f() { return extern + extern + extern + extern; }", "var extern; " + "function f() { return extern + extern + extern + extern; }", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); } public void testDuplicateVariablesInExterns() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = true; externs = ImmutableList.of( SourceFile.fromCode("externs", "var externs = {}; /** @suppress {duplicate} */ var externs = {};")); testSame(options, ""); } public void testLanguageMode() { CompilerOptions options = createCompilerOptions(); options.setLanguageIn(LanguageMode.ECMASCRIPT3); String code = "var a = {get f(){}}"; Compiler compiler = compile(options, code); checkUnexpectedErrorsOrWarnings(compiler, 1); assertEquals( "JSC_PARSE_ERROR. Parse error. " + "getters are not supported in Internet Explorer " + "at i0 line 1 : 0", compiler.getErrors()[0].toString()); options.setLanguageIn(LanguageMode.ECMASCRIPT5); testSame(options, code); options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT); testSame(options, code); } public void testLanguageMode2() { CompilerOptions options = createCompilerOptions(); options.setLanguageIn(LanguageMode.ECMASCRIPT3); options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.OFF); String code = "var a = 2; delete a;"; testSame(options, code); options.setLanguageIn(LanguageMode.ECMASCRIPT5); testSame(options, code); options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT); test(options, code, code, StrictModeCheck.DELETE_VARIABLE); } public void testIssue598() { CompilerOptions options = createCompilerOptions(); options.setLanguageIn(LanguageMode.ECMASCRIPT5_STRICT); WarningLevel.VERBOSE.setOptionsForWarningLevel(options); options.setLanguageIn(LanguageMode.ECMASCRIPT5); String code = "'use strict';\n" + "function App() {}\n" + "App.prototype = {\n" + " get appData() { return this.appData_; },\n" + " set appData(data) { this.appData_ = data; }\n" + "};"; Compiler compiler = compile(options, code); testSame(options, code); } public void testIssue701() { // Check ASCII art in license comments. String ascii = "/**\n" + " * @preserve\n" + " This\n" + " is\n" + " ASCII ART\n" + "*/"; String result = "/*\n\n" + " This\n" + " is\n" + " ASCII ART\n" + "*/\n"; testSame(createCompilerOptions(), ascii); assertEquals(result, lastCompiler.toSource()); } public void testCoaleseVariables() { CompilerOptions options = createCompilerOptions(); options.foldConstants = false; options.coalesceVariableNames = true; String code = "function f(a) {" + " if (a) {" + " return a;" + " } else {" + " var b = a;" + " return b;" + " }" + " return a;" + "}"; String expected = "function f(a) {" + " if (a) {" + " return a;" + " } else {" + " a = a;" + " return a;" + " }" + " return a;" + "}"; test(options, code, expected); options.foldConstants = true; options.coalesceVariableNames = false; code = "function f(a) {" + " if (a) {" + " return a;" + " } else {" + " var b = a;" + " return b;" + " }" + " return a;" + "}"; expected = "function f(a) {" + " if (!a) {" + " var b = a;" + " return b;" + " }" + " return a;" + "}"; test(options, code, expected); options.foldConstants = true; options.coalesceVariableNames = true; expected = "function f(a) {" + " return a;" + "}"; test(options, code, expected); } public void testLateStatementFusion() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; test(options, "while(a){a();if(b){b();b()}}", "for(;a;)a(),b&&(b(),b())"); } public void testLateConstantReordering() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; test(options, "if (x < 1 || x > 1 || 1 < x || 1 > x) { alert(x) }", " (1 > x || 1 < x || 1 < x || 1 > x) && alert(x) "); } public void testsyntheticBlockOnDeadAssignments() { CompilerOptions options = createCompilerOptions(); options.deadAssignmentElimination = true; options.removeUnusedVars = true; options.syntheticBlockStartMarker = "START"; options.syntheticBlockEndMarker = "END"; test(options, "var x; x = 1; START(); x = 1;END();x()", "var x; x = 1;{START();{x = 1}END()}x()"); } public void testBug4152835() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; options.syntheticBlockStartMarker = "START"; options.syntheticBlockEndMarker = "END"; test(options, "START();END()", "{START();{}END()}"); } public void testBug5786871() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; test(options, "function () {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue378() { CompilerOptions options = createCompilerOptions(); options.inlineVariables = true; options.flowSensitiveInlineVariables = true; testSame(options, "function f(c) {var f = c; arguments[0] = this;" + " f.apply(this, arguments); return this;}"); } public void testIssue550() { CompilerOptions options = createCompilerOptions(); CompilationLevel.SIMPLE_OPTIMIZATIONS .setOptionsForCompilationLevel(options); options.foldConstants = true; options.inlineVariables = true; options.flowSensitiveInlineVariables = true; test(options, "function f(h) {\n" + " var a = h;\n" + " a = a + 'x';\n" + " a = a + 'y';\n" + " return a;\n" + "}", "function f(a) {return a + 'xy'}"); } public void testIssue284() { CompilerOptions options = createCompilerOptions(); options.smartNameRemoval = true; test(options, "var goog = {};" + "goog.inherits = function(x, y) {};" + "var ns = {};" + "/** @constructor */" + "ns.PageSelectionModel = function() {};" + "/** @constructor */" + "ns.PageSelectionModel.FooEvent = function() {};" + "/** @constructor */" + "ns.PageSelectionModel.SelectEvent = function() {};" + "goog.inherits(ns.PageSelectionModel.ChangeEvent," + " ns.PageSelectionModel.FooEvent);", ""); } public void testCodingConvention() { Compiler compiler = new Compiler(); compiler.initOptions(new CompilerOptions()); assertEquals( compiler.getCodingConvention().getClass().toString(), ClosureCodingConvention.class.toString()); } public void testJQueryStringSplitLoops() { CompilerOptions options = createCompilerOptions(); options.foldConstants = true; test(options, "var x=['1','2','3','4','5','6','7']", "var x='1,2,3,4,5,6,7'.split(',')"); options = createCompilerOptions(); options.foldConstants = true; options.computeFunctionSideEffects = false; options.removeUnusedVars = true; // If we do splits too early, it would add a sideeffect to x. test(options, "var x=['1','2','3','4','5','6','7']", ""); } public void testAlwaysRunSafetyCheck() { CompilerOptions options = createCompilerOptions(); options.checkSymbols = false; options.customPasses = ArrayListMultimap.create(); options.customPasses.put( CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, new CompilerPass() { @Override public void process(Node externs, Node root) { Node var = root.getLastChild().getFirstChild(); assertEquals(Token.VAR, var.getType()); var.detachFromParent(); } }); try { test(options, "var x = 3; function f() { return x + z; }", "function f() { return x + z; }"); fail("Expected runtime exception"); } catch (RuntimeException e) { assertTrue(e.getMessage().indexOf("Unexpected variable x") != -1); } } public void testSuppressEs5StrictWarning() { CompilerOptions options = createCompilerOptions(); options.setWarningLevel(DiagnosticGroups.ES5_STRICT, CheckLevel.WARNING); testSame(options, "/** @suppress{es5Strict} */\n" + "function f() { var arguments; }"); } public void testCheckProvidesWarning() { CompilerOptions options = createCompilerOptions(); options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING); options.setCheckProvides(CheckLevel.WARNING); test(options, "/** @constructor */\n" + "function f() { var arguments; }", DiagnosticType.warning("JSC_MISSING_PROVIDE", "missing goog.provide(''{0}'')")); } public void testSuppressCheckProvidesWarning() { CompilerOptions options = createCompilerOptions(); options.setWarningLevel(DiagnosticGroups.CHECK_PROVIDES, CheckLevel.WARNING); options.setCheckProvides(CheckLevel.WARNING); testSame(options, "/** @constructor\n" + " * @suppress{checkProvides} */\n" + "function f() { var arguments; }"); } public void testRenamePrefixNamespace() { String code = "var x = {}; x.FOO = 5; x.bar = 3;"; CompilerOptions options = createCompilerOptions(); testSame(options, code); options.collapseProperties = true; options.renamePrefixNamespace = "_"; test(options, code, "_.x$FOO = 5; _.x$bar = 3;"); } public void testRenamePrefixNamespaceActivatesMoveFunctionDeclarations() { CompilerOptions options = createCompilerOptions(); String code = "var x = f; function f() { return 3; }"; testSame(options, code); assertFalse(options.moveFunctionDeclarations); options.renamePrefixNamespace = "_"; test(options, code, "_.f = function() { return 3; }; _.x = _.f;"); } public void testBrokenNameSpace() { CompilerOptions options = createCompilerOptions(); String code = "var goog; goog.provide('i.am.on.a.Horse');" + "i.am.on.a.Horse = function() {};" + "i.am.on.a.Horse.prototype.x = function() {};" + "i.am.on.a.Boat.prototype.y = function() {}"; options.closurePass = true; options.collapseProperties = true; options.smartNameRemoval = true; test(options, code, ""); } public void testNamelessParameter() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); String code = "var impl_0;" + "$load($init());" + "function $load(){" + " window['f'] = impl_0;" + "}" + "function $init() {" + " impl_0 = {};" + "}"; String result = "window.f = {};"; test(options, code, result); } public void testHiddenSideEffect() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); options.setAliasExternals(true); String code = "window.offsetWidth;"; String result = "window.offsetWidth;"; test(options, code, result); } public void testNegativeZero() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); test(options, "function bar(x) { return x; }\n" + "function foo(x) { print(x / bar(0));\n" + " print(x / bar(-0)); }\n" + "foo(3);", "print(3/0);print(3/-0);"); } public void testSingletonGetter1() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); options.setCodingConvention(new ClosureCodingConvention()); test(options, "/** @const */\n" + "var goog = goog || {};\n" + "goog.addSingletonGetter = function(ctor) {\n" + " ctor.getInstance = function() {\n" + " return ctor.instance_ || (ctor.instance_ = new ctor());\n" + " };\n" + "};" + "function Foo() {}\n" + "goog.addSingletonGetter(Foo);" + "Foo.prototype.bar = 1;" + "function Bar() {}\n" + "goog.addSingletonGetter(Bar);" + "Bar.prototype.bar = 1;", ""); } public void testIncompleteFunction1() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; DiagnosticType[] warnings = new DiagnosticType[]{ RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR}; test(options, new String[] { "var foo = {bar: function(e) }" }, new String[] { "var foo = {bar: function(e){}};" }, warnings ); } public void testIncompleteFunction2() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; DiagnosticType[] warnings = new DiagnosticType[]{ RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR, RhinoErrorReporter.PARSE_ERROR}; test(options, new String[] { "function hi" }, new String[] { "function hi() {}" }, warnings ); } public void testSortingOff() { CompilerOptions options = new CompilerOptions(); options.closurePass = true; options.setCodingConvention(new ClosureCodingConvention()); test(options, new String[] { "goog.require('goog.beer');", "goog.provide('goog.beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testUnboundedArrayLiteralInfiniteLoop() { CompilerOptions options = createCompilerOptions(); options.ideMode = true; test(options, "var x = [1, 2", "var x = [1, 2]", RhinoErrorReporter.PARSE_ERROR); } public void testProvideRequireSameFile() throws Exception { CompilerOptions options = createCompilerOptions(); options.setDependencyOptions( new DependencyOptions() .setDependencySorting(true)); options.closurePass = true; test( options, "goog.provide('x');\ngoog.require('x');", "var x = {};"); } public void testStrictWarningsGuard() throws Exception { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.addWarningsGuard(new StrictWarningsGuard()); Compiler compiler = compile(options, "/** @return {number} */ function f() { return true; }"); assertEquals(1, compiler.getErrors().length); assertEquals(0, compiler.getWarnings().length); } public void testStrictWarningsGuardEmergencyMode() throws Exception { CompilerOptions options = createCompilerOptions(); options.checkTypes = true; options.addWarningsGuard(new StrictWarningsGuard()); options.useEmergencyFailSafe(); Compiler compiler = compile(options, "/** @return {number} */ function f() { return true; }"); assertEquals(0, compiler.getErrors().length); assertEquals(1, compiler.getWarnings().length); } private void testSame(CompilerOptions options, String original) { testSame(options, new String[] { original }); } private void testSame(CompilerOptions options, String[] original) { test(options, original, original); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(CompilerOptions options, String original, String compiled) { test(options, new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(CompilerOptions options, String[] original, String[] compiled) { Compiler compiler = compile(options, original); assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); Node root = compiler.getRoot().getLastChild(); Node expectedRoot = parse(compiled, options); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } /** * Asserts that when compiling with the given compiler options, * there is an error or warning. */ private void test(CompilerOptions options, String original, DiagnosticType warning) { test(options, new String[] { original }, warning); } private void test(CompilerOptions options, String original, String compiled, DiagnosticType warning) { test(options, new String[] { original }, new String[] { compiled }, warning); } private void test(CompilerOptions options, String[] original, DiagnosticType warning) { test(options, original, null, warning); } /** * Asserts that when compiling with the given compiler options, * there is an error or warning. */ private void test(CompilerOptions options, String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(options, original); checkUnexpectedErrorsOrWarnings(compiler, 1); assertEquals("Expected exactly one warning or error", 1, compiler.getErrors().length + compiler.getWarnings().length); if (compiler.getErrors().length > 0) { assertEquals(warning, compiler.getErrors()[0].getType()); } else { assertEquals(warning, compiler.getWarnings()[0].getType()); } if (compiled != null) { Node root = compiler.getRoot().getLastChild(); Node expectedRoot = parse(compiled, options); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling with the given compiler options, * there is an error or warning. */ private void test(CompilerOptions options, String[] original, String[] compiled, DiagnosticType[] warnings) { Compiler compiler = compile(options, original); checkUnexpectedErrorsOrWarnings(compiler, warnings.length); if (compiled != null) { Node root = compiler.getRoot().getLastChild(); Node expectedRoot = parse(compiled, options); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } private void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } private Compiler compile(CompilerOptions options, String original) { return compile(options, new String[] { original }); } private Compiler compile(CompilerOptions options, String[] original) { Compiler compiler = lastCompiler = new Compiler(); List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode("input" + i, original[i])); } compiler.compileModules( externs, Lists.newArrayList(CompilerTestCase.createModuleChain(original)), options); return compiler; } private Node parse(String[] original, CompilerOptions options) { Compiler compiler = new Compiler(); List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode("input" + i, original[i])); } compiler.init(externs, inputs, options); checkUnexpectedErrorsOrWarnings(compiler, 0); Node all = compiler.parseInputs(); checkUnexpectedErrorsOrWarnings(compiler, 0); Node n = all.getLastChild(); Node externs = all.getFirstChild(); (new CreateSyntheticBlocks( compiler, "synStart", "synEnd")).process(externs, n); (new Normalize(compiler, false)).process(externs, n); (MakeDeclaredNamesUnique.getContextualRenameInverter(compiler)).process( externs, n); (new Denormalize(compiler)).process(externs, n); return n; } /** Creates a CompilerOptions object with google coding conventions. */ private CompilerOptions createCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new GoogleCodingConvention()); return options; } }
public void testPrintOptionWithEmptyArgNameUsage() { Option option = new Option("f", true, null); option.setArgName(""); option.setRequired(true); Options options = new Options(); options.addOption(option); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app -f" + EOL, out.toString()); }
org.apache.commons.cli.HelpFormatterTest::testPrintOptionWithEmptyArgNameUsage
src/test/org/apache/commons/cli/HelpFormatterTest.java
273
src/test/org/apache/commons/cli/HelpFormatterTest.java
testPrintOptionWithEmptyArgNameUsage
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Comparator; import junit.framework.TestCase; /** * Test case for the HelpFormatter class * * @author Slawek Zachcial * @author John Keyes ( john at integralsource.com ) * @author brianegge **/ public class HelpFormatterTest extends TestCase { private static final String EOL = System.getProperty("line.separator"); public static void main( String[] args ) { String[] testName = { HelpFormatterTest.class.getName() }; junit.textui.TestRunner.main(testName); } public void testFindWrapPos() throws Exception { HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; //text width should be max 8; the wrap postition is 7 assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0)); //starting from 8 must give -1 - the wrap pos is after end assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); //if there is no a good position before width to make a wrapping look for the next one text = "aaaa aa"; assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); } public void testPrintWrapped() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; String expected; expected = "This is a" + hf.getNewLine() + "test."; hf.renderWrappedText(sb, 12, 0, text); assertEquals("single line text", expected, sb.toString()); sb.setLength(0); expected = "This is a" + hf.getNewLine() + " test."; hf.renderWrappedText(sb, 12, 4, text); assertEquals("single line padded text", expected, sb.toString()); text = " -p,--period <PERIOD> PERIOD is time duration of form " + "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; sb.setLength(0); expected = " -p,--period <PERIOD> PERIOD is time duration of" + hf.getNewLine() + " form DATE[-DATE] where DATE" + hf.getNewLine() + " has form YYYY[MM[DD]]"; hf.renderWrappedText(sb, 53, 24, text); assertEquals("single line padded text 2", expected, sb.toString()); text = "aaaa aaaa aaaa" + hf.getNewLine() + "aaaaaa" + hf.getNewLine() + "aaaaa"; expected = text; sb.setLength(0); hf.renderWrappedText(sb, 16, 0, text); assertEquals("multi line text", expected, sb.toString()); expected = "aaaa aaaa aaaa" + hf.getNewLine() + " aaaaaa" + hf.getNewLine() + " aaaaa"; sb.setLength(0); hf.renderWrappedText(sb, 16, 4, text); assertEquals("multi-line padded text", expected, sb.toString()); } public void testPrintOptions() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); final int leftPad = 1; final int descPad = 3; final String lpad = hf.createPadding(leftPad); final String dpad = hf.createPadding(descPad); Options options = null; String expected = null; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa"; hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("simple non-wrapped option", expected, sb.toString()); int nextLineTabStop = leftPad+descPad+"-a".length(); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "aaaa aaaa"; sb.setLength(0); hf.renderOptions(sb, nextLineTabStop+17, options, leftPad, descPad); assertEquals("simple wrapped option", expected, sb.toString()); options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("long non-wrapped option", expected, sb.toString()); nextLineTabStop = leftPad+descPad+"-a,--aaa".length(); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("long wrapped option", expected, sb.toString()); options = new Options(). addOption("a", "aaa", false, "dddd dddd dddd dddd"). addOption("b", false, "feeee eeee eeee eeee"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.getNewLine() + lpad + "-b " + dpad + "feeee eeee" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "eeee eeee"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("multiple wrapped options", expected, sb.toString()); } public void testAutomaticUsage() throws Exception { HelpFormatter hf = new HelpFormatter(); Options options = null; String expected = "usage: app [-a]"; ByteArrayOutputStream out = new ByteArrayOutputStream( ); PrintWriter pw = new PrintWriter( out ); options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); expected = "usage: app [-a] [-b]"; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa") .addOption("b", false, "bbb" ); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); } // This test ensures the options are properly sorted // See https://issues.apache.org/jira/browse/CLI-131 public void testPrintUsage() { Option optionA = new Option("a", "first"); Option optionB = new Option("b", "second"); Option optionC = new Option("c", "third"); Options opts = new Options(); opts.addOption(optionA); opts.addOption(optionB); opts.addOption(optionC); HelpFormatter helpFormatter = new HelpFormatter(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(bytesOut); helpFormatter.printUsage(printWriter, 80, "app", opts); printWriter.close(); assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString()); } // uses the test for CLI-131 to implement CLI-155 public void testPrintSortedUsage() { Option optionA = new Option("a", "first"); Option optionB = new Option("b", "second"); Option optionC = new Option("c", "third"); Options opts = new Options(); opts.addOption(optionA); opts.addOption(optionB); opts.addOption(optionC); HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setOptionComparator( new Comparator() { public int compare(Object o1, Object o2) { // reverses the fuctionality of the default comparator Option opt1 = (Option)o1; Option opt2 = (Option)o2; return opt2.getKey().compareToIgnoreCase(opt1.getKey()); } } ); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(bytesOut); helpFormatter.printUsage(printWriter, 80, "app", opts); printWriter.close(); assertEquals("usage: app [-c] [-b] [-a]" + EOL, bytesOut.toString()); } public void testPrintOptionGroupUsage() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create("a")); group.addOption(OptionBuilder.create("b")); group.addOption(OptionBuilder.create("c")); Options options = new Options(); options.addOptionGroup(group); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app [-a | -b | -c]" + EOL, out.toString()); } public void testPrintRequiredOptionGroupUsage() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create("a")); group.addOption(OptionBuilder.create("b")); group.addOption(OptionBuilder.create("c")); group.setRequired(true); Options options = new Options(); options.addOptionGroup(group); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app -a | -b | -c" + EOL, out.toString()); } public void testPrintOptionWithEmptyArgNameUsage() { Option option = new Option("f", true, null); option.setArgName(""); option.setRequired(true); Options options = new Options(); options.addOption(option); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app -f" + EOL, out.toString()); } }
// You are a professional Java test case writer, please create a test case named `testPrintOptionWithEmptyArgNameUsage` for the issue `Cli-cli-1`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-cli-1 // // ## Issue-Title: // PosixParser interupts "-target opt" as "-t arget opt" // // ## Issue-Description: // // This was posted on the Commons-Developer list and confirmed as a bug. // // // > Is this a bug? Or am I using this incorrectly? // // > I have an option with short and long values. Given code that is // // > essentially what is below, with a PosixParser I see results as // // > follows: // // > // // > A command line with just "-t" prints out the results of the catch // // > block // // > (OK) // // > A command line with just "-target" prints out the results of the catch // // > block (OK) // // > A command line with just "-t foobar.com" prints out "processing selected // // > target: foobar.com" (OK) // // > A command line with just "-target foobar.com" prints out "processing // // > selected target: arget" (ERROR?) // // > // // > ====================================================================== // // > == // // > ======================= // // > private static final String OPTION\_TARGET = "t"; // // > private static final String OPTION\_TARGET\_LONG = "target"; // // > // ... // // > Option generateTarget = new Option(OPTION\_TARGET, // // > OPTION\_TARGET\_LONG, // // > true, // // > "Generate files for the specified // // > target machine"); // // > // ... // // > try // // // { // > parsedLine = parser.parse(cmdLineOpts, args); // > } // catch (ParseException pe) // // // { // > System.out.println("Invalid command: " + pe.getMessage() + // > "\n"); // > HelpFormatter hf = new HelpFormatter(); // > hf.printHelp(USAGE, cmdLineOpts); // > System.exit(-1); // > } // > // // > if (parsedLine.hasOption(OPTION\_TARGET)) // // // { // > System.out.println("processing selected target: " + // > parsedLine.getOptionValue(OPTION\_TARGET)); // > } // // It is a bug but it is due to well defined behaviour (so that makes me feel a // // little better about myself ![](/jira/images/icons/emoticons/wink.png). To support **special** // // (well I call them special anyway) like -Dsystem.property=value we need to be // // able to examine the first character of an option. If the first character is // // itself defined as an Option then the remainder of the token is used as the // // value, e.g. 'D' is the token, it is an option so 'system.property=value' is the // // argument value for that option. This is the behaviour that we are seeing for // // your example. // // 't' is the token, it is an options so 'arget' is the argument value. // // // I suppose a solution to this could be to have a way to specify properties for // // parsers. In this case 'posix.special.option == true' for turning // // on **special** options. I'll have a look into this and let you know. // // // Just to keep track of this and to get you used to how we operate, can you log a // // bug in bugzilla for this. // // // Thanks, // // -John K // // // // // public void testPrintOptionWithEmptyArgNameUsage() {
273
11
259
src/test/org/apache/commons/cli/HelpFormatterTest.java
src/test
```markdown ## Issue-ID: Cli-cli-1 ## Issue-Title: PosixParser interupts "-target opt" as "-t arget opt" ## Issue-Description: This was posted on the Commons-Developer list and confirmed as a bug. > Is this a bug? Or am I using this incorrectly? > I have an option with short and long values. Given code that is > essentially what is below, with a PosixParser I see results as > follows: > > A command line with just "-t" prints out the results of the catch > block > (OK) > A command line with just "-target" prints out the results of the catch > block (OK) > A command line with just "-t foobar.com" prints out "processing selected > target: foobar.com" (OK) > A command line with just "-target foobar.com" prints out "processing > selected target: arget" (ERROR?) > > ====================================================================== > == > ======================= > private static final String OPTION\_TARGET = "t"; > private static final String OPTION\_TARGET\_LONG = "target"; > // ... > Option generateTarget = new Option(OPTION\_TARGET, > OPTION\_TARGET\_LONG, > true, > "Generate files for the specified > target machine"); > // ... > try { > parsedLine = parser.parse(cmdLineOpts, args); > } catch (ParseException pe) { > System.out.println("Invalid command: " + pe.getMessage() + > "\n"); > HelpFormatter hf = new HelpFormatter(); > hf.printHelp(USAGE, cmdLineOpts); > System.exit(-1); > } > > if (parsedLine.hasOption(OPTION\_TARGET)) { > System.out.println("processing selected target: " + > parsedLine.getOptionValue(OPTION\_TARGET)); > } It is a bug but it is due to well defined behaviour (so that makes me feel a little better about myself ![](/jira/images/icons/emoticons/wink.png). To support **special** (well I call them special anyway) like -Dsystem.property=value we need to be able to examine the first character of an option. If the first character is itself defined as an Option then the remainder of the token is used as the value, e.g. 'D' is the token, it is an option so 'system.property=value' is the argument value for that option. This is the behaviour that we are seeing for your example. 't' is the token, it is an options so 'arget' is the argument value. I suppose a solution to this could be to have a way to specify properties for parsers. In this case 'posix.special.option == true' for turning on **special** options. I'll have a look into this and let you know. Just to keep track of this and to get you used to how we operate, can you log a bug in bugzilla for this. Thanks, -John K ``` You are a professional Java test case writer, please create a test case named `testPrintOptionWithEmptyArgNameUsage` for the issue `Cli-cli-1`, utilizing the provided issue report information and the following function signature. ```java public void testPrintOptionWithEmptyArgNameUsage() { ```
259
[ "org.apache.commons.cli.HelpFormatter" ]
f1b56a398fc12c3d3d6d11d38ba53eef5c26b1d2e7d3494c3c19ab273505339e
public void testPrintOptionWithEmptyArgNameUsage()
// You are a professional Java test case writer, please create a test case named `testPrintOptionWithEmptyArgNameUsage` for the issue `Cli-cli-1`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-cli-1 // // ## Issue-Title: // PosixParser interupts "-target opt" as "-t arget opt" // // ## Issue-Description: // // This was posted on the Commons-Developer list and confirmed as a bug. // // // > Is this a bug? Or am I using this incorrectly? // // > I have an option with short and long values. Given code that is // // > essentially what is below, with a PosixParser I see results as // // > follows: // // > // // > A command line with just "-t" prints out the results of the catch // // > block // // > (OK) // // > A command line with just "-target" prints out the results of the catch // // > block (OK) // // > A command line with just "-t foobar.com" prints out "processing selected // // > target: foobar.com" (OK) // // > A command line with just "-target foobar.com" prints out "processing // // > selected target: arget" (ERROR?) // // > // // > ====================================================================== // // > == // // > ======================= // // > private static final String OPTION\_TARGET = "t"; // // > private static final String OPTION\_TARGET\_LONG = "target"; // // > // ... // // > Option generateTarget = new Option(OPTION\_TARGET, // // > OPTION\_TARGET\_LONG, // // > true, // // > "Generate files for the specified // // > target machine"); // // > // ... // // > try // // // { // > parsedLine = parser.parse(cmdLineOpts, args); // > } // catch (ParseException pe) // // // { // > System.out.println("Invalid command: " + pe.getMessage() + // > "\n"); // > HelpFormatter hf = new HelpFormatter(); // > hf.printHelp(USAGE, cmdLineOpts); // > System.exit(-1); // > } // > // // > if (parsedLine.hasOption(OPTION\_TARGET)) // // // { // > System.out.println("processing selected target: " + // > parsedLine.getOptionValue(OPTION\_TARGET)); // > } // // It is a bug but it is due to well defined behaviour (so that makes me feel a // // little better about myself ![](/jira/images/icons/emoticons/wink.png). To support **special** // // (well I call them special anyway) like -Dsystem.property=value we need to be // // able to examine the first character of an option. If the first character is // // itself defined as an Option then the remainder of the token is used as the // // value, e.g. 'D' is the token, it is an option so 'system.property=value' is the // // argument value for that option. This is the behaviour that we are seeing for // // your example. // // 't' is the token, it is an options so 'arget' is the argument value. // // // I suppose a solution to this could be to have a way to specify properties for // // parsers. In this case 'posix.special.option == true' for turning // // on **special** options. I'll have a look into this and let you know. // // // Just to keep track of this and to get you used to how we operate, can you log a // // bug in bugzilla for this. // // // Thanks, // // -John K // // // // //
Cli
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Comparator; import junit.framework.TestCase; /** * Test case for the HelpFormatter class * * @author Slawek Zachcial * @author John Keyes ( john at integralsource.com ) * @author brianegge **/ public class HelpFormatterTest extends TestCase { private static final String EOL = System.getProperty("line.separator"); public static void main( String[] args ) { String[] testName = { HelpFormatterTest.class.getName() }; junit.textui.TestRunner.main(testName); } public void testFindWrapPos() throws Exception { HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; //text width should be max 8; the wrap postition is 7 assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0)); //starting from 8 must give -1 - the wrap pos is after end assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); //if there is no a good position before width to make a wrapping look for the next one text = "aaaa aa"; assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); } public void testPrintWrapped() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; String expected; expected = "This is a" + hf.getNewLine() + "test."; hf.renderWrappedText(sb, 12, 0, text); assertEquals("single line text", expected, sb.toString()); sb.setLength(0); expected = "This is a" + hf.getNewLine() + " test."; hf.renderWrappedText(sb, 12, 4, text); assertEquals("single line padded text", expected, sb.toString()); text = " -p,--period <PERIOD> PERIOD is time duration of form " + "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; sb.setLength(0); expected = " -p,--period <PERIOD> PERIOD is time duration of" + hf.getNewLine() + " form DATE[-DATE] where DATE" + hf.getNewLine() + " has form YYYY[MM[DD]]"; hf.renderWrappedText(sb, 53, 24, text); assertEquals("single line padded text 2", expected, sb.toString()); text = "aaaa aaaa aaaa" + hf.getNewLine() + "aaaaaa" + hf.getNewLine() + "aaaaa"; expected = text; sb.setLength(0); hf.renderWrappedText(sb, 16, 0, text); assertEquals("multi line text", expected, sb.toString()); expected = "aaaa aaaa aaaa" + hf.getNewLine() + " aaaaaa" + hf.getNewLine() + " aaaaa"; sb.setLength(0); hf.renderWrappedText(sb, 16, 4, text); assertEquals("multi-line padded text", expected, sb.toString()); } public void testPrintOptions() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); final int leftPad = 1; final int descPad = 3; final String lpad = hf.createPadding(leftPad); final String dpad = hf.createPadding(descPad); Options options = null; String expected = null; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa"; hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("simple non-wrapped option", expected, sb.toString()); int nextLineTabStop = leftPad+descPad+"-a".length(); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "aaaa aaaa"; sb.setLength(0); hf.renderOptions(sb, nextLineTabStop+17, options, leftPad, descPad); assertEquals("simple wrapped option", expected, sb.toString()); options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("long non-wrapped option", expected, sb.toString()); nextLineTabStop = leftPad+descPad+"-a,--aaa".length(); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("long wrapped option", expected, sb.toString()); options = new Options(). addOption("a", "aaa", false, "dddd dddd dddd dddd"). addOption("b", false, "feeee eeee eeee eeee"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.getNewLine() + lpad + "-b " + dpad + "feeee eeee" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "eeee eeee"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("multiple wrapped options", expected, sb.toString()); } public void testAutomaticUsage() throws Exception { HelpFormatter hf = new HelpFormatter(); Options options = null; String expected = "usage: app [-a]"; ByteArrayOutputStream out = new ByteArrayOutputStream( ); PrintWriter pw = new PrintWriter( out ); options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); expected = "usage: app [-a] [-b]"; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa") .addOption("b", false, "bbb" ); hf.printUsage( pw, 60, "app", options ); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); } // This test ensures the options are properly sorted // See https://issues.apache.org/jira/browse/CLI-131 public void testPrintUsage() { Option optionA = new Option("a", "first"); Option optionB = new Option("b", "second"); Option optionC = new Option("c", "third"); Options opts = new Options(); opts.addOption(optionA); opts.addOption(optionB); opts.addOption(optionC); HelpFormatter helpFormatter = new HelpFormatter(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(bytesOut); helpFormatter.printUsage(printWriter, 80, "app", opts); printWriter.close(); assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString()); } // uses the test for CLI-131 to implement CLI-155 public void testPrintSortedUsage() { Option optionA = new Option("a", "first"); Option optionB = new Option("b", "second"); Option optionC = new Option("c", "third"); Options opts = new Options(); opts.addOption(optionA); opts.addOption(optionB); opts.addOption(optionC); HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setOptionComparator( new Comparator() { public int compare(Object o1, Object o2) { // reverses the fuctionality of the default comparator Option opt1 = (Option)o1; Option opt2 = (Option)o2; return opt2.getKey().compareToIgnoreCase(opt1.getKey()); } } ); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(bytesOut); helpFormatter.printUsage(printWriter, 80, "app", opts); printWriter.close(); assertEquals("usage: app [-c] [-b] [-a]" + EOL, bytesOut.toString()); } public void testPrintOptionGroupUsage() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create("a")); group.addOption(OptionBuilder.create("b")); group.addOption(OptionBuilder.create("c")); Options options = new Options(); options.addOptionGroup(group); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app [-a | -b | -c]" + EOL, out.toString()); } public void testPrintRequiredOptionGroupUsage() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create("a")); group.addOption(OptionBuilder.create("b")); group.addOption(OptionBuilder.create("c")); group.setRequired(true); Options options = new Options(); options.addOptionGroup(group); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app -a | -b | -c" + EOL, out.toString()); } public void testPrintOptionWithEmptyArgNameUsage() { Option option = new Option("f", true, null); option.setArgName(""); option.setRequired(true); Options options = new Options(); options.addOption(option); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app -f" + EOL, out.toString()); } }
@Test public void testMath272() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); assertEquals(3.0, solution.getValue(), .0000001); }
org.apache.commons.math.optimization.linear.SimplexSolverTest::testMath272
src/test/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
48
src/test/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
testMath272
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.linear.RealVectorImpl; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.OptimizationException; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Test; public class SimplexSolverTest { @Test public void testMath272() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); assertEquals(3.0, solution.getValue(), .0000001); } @Test public void testSimplexSolver() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 7); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(57.0, solution.getValue(), 0.0); } /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(50.0, solution.getValue(), 0.0); } @Test public void testMinimization() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false); assertEquals(4.0, solution.getPoint()[0], 0.0); assertEquals(0.0, solution.getPoint()[1], 0.0); assertEquals(-13.0, solution.getValue(), 0.0); } @Test public void testSolutionWithNegativeDecisionVariable() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(-2.0, solution.getPoint()[0], 0.0); assertEquals(8.0, solution.getPoint()[1], 0.0); assertEquals(12.0, solution.getValue(), 0.0); } @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test public void testRestrictVariablesToNonNegative() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); assertEquals(480.419243986254, solution.getPoint()[1], .0000001); assertEquals(0.0, solution.getPoint()[2], .0000001); assertEquals(0.0, solution.getPoint()[3], .0000001); assertEquals(0.0, solution.getPoint()[4], .0000001); assertEquals(1438556.7491409, solution.getValue(), .0000001); } @Test public void testEpsilon() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(1.0, solution.getPoint()[0], 0.0); assertEquals(1.0, solution.getPoint()[1], 0.0); assertEquals(0.0, solution.getPoint()[2], 0.0); assertEquals(15.0, solution.getValue(), 0.0); } @Test public void testTrivialModel() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(0, solution.getValue(), .0000001); } @Test public void testLargeModel() throws OptimizationException { double[] objective = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(7518.0, solution.getValue(), .0000001); } /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 */ private LinearConstraint equationFromString(int numCoefficients, String s) { Relationship relationship; if (s.contains(">=")) { relationship = Relationship.GEQ; } else if (s.contains("<=")) { relationship = Relationship.LEQ; } else if (s.contains("=")) { relationship = Relationship.EQ; } else { throw new IllegalArgumentException(); } String[] equationParts = s.split("[>|<]?="); double rhs = Double.parseDouble(equationParts[1].trim()); RealVector lhs = new RealVectorImpl(numCoefficients); String left = equationParts[0].replaceAll(" ?x", ""); String[] coefficients = left.split(" "); for (String coefficient : coefficients) { double value = coefficient.charAt(0) == '-' ? -1 : 1; int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim()); lhs.setEntry(index, value); } return new LinearConstraint(lhs, relationship, rhs); } }
// You are a professional Java test case writer, please create a test case named `testMath272` for the issue `Math-MATH-272`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-272 // // ## Issue-Title: // Simplex Solver arrives at incorrect solution // // ## Issue-Description: // // I have reduced the problem reported to me down to a minimal test case which I will attach. // // // // // @Test public void testMath272() throws OptimizationException {
48
88
33
src/test/org/apache/commons/math/optimization/linear/SimplexSolverTest.java
src/test
```markdown ## Issue-ID: Math-MATH-272 ## Issue-Title: Simplex Solver arrives at incorrect solution ## Issue-Description: I have reduced the problem reported to me down to a minimal test case which I will attach. ``` You are a professional Java test case writer, please create a test case named `testMath272` for the issue `Math-MATH-272`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMath272() throws OptimizationException { ```
33
[ "org.apache.commons.math.optimization.linear.SimplexTableau" ]
f1b768669ce7276966f8dddb1908c1bc07d04ad14208c0b6d30b88e454242f05
@Test public void testMath272() throws OptimizationException
// You are a professional Java test case writer, please create a test case named `testMath272` for the issue `Math-MATH-272`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-272 // // ## Issue-Title: // Simplex Solver arrives at incorrect solution // // ## Issue-Description: // // I have reduced the problem reported to me down to a minimal test case which I will attach. // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.linear.RealVectorImpl; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.OptimizationException; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Test; public class SimplexSolverTest { @Test public void testMath272() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(0.0, solution.getPoint()[0], .0000001); assertEquals(1.0, solution.getPoint()[1], .0000001); assertEquals(1.0, solution.getPoint()[2], .0000001); assertEquals(3.0, solution.getValue(), .0000001); } @Test public void testSimplexSolver() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 7); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(57.0, solution.getValue(), 0.0); } /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(2.0, solution.getPoint()[0], 0.0); assertEquals(2.0, solution.getPoint()[1], 0.0); assertEquals(50.0, solution.getValue(), 0.0); } @Test public void testMinimization() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false); assertEquals(4.0, solution.getPoint()[0], 0.0); assertEquals(0.0, solution.getPoint()[1], 0.0); assertEquals(-13.0, solution.getValue(), 0.0); } @Test public void testSolutionWithNegativeDecisionVariable() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(-2.0, solution.getPoint()[0], 0.0); assertEquals(8.0, solution.getPoint()[1], 0.0); assertEquals(12.0, solution.getValue(), 0.0); } @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); SimplexSolver solver = new SimplexSolver(); solver.optimize(f, constraints, GoalType.MAXIMIZE, false); } @Test public void testRestrictVariablesToNonNegative() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); assertEquals(480.419243986254, solution.getPoint()[1], .0000001); assertEquals(0.0, solution.getPoint()[2], .0000001); assertEquals(0.0, solution.getPoint()[3], .0000001); assertEquals(0.0, solution.getPoint()[4], .0000001); assertEquals(1438556.7491409, solution.getValue(), .0000001); } @Test public void testEpsilon() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false); assertEquals(1.0, solution.getPoint()[0], 0.0); assertEquals(1.0, solution.getPoint()[1], 0.0); assertEquals(0.0, solution.getPoint()[2], 0.0); assertEquals(15.0, solution.getValue(), 0.0); } @Test public void testTrivialModel() throws OptimizationException { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true); assertEquals(0, solution.getValue(), .0000001); } @Test public void testLargeModel() throws OptimizationException { double[] objective = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); SimplexSolver solver = new SimplexSolver(); RealPointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true); assertEquals(7518.0, solution.getValue(), .0000001); } /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 */ private LinearConstraint equationFromString(int numCoefficients, String s) { Relationship relationship; if (s.contains(">=")) { relationship = Relationship.GEQ; } else if (s.contains("<=")) { relationship = Relationship.LEQ; } else if (s.contains("=")) { relationship = Relationship.EQ; } else { throw new IllegalArgumentException(); } String[] equationParts = s.split("[>|<]?="); double rhs = Double.parseDouble(equationParts[1].trim()); RealVector lhs = new RealVectorImpl(numCoefficients); String left = equationParts[0].replaceAll(" ?x", ""); String[] coefficients = left.split(" "); for (String coefficient : coefficients) { double value = coefficient.charAt(0) == '-' ? -1 : 1; int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim()); lhs.setEntry(index, value); } return new LinearConstraint(lhs, relationship, rhs); } }
@Test public void testIterationConsistency() { final MultidimensionalCounter c = new MultidimensionalCounter(2, 3, 4); final int[][] expected = new int[][] { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 0, 2 }, { 0, 0, 3 }, { 0, 1, 0 }, { 0, 1, 1 }, { 0, 1, 2 }, { 0, 1, 3 }, { 0, 2, 0 }, { 0, 2, 1 }, { 0, 2, 2 }, { 0, 2, 3 }, { 1, 0, 0 }, { 1, 0, 1 }, { 1, 0, 2 }, { 1, 0, 3 }, { 1, 1, 0 }, { 1, 1, 1 }, { 1, 1, 2 }, { 1, 1, 3 }, { 1, 2, 0 }, { 1, 2, 1 }, { 1, 2, 2 }, { 1, 2, 3 } }; final int totalSize = c.getSize(); final int nDim = c.getDimension(); final MultidimensionalCounter.Iterator iter = c.iterator(); for (int i = 0; i < totalSize; i++) { if (!iter.hasNext()) { Assert.fail("Too short"); } final int uniDimIndex = iter.next(); Assert.assertEquals("Wrong iteration at " + i, i, uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], iter.getCount(dimIndex)); } Assert.assertEquals("Wrong unidimensional index for [" + i + "]", c.getCount(expected[i]), uniDimIndex); final int[] indices = c.getCounts(uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], indices[dimIndex]); } } if (iter.hasNext()) { Assert.fail("Too long"); } }
org.apache.commons.math.util.MultidimensionalCounterTest::testIterationConsistency
src/test/java/org/apache/commons/math/util/MultidimensionalCounterTest.java
179
src/test/java/org/apache/commons/math/util/MultidimensionalCounterTest.java
testIterationConsistency
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.util; import org.apache.commons.math.exception.DimensionMismatchException; import org.apache.commons.math.exception.OutOfRangeException; import org.apache.commons.math.exception.NotStrictlyPositiveException; import org.junit.Assert; import org.junit.Test; /** * */ public class MultidimensionalCounterTest { @Test public void testPreconditions() { MultidimensionalCounter c; try { c = new MultidimensionalCounter(0, 1); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } try { c = new MultidimensionalCounter(2, 0); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } try { c = new MultidimensionalCounter(-1, 1); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } c = new MultidimensionalCounter(2, 3); try { c.getCount(1, 1, 1); Assert.fail("DimensionMismatchException expected"); } catch (DimensionMismatchException e) { // Expected. } try { c.getCount(3, 1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCount(0, -1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCounts(-1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCounts(6); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } } @Test public void testIteratorPreconditions() { MultidimensionalCounter.Iterator iter = (new MultidimensionalCounter(2, 3)).iterator(); try { iter.getCount(-1); Assert.fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { // Expected. } try { iter.getCount(2); Assert.fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { // Expected. } } @Test public void testMulti2UniConversion() { final MultidimensionalCounter c = new MultidimensionalCounter(2, 4, 5); Assert.assertEquals(c.getCount(1, 2, 3), 33); } @Test public void testAccessors() { final int[] originalSize = new int[] {2, 6, 5}; final MultidimensionalCounter c = new MultidimensionalCounter(originalSize); final int nDim = c.getDimension(); Assert.assertEquals(nDim, originalSize.length); final int[] size = c.getSizes(); for (int i = 0; i < nDim; i++) { Assert.assertEquals(originalSize[i], size[i]); } } @Test public void testIterationConsistency() { final MultidimensionalCounter c = new MultidimensionalCounter(2, 3, 4); final int[][] expected = new int[][] { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 0, 2 }, { 0, 0, 3 }, { 0, 1, 0 }, { 0, 1, 1 }, { 0, 1, 2 }, { 0, 1, 3 }, { 0, 2, 0 }, { 0, 2, 1 }, { 0, 2, 2 }, { 0, 2, 3 }, { 1, 0, 0 }, { 1, 0, 1 }, { 1, 0, 2 }, { 1, 0, 3 }, { 1, 1, 0 }, { 1, 1, 1 }, { 1, 1, 2 }, { 1, 1, 3 }, { 1, 2, 0 }, { 1, 2, 1 }, { 1, 2, 2 }, { 1, 2, 3 } }; final int totalSize = c.getSize(); final int nDim = c.getDimension(); final MultidimensionalCounter.Iterator iter = c.iterator(); for (int i = 0; i < totalSize; i++) { if (!iter.hasNext()) { Assert.fail("Too short"); } final int uniDimIndex = iter.next(); Assert.assertEquals("Wrong iteration at " + i, i, uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], iter.getCount(dimIndex)); } Assert.assertEquals("Wrong unidimensional index for [" + i + "]", c.getCount(expected[i]), uniDimIndex); final int[] indices = c.getCounts(uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], indices[dimIndex]); } } if (iter.hasNext()) { Assert.fail("Too long"); } } }
// You are a professional Java test case writer, please create a test case named `testIterationConsistency` for the issue `Math-MATH-552`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-552 // // ## Issue-Title: // MultidimensionalCounter.getCounts(int) returns wrong array of indices // // ## Issue-Description: // // MultidimensionalCounter counter = new MultidimensionalCounter(2, 4); // // for (Integer i : counter) { // // int[] x = counter.getCounts![](/jira/images/icons/emoticons/information.png); // // System.out.println(i + " " + Arrays.toString![](/jira/images/icons/emoticons/error.png)); // // } // // // Output is: // // 0 [0, 0] // // 1 [0, 1] // // 2 [0, 2] // // 3 [0, 2] <=== should be [0, 3] // // 4 [1, 0] // // 5 [1, 1] // // 6 [1, 2] // // 7 [1, 2] <=== should be [1, 3] // // // // // @Test public void testIterationConsistency() {
179
56
121
src/test/java/org/apache/commons/math/util/MultidimensionalCounterTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-552 ## Issue-Title: MultidimensionalCounter.getCounts(int) returns wrong array of indices ## Issue-Description: MultidimensionalCounter counter = new MultidimensionalCounter(2, 4); for (Integer i : counter) { int[] x = counter.getCounts![](/jira/images/icons/emoticons/information.png); System.out.println(i + " " + Arrays.toString![](/jira/images/icons/emoticons/error.png)); } Output is: 0 [0, 0] 1 [0, 1] 2 [0, 2] 3 [0, 2] <=== should be [0, 3] 4 [1, 0] 5 [1, 1] 6 [1, 2] 7 [1, 2] <=== should be [1, 3] ``` You are a professional Java test case writer, please create a test case named `testIterationConsistency` for the issue `Math-MATH-552`, utilizing the provided issue report information and the following function signature. ```java @Test public void testIterationConsistency() { ```
121
[ "org.apache.commons.math.util.MultidimensionalCounter" ]
f22ccea39031ccd64c2f8b3b0130c4f045ba920c7c9b06ccb6735621d91c196f
@Test public void testIterationConsistency()
// You are a professional Java test case writer, please create a test case named `testIterationConsistency` for the issue `Math-MATH-552`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-552 // // ## Issue-Title: // MultidimensionalCounter.getCounts(int) returns wrong array of indices // // ## Issue-Description: // // MultidimensionalCounter counter = new MultidimensionalCounter(2, 4); // // for (Integer i : counter) { // // int[] x = counter.getCounts![](/jira/images/icons/emoticons/information.png); // // System.out.println(i + " " + Arrays.toString![](/jira/images/icons/emoticons/error.png)); // // } // // // Output is: // // 0 [0, 0] // // 1 [0, 1] // // 2 [0, 2] // // 3 [0, 2] <=== should be [0, 3] // // 4 [1, 0] // // 5 [1, 1] // // 6 [1, 2] // // 7 [1, 2] <=== should be [1, 3] // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.util; import org.apache.commons.math.exception.DimensionMismatchException; import org.apache.commons.math.exception.OutOfRangeException; import org.apache.commons.math.exception.NotStrictlyPositiveException; import org.junit.Assert; import org.junit.Test; /** * */ public class MultidimensionalCounterTest { @Test public void testPreconditions() { MultidimensionalCounter c; try { c = new MultidimensionalCounter(0, 1); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } try { c = new MultidimensionalCounter(2, 0); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } try { c = new MultidimensionalCounter(-1, 1); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } c = new MultidimensionalCounter(2, 3); try { c.getCount(1, 1, 1); Assert.fail("DimensionMismatchException expected"); } catch (DimensionMismatchException e) { // Expected. } try { c.getCount(3, 1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCount(0, -1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCounts(-1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCounts(6); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } } @Test public void testIteratorPreconditions() { MultidimensionalCounter.Iterator iter = (new MultidimensionalCounter(2, 3)).iterator(); try { iter.getCount(-1); Assert.fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { // Expected. } try { iter.getCount(2); Assert.fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { // Expected. } } @Test public void testMulti2UniConversion() { final MultidimensionalCounter c = new MultidimensionalCounter(2, 4, 5); Assert.assertEquals(c.getCount(1, 2, 3), 33); } @Test public void testAccessors() { final int[] originalSize = new int[] {2, 6, 5}; final MultidimensionalCounter c = new MultidimensionalCounter(originalSize); final int nDim = c.getDimension(); Assert.assertEquals(nDim, originalSize.length); final int[] size = c.getSizes(); for (int i = 0; i < nDim; i++) { Assert.assertEquals(originalSize[i], size[i]); } } @Test public void testIterationConsistency() { final MultidimensionalCounter c = new MultidimensionalCounter(2, 3, 4); final int[][] expected = new int[][] { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 0, 2 }, { 0, 0, 3 }, { 0, 1, 0 }, { 0, 1, 1 }, { 0, 1, 2 }, { 0, 1, 3 }, { 0, 2, 0 }, { 0, 2, 1 }, { 0, 2, 2 }, { 0, 2, 3 }, { 1, 0, 0 }, { 1, 0, 1 }, { 1, 0, 2 }, { 1, 0, 3 }, { 1, 1, 0 }, { 1, 1, 1 }, { 1, 1, 2 }, { 1, 1, 3 }, { 1, 2, 0 }, { 1, 2, 1 }, { 1, 2, 2 }, { 1, 2, 3 } }; final int totalSize = c.getSize(); final int nDim = c.getDimension(); final MultidimensionalCounter.Iterator iter = c.iterator(); for (int i = 0; i < totalSize; i++) { if (!iter.hasNext()) { Assert.fail("Too short"); } final int uniDimIndex = iter.next(); Assert.assertEquals("Wrong iteration at " + i, i, uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], iter.getCount(dimIndex)); } Assert.assertEquals("Wrong unidimensional index for [" + i + "]", c.getCount(expected[i]), uniDimIndex); final int[] indices = c.getCounts(uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], indices[dimIndex]); } } if (iter.hasNext()) { Assert.fail("Too long"); } } }
@Test public void normalizesDiscordantTags() { Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); assertEquals("<div>\n test\n</div>\n<p></p>", document.html()); // was failing -> toString() = "<div>\n test\n <p></p>\n</div>" }
org.jsoup.parser.XmlTreeBuilderTest::normalizesDiscordantTags
src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java
198
src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java
normalizesDiscordantTags
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.CDataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.nodes.XmlDeclaration; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.List; import static org.jsoup.nodes.Document.OutputSettings.Syntax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests XmlTreeBuilder. * * @author Jonathan Hedley */ public class XmlTreeBuilderTest { @Test public void testSimpleXmlParse() { String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>", TextUtil.stripNewlines(doc.html())); assertEquals(doc.getElementById("2").absUrl("href"), "http://foo.com/bar"); } @Test public void testPopToClose() { // test: </val> closes Two, </bar> ignored String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testCommentAndDocType() { String xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<!DOCTYPE HTML><!-- a comment -->One <qux />Two", TextUtil.stripNewlines(doc.html())); } @Test public void testSupplyParserToJsoupClass() { String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; Document doc = Jsoup.parse(xml, "http://foo.com/", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Ignore @Test public void testSupplyParserToConnection() throws IOException { String xmlUrl = "http://direct.infohound.net/tools/jsoup-xml-test.xml"; // parse with both xml and html parser, ensure different Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get(); Document htmlDoc = Jsoup.connect(xmlUrl).parser(Parser.htmlParser()).get(); Document autoXmlDoc = Jsoup.connect(xmlUrl).get(); // check connection auto detects xml, uses xml parser assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(xmlDoc.html())); assertFalse(htmlDoc.equals(xmlDoc)); assertEquals(xmlDoc, autoXmlDoc); assertEquals(1, htmlDoc.select("head").size()); // html parser normalises assertEquals(0, xmlDoc.select("head").size()); // xml parser does not assertEquals(0, autoXmlDoc.select("head").size()); // xml parser does not } @Test public void testSupplyParserToDataStream() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-test.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://foo.com", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testDoesNotForceSelfClosingKnownTags() { // html will force "<br>one</br>" to logically "<br />One<br />". XML should be stay "<br>one</br> -- don't recognise tag. Document htmlDoc = Jsoup.parse("<br>one</br>"); assertEquals("<br>one\n<br>", htmlDoc.body().html()); Document xmlDoc = Jsoup.parse("<br>one</br>", "", Parser.xmlParser()); assertEquals("<br>one</br>", xmlDoc.html()); } @Test public void handlesXmlDeclarationAsDeclaration() { String html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->"; Document doc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<?xml encoding=\"UTF-8\"?> <body> One </body> <!-- comment -->", StringUtil.normaliseWhitespace(doc.outerHtml())); assertEquals("#declaration", doc.childNode(0).nodeName()); assertEquals("#comment", doc.childNode(2).nodeName()); } @Test public void xmlFragment() { String xml = "<one src='/foo/' />Two<three><four /></three>"; List<Node> nodes = Parser.parseXmlFragment(xml, "http://example.com/"); assertEquals(3, nodes.size()); assertEquals("http://example.com/foo/", nodes.get(0).absUrl("src")); assertEquals("one", nodes.get(0).nodeName()); assertEquals("Two", ((TextNode)nodes.get(1)).text()); } @Test public void xmlParseDefaultsToHtmlOutputSyntax() { Document doc = Jsoup.parse("x", "", Parser.xmlParser()); assertEquals(Syntax.xml, doc.outputSettings().syntax()); } @Test public void testDoesHandleEOFInTag() { String html = "<img src=asdf onerror=\"alert(1)\" x="; Document xmlDoc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.html()); } @Test public void testDetectCharsetEncodingDeclaration() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-charset.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://example.com/", Parser.xmlParser()); assertEquals("ISO-8859-1", doc.charset().name()); assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <data>äöåéü</data>", TextUtil.stripNewlines(doc.html())); } @Test public void testParseDeclarationAttributes() { String xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); XmlDeclaration decl = (XmlDeclaration) doc.childNode(0); assertEquals("1", decl.attr("version")); assertEquals("UTF-8", decl.attr("encoding")); assertEquals("else", decl.attr("something")); assertEquals("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.getWholeDeclaration()); assertEquals("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml()); } @Test public void caseSensitiveDeclaration() { String xml = "<?XML version='1' encoding='UTF-8' something='else'?>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.outerHtml()); } @Test public void testCreatesValidProlog() { Document document = Document.createShell(""); document.outputSettings().syntax(Syntax.xml); document.charset(Charset.forName("utf-8")); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>", document.outerHtml()); } @Test public void preservesCaseByDefault() { String xml = "<TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<TEST ID=\"1\">Check</TEST>", TextUtil.stripNewlines(doc.html())); } @Test public void canNormalizeCase() { String xml = "<TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser().settings(ParseSettings.htmlDefault)); assertEquals("<test id=\"1\">Check</test>", TextUtil.stripNewlines(doc.html())); } @Test public void normalizesDiscordantTags() { Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); assertEquals("<div>\n test\n</div>\n<p></p>", document.html()); // was failing -> toString() = "<div>\n test\n <p></p>\n</div>" } @Test public void roundTripsCdata() { String xml = "<div id=1><![CDATA[\n<html>\n <foo><&amp;]]></div>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&amp;]]>\n</div>", div.outerHtml()); CDataNode cdata = (CDataNode) div.textNodes().get(0); assertEquals("\n<html>\n <foo><&amp;", cdata.text()); } @Test public void cdataPreservesWhiteSpace() { String xml = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals(xml, doc.outerHtml()); assertEquals("//\n\n foo();\n//", doc.selectFirst("script").text()); } }
// You are a professional Java test case writer, please create a test case named `normalizesDiscordantTags` for the issue `Jsoup-998`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-998 // // ## Issue-Title: // xmlParser() with ParseSettings.htmlDefault does not put end tag to lower case // // ## Issue-Description: // // ``` // @Test public void test() { // Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); // Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); // assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // fail -> toString() = "<div>\n test\n <p></p>\n</div>" // } // // @Test public void test1() { // Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); // Document document = Jsoup.parse("<DIV>test</div><p></p>", "", parser); // assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // pass // } // ``` // // // @Test public void normalizesDiscordantTags() {
198
77
193
src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-998 ## Issue-Title: xmlParser() with ParseSettings.htmlDefault does not put end tag to lower case ## Issue-Description: ``` @Test public void test() { Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // fail -> toString() = "<div>\n test\n <p></p>\n</div>" } @Test public void test1() { Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); Document document = Jsoup.parse("<DIV>test</div><p></p>", "", parser); assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // pass } ``` ``` You are a professional Java test case writer, please create a test case named `normalizesDiscordantTags` for the issue `Jsoup-998`, utilizing the provided issue report information and the following function signature. ```java @Test public void normalizesDiscordantTags() { ```
193
[ "org.jsoup.parser.XmlTreeBuilder" ]
f2ec9f3167dd5ddfb7793d7268af786b865a7c7ccf6d79069c43ca1aafbde19e
@Test public void normalizesDiscordantTags()
// You are a professional Java test case writer, please create a test case named `normalizesDiscordantTags` for the issue `Jsoup-998`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-998 // // ## Issue-Title: // xmlParser() with ParseSettings.htmlDefault does not put end tag to lower case // // ## Issue-Description: // // ``` // @Test public void test() { // Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); // Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); // assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // fail -> toString() = "<div>\n test\n <p></p>\n</div>" // } // // @Test public void test1() { // Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); // Document document = Jsoup.parse("<DIV>test</div><p></p>", "", parser); // assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // pass // } // ``` // // //
Jsoup
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.CDataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.nodes.XmlDeclaration; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.List; import static org.jsoup.nodes.Document.OutputSettings.Syntax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests XmlTreeBuilder. * * @author Jonathan Hedley */ public class XmlTreeBuilderTest { @Test public void testSimpleXmlParse() { String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>", TextUtil.stripNewlines(doc.html())); assertEquals(doc.getElementById("2").absUrl("href"), "http://foo.com/bar"); } @Test public void testPopToClose() { // test: </val> closes Two, </bar> ignored String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testCommentAndDocType() { String xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http://foo.com/"); assertEquals("<!DOCTYPE HTML><!-- a comment -->One <qux />Two", TextUtil.stripNewlines(doc.html())); } @Test public void testSupplyParserToJsoupClass() { String xml = "<doc><val>One<val>Two</val></bar>Three</doc>"; Document doc = Jsoup.parse(xml, "http://foo.com/", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Ignore @Test public void testSupplyParserToConnection() throws IOException { String xmlUrl = "http://direct.infohound.net/tools/jsoup-xml-test.xml"; // parse with both xml and html parser, ensure different Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get(); Document htmlDoc = Jsoup.connect(xmlUrl).parser(Parser.htmlParser()).get(); Document autoXmlDoc = Jsoup.connect(xmlUrl).get(); // check connection auto detects xml, uses xml parser assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(xmlDoc.html())); assertFalse(htmlDoc.equals(xmlDoc)); assertEquals(xmlDoc, autoXmlDoc); assertEquals(1, htmlDoc.select("head").size()); // html parser normalises assertEquals(0, xmlDoc.select("head").size()); // xml parser does not assertEquals(0, autoXmlDoc.select("head").size()); // xml parser does not } @Test public void testSupplyParserToDataStream() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-test.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://foo.com", Parser.xmlParser()); assertEquals("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())); } @Test public void testDoesNotForceSelfClosingKnownTags() { // html will force "<br>one</br>" to logically "<br />One<br />". XML should be stay "<br>one</br> -- don't recognise tag. Document htmlDoc = Jsoup.parse("<br>one</br>"); assertEquals("<br>one\n<br>", htmlDoc.body().html()); Document xmlDoc = Jsoup.parse("<br>one</br>", "", Parser.xmlParser()); assertEquals("<br>one</br>", xmlDoc.html()); } @Test public void handlesXmlDeclarationAsDeclaration() { String html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->"; Document doc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<?xml encoding=\"UTF-8\"?> <body> One </body> <!-- comment -->", StringUtil.normaliseWhitespace(doc.outerHtml())); assertEquals("#declaration", doc.childNode(0).nodeName()); assertEquals("#comment", doc.childNode(2).nodeName()); } @Test public void xmlFragment() { String xml = "<one src='/foo/' />Two<three><four /></three>"; List<Node> nodes = Parser.parseXmlFragment(xml, "http://example.com/"); assertEquals(3, nodes.size()); assertEquals("http://example.com/foo/", nodes.get(0).absUrl("src")); assertEquals("one", nodes.get(0).nodeName()); assertEquals("Two", ((TextNode)nodes.get(1)).text()); } @Test public void xmlParseDefaultsToHtmlOutputSyntax() { Document doc = Jsoup.parse("x", "", Parser.xmlParser()); assertEquals(Syntax.xml, doc.outputSettings().syntax()); } @Test public void testDoesHandleEOFInTag() { String html = "<img src=asdf onerror=\"alert(1)\" x="; Document xmlDoc = Jsoup.parse(html, "", Parser.xmlParser()); assertEquals("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.html()); } @Test public void testDetectCharsetEncodingDeclaration() throws IOException, URISyntaxException { File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-charset.xml").toURI()); InputStream inStream = new FileInputStream(xmlFile); Document doc = Jsoup.parse(inStream, null, "http://example.com/", Parser.xmlParser()); assertEquals("ISO-8859-1", doc.charset().name()); assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <data>äöåéü</data>", TextUtil.stripNewlines(doc.html())); } @Test public void testParseDeclarationAttributes() { String xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); XmlDeclaration decl = (XmlDeclaration) doc.childNode(0); assertEquals("1", decl.attr("version")); assertEquals("UTF-8", decl.attr("encoding")); assertEquals("else", decl.attr("something")); assertEquals("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.getWholeDeclaration()); assertEquals("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml()); } @Test public void caseSensitiveDeclaration() { String xml = "<?XML version='1' encoding='UTF-8' something='else'?>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.outerHtml()); } @Test public void testCreatesValidProlog() { Document document = Document.createShell(""); document.outputSettings().syntax(Syntax.xml); document.charset(Charset.forName("utf-8")); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>", document.outerHtml()); } @Test public void preservesCaseByDefault() { String xml = "<TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals("<TEST ID=\"1\">Check</TEST>", TextUtil.stripNewlines(doc.html())); } @Test public void canNormalizeCase() { String xml = "<TEST ID=1>Check</TEST>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser().settings(ParseSettings.htmlDefault)); assertEquals("<test id=\"1\">Check</test>", TextUtil.stripNewlines(doc.html())); } @Test public void normalizesDiscordantTags() { Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault); Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser); assertEquals("<div>\n test\n</div>\n<p></p>", document.html()); // was failing -> toString() = "<div>\n test\n <p></p>\n</div>" } @Test public void roundTripsCdata() { String xml = "<div id=1><![CDATA[\n<html>\n <foo><&amp;]]></div>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&amp;]]>\n</div>", div.outerHtml()); CDataNode cdata = (CDataNode) div.textNodes().get(0); assertEquals("\n<html>\n <foo><&amp;", cdata.text()); } @Test public void cdataPreservesWhiteSpace() { String xml = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>"; Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); assertEquals(xml, doc.outerHtml()); assertEquals("//\n\n foo();\n//", doc.selectFirst("script").text()); } }
@Test public void winzipBackSlashWorkaround() throws Exception { URL zip = getClass().getResource("/test-winzip.zip"); ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(new File(new URI(zip.toString())))); ZipArchiveEntry zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); assertEquals("\u00e4/", zae.getName()); } finally { if (in != null) { in.close(); } } }
org.apache.commons.compress.archivers.zip.ZipArchiveInputStreamTest::winzipBackSlashWorkaround
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
48
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
winzipBackSlashWorkaround
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import java.io.File; import java.io.FileInputStream; import java.net.URI; import java.net.URL; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ZipArchiveInputStreamTest { /** * @see https://issues.apache.org/jira/browse/COMPRESS-176 */ @Test public void winzipBackSlashWorkaround() throws Exception { URL zip = getClass().getResource("/test-winzip.zip"); ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(new File(new URI(zip.toString())))); ZipArchiveEntry zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); assertEquals("\u00e4/", zae.getName()); } finally { if (in != null) { in.close(); } } } }
// You are a professional Java test case writer, please create a test case named `winzipBackSlashWorkaround` for the issue `Compress-COMPRESS-176`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-176 // // ## Issue-Title: // ArchiveInputStream#getNextEntry(): Problems with WinZip directories with Umlauts // // ## Issue-Description: // // There is a problem when handling a WinZip-created zip with Umlauts in directories. // // // I'm accessing a zip file created with WinZip containing a directory with an umlaut ("ä") with ArchiveInputStream. When creating the zip file the unicode-flag of winzip had been active. // // // The following problem occurs when accessing the entries of the zip: // // the ArchiveEntry for a directory containing an umlaut is not marked as a directory and the file names for the directory and all files contained in that directory contain backslashes instead of slashes (i.e. completely different to all other files in directories with no umlaut in their path). // // // There is no difference when letting the ArchiveStreamFactory decide which ArchiveInputStream to create or when using the ZipArchiveInputStream constructor with the correct encoding (I've tried different encodings CP437, CP850, ISO-8859-15, but still the problem persisted). // // // This problem does not occur when using the very same zip file but compressed by 7zip or the built-in Windows 7 zip functionality. // // // // // @Test public void winzipBackSlashWorkaround() throws Exception {
48
/** * @see https://issues.apache.org/jira/browse/COMPRESS-176 */
13
33
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-176 ## Issue-Title: ArchiveInputStream#getNextEntry(): Problems with WinZip directories with Umlauts ## Issue-Description: There is a problem when handling a WinZip-created zip with Umlauts in directories. I'm accessing a zip file created with WinZip containing a directory with an umlaut ("ä") with ArchiveInputStream. When creating the zip file the unicode-flag of winzip had been active. The following problem occurs when accessing the entries of the zip: the ArchiveEntry for a directory containing an umlaut is not marked as a directory and the file names for the directory and all files contained in that directory contain backslashes instead of slashes (i.e. completely different to all other files in directories with no umlaut in their path). There is no difference when letting the ArchiveStreamFactory decide which ArchiveInputStream to create or when using the ZipArchiveInputStream constructor with the correct encoding (I've tried different encodings CP437, CP850, ISO-8859-15, but still the problem persisted). This problem does not occur when using the very same zip file but compressed by 7zip or the built-in Windows 7 zip functionality. ``` You are a professional Java test case writer, please create a test case named `winzipBackSlashWorkaround` for the issue `Compress-COMPRESS-176`, utilizing the provided issue report information and the following function signature. ```java @Test public void winzipBackSlashWorkaround() throws Exception { ```
33
[ "org.apache.commons.compress.archivers.zip.ZipArchiveEntry" ]
f40da3e464d452b2a447654e5ac98053ddfdeac553f8fb23fda89931a23aa883
@Test public void winzipBackSlashWorkaround() throws Exception
// You are a professional Java test case writer, please create a test case named `winzipBackSlashWorkaround` for the issue `Compress-COMPRESS-176`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-176 // // ## Issue-Title: // ArchiveInputStream#getNextEntry(): Problems with WinZip directories with Umlauts // // ## Issue-Description: // // There is a problem when handling a WinZip-created zip with Umlauts in directories. // // // I'm accessing a zip file created with WinZip containing a directory with an umlaut ("ä") with ArchiveInputStream. When creating the zip file the unicode-flag of winzip had been active. // // // The following problem occurs when accessing the entries of the zip: // // the ArchiveEntry for a directory containing an umlaut is not marked as a directory and the file names for the directory and all files contained in that directory contain backslashes instead of slashes (i.e. completely different to all other files in directories with no umlaut in their path). // // // There is no difference when letting the ArchiveStreamFactory decide which ArchiveInputStream to create or when using the ZipArchiveInputStream constructor with the correct encoding (I've tried different encodings CP437, CP850, ISO-8859-15, but still the problem persisted). // // // This problem does not occur when using the very same zip file but compressed by 7zip or the built-in Windows 7 zip functionality. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import java.io.File; import java.io.FileInputStream; import java.net.URI; import java.net.URL; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ZipArchiveInputStreamTest { /** * @see https://issues.apache.org/jira/browse/COMPRESS-176 */ @Test public void winzipBackSlashWorkaround() throws Exception { URL zip = getClass().getResource("/test-winzip.zip"); ZipArchiveInputStream in = null; try { in = new ZipArchiveInputStream(new FileInputStream(new File(new URI(zip.toString())))); ZipArchiveEntry zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); zae = in.getNextZipEntry(); assertEquals("\u00e4/", zae.getName()); } finally { if (in != null) { in.close(); } } } }
@Test public void testLargeSample() { Random randomizer = new Random(0x5551480dca5b369bl); double maxError = 0; for (int degree = 0; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer()); for (int i = 0; i < 40000; ++i) { double x = -1.0 + i / 20000.0; fitter.addObservedPoint(1.0, x, p.value(x) + 0.1 * randomizer.nextGaussian()); } final double[] init = new double[degree + 1]; PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init)); for (double x = -1.0; x < 1.0; x += 0.01) { double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); maxError = FastMath.max(maxError, error); Assert.assertTrue(FastMath.abs(error) < 0.01); } } Assert.assertTrue(maxError > 0.001); }
org.apache.commons.math3.optimization.fitting.PolynomialFitterTest::testLargeSample
src/test/java/org/apache/commons/math3/optimization/fitting/PolynomialFitterTest.java
250
src/test/java/org/apache/commons/math3/optimization/fitting/PolynomialFitterTest.java
testLargeSample
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.commons.math3.optimization.fitting; import java.util.Random; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction.Parametric; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.DifferentiableMultivariateVectorOptimizer; import org.apache.commons.math3.optimization.general.GaussNewtonOptimizer; import org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer; import org.apache.commons.math3.optimization.SimpleVectorValueChecker; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.TestUtils; import org.junit.Test; import org.junit.Assert; /** * Test for class {@link CurveFitter} where the function to fit is a * polynomial. */ public class PolynomialFitterTest { @Test public void testFit() { final RealDistribution rng = new UniformRealDistribution(-100, 100); rng.reseedRandomGenerator(64925784252L); final LevenbergMarquardtOptimizer optim = new LevenbergMarquardtOptimizer(); final PolynomialFitter fitter = new PolynomialFitter(optim); final double[] coeff = { 12.9, -3.4, 2.1 }; // 12.9 - 3.4 x + 2.1 x^2 final PolynomialFunction f = new PolynomialFunction(coeff); // Collect data from a known polynomial. for (int i = 0; i < 100; i++) { final double x = rng.sample(); fitter.addObservedPoint(x, f.value(x)); } // Start fit from initial guesses that are far from the optimal values. final double[] best = fitter.fit(new double[] { -1e-20, 3e15, -5e25 }); TestUtils.assertEquals("best != coeff", coeff, best, 1e-12); } @Test public void testNoError() { Random randomizer = new Random(64925784252l); for (int degree = 1; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer()); for (int i = 0; i <= degree; ++i) { fitter.addObservedPoint(1.0, i, p.value(i)); } final double[] init = new double[degree + 1]; PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init)); for (double x = -1.0; x < 1.0; x += 0.01) { double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); Assert.assertEquals(0.0, error, 1.0e-6); } } } @Test public void testSmallError() { Random randomizer = new Random(53882150042l); double maxError = 0; for (int degree = 0; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer()); for (double x = -1.0; x < 1.0; x += 0.01) { fitter.addObservedPoint(1.0, x, p.value(x) + 0.1 * randomizer.nextGaussian()); } final double[] init = new double[degree + 1]; PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init)); for (double x = -1.0; x < 1.0; x += 0.01) { double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); maxError = FastMath.max(maxError, error); Assert.assertTrue(FastMath.abs(error) < 0.1); } } Assert.assertTrue(maxError > 0.01); } @Test public void testMath798() { final double tol = 1e-14; final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol); final double[] init = new double[] { 0, 0 }; final int maxEval = 3; final double[] lm = doMath798(new LevenbergMarquardtOptimizer(checker), maxEval, init); final double[] gn = doMath798(new GaussNewtonOptimizer(checker), maxEval, init); for (int i = 0; i <= 1; i++) { Assert.assertEquals(lm[i], gn[i], tol); } } /** * This test shows that the user can set the maximum number of iterations * to avoid running for too long. * But in the test case, the real problem is that the tolerance is way too * stringent. */ @Test(expected=TooManyEvaluationsException.class) public void testMath798WithToleranceTooLow() { final double tol = 1e-100; final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol); final double[] init = new double[] { 0, 0 }; final int maxEval = 10000; // Trying hard to fit. final double[] gn = doMath798(new GaussNewtonOptimizer(checker), maxEval, init); } /** * This test shows that the user can set the maximum number of iterations * to avoid running for too long. * Even if the real problem is that the tolerance is way too stringent, it * is possible to get the best solution so far, i.e. a checker will return * the point when the maximum iteration count has been reached. */ @Test public void testMath798WithToleranceTooLowButNoException() { final double tol = 1e-100; final double[] init = new double[] { 0, 0 }; final int maxEval = 10000; // Trying hard to fit. final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol, maxEval); final double[] lm = doMath798(new LevenbergMarquardtOptimizer(checker), maxEval, init); final double[] gn = doMath798(new GaussNewtonOptimizer(checker), maxEval, init); for (int i = 0; i <= 1; i++) { Assert.assertEquals(lm[i], gn[i], 1e-15); } } /** * @param optimizer Optimizer. * @param maxEval Maximum number of function evaluations. * @param init First guess. * @return the solution found by the given optimizer. */ private double[] doMath798(DifferentiableMultivariateVectorOptimizer optimizer, int maxEval, double[] init) { final CurveFitter<Parametric> fitter = new CurveFitter<Parametric>(optimizer); fitter.addObservedPoint(-0.2, -7.12442E-13); fitter.addObservedPoint(-0.199, -4.33397E-13); fitter.addObservedPoint(-0.198, -2.823E-13); fitter.addObservedPoint(-0.197, -1.40405E-13); fitter.addObservedPoint(-0.196, -7.80821E-15); fitter.addObservedPoint(-0.195, 6.20484E-14); fitter.addObservedPoint(-0.194, 7.24673E-14); fitter.addObservedPoint(-0.193, 1.47152E-13); fitter.addObservedPoint(-0.192, 1.9629E-13); fitter.addObservedPoint(-0.191, 2.12038E-13); fitter.addObservedPoint(-0.19, 2.46906E-13); fitter.addObservedPoint(-0.189, 2.77495E-13); fitter.addObservedPoint(-0.188, 2.51281E-13); fitter.addObservedPoint(-0.187, 2.64001E-13); fitter.addObservedPoint(-0.186, 2.8882E-13); fitter.addObservedPoint(-0.185, 3.13604E-13); fitter.addObservedPoint(-0.184, 3.14248E-13); fitter.addObservedPoint(-0.183, 3.1172E-13); fitter.addObservedPoint(-0.182, 3.12912E-13); fitter.addObservedPoint(-0.181, 3.06761E-13); fitter.addObservedPoint(-0.18, 2.8559E-13); fitter.addObservedPoint(-0.179, 2.86806E-13); fitter.addObservedPoint(-0.178, 2.985E-13); fitter.addObservedPoint(-0.177, 2.67148E-13); fitter.addObservedPoint(-0.176, 2.94173E-13); fitter.addObservedPoint(-0.175, 3.27528E-13); fitter.addObservedPoint(-0.174, 3.33858E-13); fitter.addObservedPoint(-0.173, 2.97511E-13); fitter.addObservedPoint(-0.172, 2.8615E-13); fitter.addObservedPoint(-0.171, 2.84624E-13); final double[] coeff = fitter.fit(maxEval, new PolynomialFunction.Parametric(), init); return coeff; } @Test public void testRedundantSolvable() { // Levenberg-Marquardt should handle redundant information gracefully checkUnsolvableProblem(new LevenbergMarquardtOptimizer(), true); } @Test public void testRedundantUnsolvable() { // Gauss-Newton should not be able to solve redundant information checkUnsolvableProblem(new GaussNewtonOptimizer(true, new SimpleVectorValueChecker(1e-15, 1e-15)), false); } @Test public void testLargeSample() { Random randomizer = new Random(0x5551480dca5b369bl); double maxError = 0; for (int degree = 0; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer()); for (int i = 0; i < 40000; ++i) { double x = -1.0 + i / 20000.0; fitter.addObservedPoint(1.0, x, p.value(x) + 0.1 * randomizer.nextGaussian()); } final double[] init = new double[degree + 1]; PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init)); for (double x = -1.0; x < 1.0; x += 0.01) { double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); maxError = FastMath.max(maxError, error); Assert.assertTrue(FastMath.abs(error) < 0.01); } } Assert.assertTrue(maxError > 0.001); } private void checkUnsolvableProblem(DifferentiableMultivariateVectorOptimizer optimizer, boolean solvable) { Random randomizer = new Random(1248788532l); for (int degree = 0; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(optimizer); // reusing the same point over and over again does not bring // information, the problem cannot be solved in this case for // degrees greater than 1 (but one point is sufficient for // degree 0) for (double x = -1.0; x < 1.0; x += 0.01) { fitter.addObservedPoint(1.0, 0.0, p.value(0.0)); } try { final double[] init = new double[degree + 1]; fitter.fit(init); Assert.assertTrue(solvable || (degree == 0)); } catch(ConvergenceException e) { Assert.assertTrue((! solvable) && (degree > 0)); } } } private PolynomialFunction buildRandomPolynomial(int degree, Random randomizer) { final double[] coefficients = new double[degree + 1]; for (int i = 0; i <= degree; ++i) { coefficients[i] = randomizer.nextGaussian(); } return new PolynomialFunction(coefficients); } }
// You are a professional Java test case writer, please create a test case named `testLargeSample` for the issue `Math-MATH-924`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-924 // // ## Issue-Title: // new multivariate vector optimizers cannot be used with large number of weights // // ## Issue-Description: // // When using the Weigth class to pass a large number of weights to multivariate vector optimizers, an nxn full matrix is created (and copied) when a n elements vector is used. This exhausts memory when n is large. // // // This happens for example when using curve fitters (even simple curve fitters like polynomial ones for low degree) with large number of points. I encountered this with curve fitting on 41200 points, which created a matrix with 1.7 billion elements. // // // // // @Test public void testLargeSample() {
250
13
225
src/test/java/org/apache/commons/math3/optimization/fitting/PolynomialFitterTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-924 ## Issue-Title: new multivariate vector optimizers cannot be used with large number of weights ## Issue-Description: When using the Weigth class to pass a large number of weights to multivariate vector optimizers, an nxn full matrix is created (and copied) when a n elements vector is used. This exhausts memory when n is large. This happens for example when using curve fitters (even simple curve fitters like polynomial ones for low degree) with large number of points. I encountered this with curve fitting on 41200 points, which created a matrix with 1.7 billion elements. ``` You are a professional Java test case writer, please create a test case named `testLargeSample` for the issue `Math-MATH-924`, utilizing the provided issue report information and the following function signature. ```java @Test public void testLargeSample() { ```
225
[ "org.apache.commons.math3.optimization.general.AbstractLeastSquaresOptimizer" ]
f47710dced977e97163c19c4849ad7352941f6009076e325da61e3a76ffdecf7
@Test public void testLargeSample()
// You are a professional Java test case writer, please create a test case named `testLargeSample` for the issue `Math-MATH-924`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-924 // // ## Issue-Title: // new multivariate vector optimizers cannot be used with large number of weights // // ## Issue-Description: // // When using the Weigth class to pass a large number of weights to multivariate vector optimizers, an nxn full matrix is created (and copied) when a n elements vector is used. This exhausts memory when n is large. // // // This happens for example when using curve fitters (even simple curve fitters like polynomial ones for low degree) with large number of points. I encountered this with curve fitting on 41200 points, which created a matrix with 1.7 billion elements. // // // // //
Math
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.commons.math3.optimization.fitting; import java.util.Random; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction.Parametric; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.DifferentiableMultivariateVectorOptimizer; import org.apache.commons.math3.optimization.general.GaussNewtonOptimizer; import org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer; import org.apache.commons.math3.optimization.SimpleVectorValueChecker; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.TestUtils; import org.junit.Test; import org.junit.Assert; /** * Test for class {@link CurveFitter} where the function to fit is a * polynomial. */ public class PolynomialFitterTest { @Test public void testFit() { final RealDistribution rng = new UniformRealDistribution(-100, 100); rng.reseedRandomGenerator(64925784252L); final LevenbergMarquardtOptimizer optim = new LevenbergMarquardtOptimizer(); final PolynomialFitter fitter = new PolynomialFitter(optim); final double[] coeff = { 12.9, -3.4, 2.1 }; // 12.9 - 3.4 x + 2.1 x^2 final PolynomialFunction f = new PolynomialFunction(coeff); // Collect data from a known polynomial. for (int i = 0; i < 100; i++) { final double x = rng.sample(); fitter.addObservedPoint(x, f.value(x)); } // Start fit from initial guesses that are far from the optimal values. final double[] best = fitter.fit(new double[] { -1e-20, 3e15, -5e25 }); TestUtils.assertEquals("best != coeff", coeff, best, 1e-12); } @Test public void testNoError() { Random randomizer = new Random(64925784252l); for (int degree = 1; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer()); for (int i = 0; i <= degree; ++i) { fitter.addObservedPoint(1.0, i, p.value(i)); } final double[] init = new double[degree + 1]; PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init)); for (double x = -1.0; x < 1.0; x += 0.01) { double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); Assert.assertEquals(0.0, error, 1.0e-6); } } } @Test public void testSmallError() { Random randomizer = new Random(53882150042l); double maxError = 0; for (int degree = 0; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer()); for (double x = -1.0; x < 1.0; x += 0.01) { fitter.addObservedPoint(1.0, x, p.value(x) + 0.1 * randomizer.nextGaussian()); } final double[] init = new double[degree + 1]; PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init)); for (double x = -1.0; x < 1.0; x += 0.01) { double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); maxError = FastMath.max(maxError, error); Assert.assertTrue(FastMath.abs(error) < 0.1); } } Assert.assertTrue(maxError > 0.01); } @Test public void testMath798() { final double tol = 1e-14; final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol); final double[] init = new double[] { 0, 0 }; final int maxEval = 3; final double[] lm = doMath798(new LevenbergMarquardtOptimizer(checker), maxEval, init); final double[] gn = doMath798(new GaussNewtonOptimizer(checker), maxEval, init); for (int i = 0; i <= 1; i++) { Assert.assertEquals(lm[i], gn[i], tol); } } /** * This test shows that the user can set the maximum number of iterations * to avoid running for too long. * But in the test case, the real problem is that the tolerance is way too * stringent. */ @Test(expected=TooManyEvaluationsException.class) public void testMath798WithToleranceTooLow() { final double tol = 1e-100; final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol); final double[] init = new double[] { 0, 0 }; final int maxEval = 10000; // Trying hard to fit. final double[] gn = doMath798(new GaussNewtonOptimizer(checker), maxEval, init); } /** * This test shows that the user can set the maximum number of iterations * to avoid running for too long. * Even if the real problem is that the tolerance is way too stringent, it * is possible to get the best solution so far, i.e. a checker will return * the point when the maximum iteration count has been reached. */ @Test public void testMath798WithToleranceTooLowButNoException() { final double tol = 1e-100; final double[] init = new double[] { 0, 0 }; final int maxEval = 10000; // Trying hard to fit. final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol, maxEval); final double[] lm = doMath798(new LevenbergMarquardtOptimizer(checker), maxEval, init); final double[] gn = doMath798(new GaussNewtonOptimizer(checker), maxEval, init); for (int i = 0; i <= 1; i++) { Assert.assertEquals(lm[i], gn[i], 1e-15); } } /** * @param optimizer Optimizer. * @param maxEval Maximum number of function evaluations. * @param init First guess. * @return the solution found by the given optimizer. */ private double[] doMath798(DifferentiableMultivariateVectorOptimizer optimizer, int maxEval, double[] init) { final CurveFitter<Parametric> fitter = new CurveFitter<Parametric>(optimizer); fitter.addObservedPoint(-0.2, -7.12442E-13); fitter.addObservedPoint(-0.199, -4.33397E-13); fitter.addObservedPoint(-0.198, -2.823E-13); fitter.addObservedPoint(-0.197, -1.40405E-13); fitter.addObservedPoint(-0.196, -7.80821E-15); fitter.addObservedPoint(-0.195, 6.20484E-14); fitter.addObservedPoint(-0.194, 7.24673E-14); fitter.addObservedPoint(-0.193, 1.47152E-13); fitter.addObservedPoint(-0.192, 1.9629E-13); fitter.addObservedPoint(-0.191, 2.12038E-13); fitter.addObservedPoint(-0.19, 2.46906E-13); fitter.addObservedPoint(-0.189, 2.77495E-13); fitter.addObservedPoint(-0.188, 2.51281E-13); fitter.addObservedPoint(-0.187, 2.64001E-13); fitter.addObservedPoint(-0.186, 2.8882E-13); fitter.addObservedPoint(-0.185, 3.13604E-13); fitter.addObservedPoint(-0.184, 3.14248E-13); fitter.addObservedPoint(-0.183, 3.1172E-13); fitter.addObservedPoint(-0.182, 3.12912E-13); fitter.addObservedPoint(-0.181, 3.06761E-13); fitter.addObservedPoint(-0.18, 2.8559E-13); fitter.addObservedPoint(-0.179, 2.86806E-13); fitter.addObservedPoint(-0.178, 2.985E-13); fitter.addObservedPoint(-0.177, 2.67148E-13); fitter.addObservedPoint(-0.176, 2.94173E-13); fitter.addObservedPoint(-0.175, 3.27528E-13); fitter.addObservedPoint(-0.174, 3.33858E-13); fitter.addObservedPoint(-0.173, 2.97511E-13); fitter.addObservedPoint(-0.172, 2.8615E-13); fitter.addObservedPoint(-0.171, 2.84624E-13); final double[] coeff = fitter.fit(maxEval, new PolynomialFunction.Parametric(), init); return coeff; } @Test public void testRedundantSolvable() { // Levenberg-Marquardt should handle redundant information gracefully checkUnsolvableProblem(new LevenbergMarquardtOptimizer(), true); } @Test public void testRedundantUnsolvable() { // Gauss-Newton should not be able to solve redundant information checkUnsolvableProblem(new GaussNewtonOptimizer(true, new SimpleVectorValueChecker(1e-15, 1e-15)), false); } @Test public void testLargeSample() { Random randomizer = new Random(0x5551480dca5b369bl); double maxError = 0; for (int degree = 0; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer()); for (int i = 0; i < 40000; ++i) { double x = -1.0 + i / 20000.0; fitter.addObservedPoint(1.0, x, p.value(x) + 0.1 * randomizer.nextGaussian()); } final double[] init = new double[degree + 1]; PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init)); for (double x = -1.0; x < 1.0; x += 0.01) { double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); maxError = FastMath.max(maxError, error); Assert.assertTrue(FastMath.abs(error) < 0.01); } } Assert.assertTrue(maxError > 0.001); } private void checkUnsolvableProblem(DifferentiableMultivariateVectorOptimizer optimizer, boolean solvable) { Random randomizer = new Random(1248788532l); for (int degree = 0; degree < 10; ++degree) { PolynomialFunction p = buildRandomPolynomial(degree, randomizer); PolynomialFitter fitter = new PolynomialFitter(optimizer); // reusing the same point over and over again does not bring // information, the problem cannot be solved in this case for // degrees greater than 1 (but one point is sufficient for // degree 0) for (double x = -1.0; x < 1.0; x += 0.01) { fitter.addObservedPoint(1.0, 0.0, p.value(0.0)); } try { final double[] init = new double[degree + 1]; fitter.fit(init); Assert.assertTrue(solvable || (degree == 0)); } catch(ConvergenceException e) { Assert.assertTrue((! solvable) && (degree > 0)); } } } private PolynomialFunction buildRandomPolynomial(int degree, Random randomizer) { final double[] coefficients = new double[degree + 1]; for (int i = 0; i <= degree; ++i) { coefficients[i] = randomizer.nextGaussian(); } return new PolynomialFunction(coefficients); } }
@Test public void testGettersSetters() { // X5455 is concerned with time, so let's // get a timestamp to play with (Jan 1st, 2000). final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.YEAR, 2000); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); final long timeMillis = cal.getTimeInMillis(); final ZipLong time = new ZipLong(timeMillis / 1000); // set too big try { // Java time is 1000 x larger (milliseconds). xf.setModifyJavaTime(new Date(1000L * (MAX_TIME_SECONDS.getValue() + 1L))); fail("Time too big for 32 bits!"); } catch (final IllegalArgumentException iae) { // All is good. } // get/set modify time xf.setModifyTime(time); assertEquals(time, xf.getModifyTime()); Date xfModifyJavaTime = xf.getModifyJavaTime(); assertEquals(timeMillis, xfModifyJavaTime.getTime()); xf.setModifyJavaTime(new Date(timeMillis)); assertEquals(time, xf.getModifyTime()); assertEquals(timeMillis, xf.getModifyJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setModifyJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getModifyTime()); assertEquals(timeMillis, xf.getModifyJavaTime().getTime()); // Null xf.setModifyTime(null); assertNull(xf.getModifyJavaTime()); xf.setModifyJavaTime(null); assertNull(xf.getModifyTime()); // get/set access time xf.setAccessTime(time); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); xf.setAccessJavaTime(new Date(timeMillis)); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setAccessJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); // Null xf.setAccessTime(null); assertNull(xf.getAccessJavaTime()); xf.setAccessJavaTime(null); assertNull(xf.getAccessTime()); // get/set create time xf.setCreateTime(time); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); xf.setCreateJavaTime(new Date(timeMillis)); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setCreateJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); // Null xf.setCreateTime(null); assertNull(xf.getCreateJavaTime()); xf.setCreateJavaTime(null); assertNull(xf.getCreateTime()); // initialize for flags xf.setModifyTime(time); xf.setAccessTime(time); xf.setCreateTime(time); // get/set flags: 000 xf.setFlags((byte) 0); assertEquals(0, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=1, Central length=1 (flags only!) assertEquals(1, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 001 xf.setFlags((byte) 1); assertEquals(1, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=5, Central length=5 (flags + mod) assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); // get/set flags: 010 xf.setFlags((byte) 2); assertEquals(2, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=5, Central length=1 assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 100 xf.setFlags((byte) 4); assertEquals(4, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=5, Central length=1 assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 111 xf.setFlags((byte) 7); assertEquals(7, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=13, Central length=5 assertEquals(13, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); // get/set flags: 11111111 xf.setFlags((byte) -1); assertEquals(-1, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=13, Central length=5 assertEquals(13, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); }
org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestampTest::testGettersSetters
src/test/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestampTest.java
339
src/test/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestampTest.java
testGettersSetters
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.TimeZone; import java.util.zip.ZipException; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.apache.commons.compress.AbstractTestCase.mkdir; import static org.apache.commons.compress.AbstractTestCase.rmdir; import static org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp.ACCESS_TIME_BIT; import static org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp.CREATE_TIME_BIT; import static org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp.MODIFY_TIME_BIT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class X5455_ExtendedTimestampTest { private final static ZipShort X5455 = new ZipShort(0x5455); private final static ZipLong ZERO_TIME = new ZipLong(0); private final static ZipLong MAX_TIME_SECONDS = new ZipLong(Integer.MAX_VALUE); private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss Z"); static { DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * The extended field (xf) we are testing. */ private X5455_ExtendedTimestamp xf; private File tmpDir; @Before public void before() { xf = new X5455_ExtendedTimestamp(); } @After public void removeTempFiles() { if (tmpDir != null) { rmdir(tmpDir); } } @Test public void testSampleFile() {} // Defects4J: flaky method // @Test // public void testSampleFile() throws Exception { // // /* // Contains entries with zipTime, accessTime, and modifyTime. // The file name tells you the year we tried to set the time to // (Jan 1st, Midnight, UTC). // // For example: // // COMPRESS-210_unix_time_zip_test/1999 // COMPRESS-210_unix_time_zip_test/2000 // COMPRESS-210_unix_time_zip_test/2108 // // File's last-modified is 1st second after midnight. // Zip-time's 2-second granularity rounds that up to 2nd second. // File's last-access is 3rd second after midnight. // // So, from example above: // // 1999's zip time: Jan 1st, 1999-01-01/00:00:02 // 1999's mod time: Jan 1st, 1999-01-01/00:00:01 // 1999's acc time: Jan 1st, 1999-01-01/00:00:03 // // Starting with a patch release of Java8, "zip time" actually // uses the extended time stamp field itself and should be the // same as "mod time". // http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/rev/90df6756406f // */ // // final File archive = getFile("COMPRESS-210_unix_time_zip_test.zip"); // ZipFile zf = null; // // try { // zf = new ZipFile(archive); // final Enumeration<ZipArchiveEntry> en = zf.getEntries(); // // // We expect EVERY entry of this zip file // // to contain extra field 0x5455. // while (en.hasMoreElements()) { // // final ZipArchiveEntry zae = en.nextElement(); // final String name = zae.getName(); // final X5455_ExtendedTimestamp xf = (X5455_ExtendedTimestamp) zae.getExtraField(X5455); // final Date rawZ = zae.getLastModifiedDate(); // final Date m = xf.getModifyJavaTime(); // final boolean zipTimeUsesExtendedTimestamp = rawZ.equals(m); // final Date z = zipTimeUsesExtendedTimestamp ? rawZ : adjustFromGMTToExpectedOffset(rawZ); // final Date a = xf.getAccessJavaTime(); // // final String zipTime = DATE_FORMAT.format(z); // final String modTime = DATE_FORMAT.format(m); // final String accTime = DATE_FORMAT.format(a); // // if (!zae.isDirectory()) { // final int x = name.lastIndexOf('/'); // final String yearString = name.substring(x + 1); // int year; // try { // year = Integer.parseInt(yearString); // } catch (final NumberFormatException nfe) { // year = -1; // } // if (year >= 0) { // switch (year) { // default: // if (!zipTimeUsesExtendedTimestamp) { // // X5455 time is good from epoch (1970) to 2037. // // Zip time is good from 1980 to 2107. // if (year < 1980) { // assertEquals("1980-01-01/08:00:00 +0000", zipTime); // } else { // assertEquals(year + "-01-01/00:00:02 +0000", zipTime); // } // }if(year <2038) { // assertEquals(year + "-01-01/00:00:01 +0000", modTime); // assertEquals(year + "-01-01/00:00:03 +0000", accTime); // } // break; // } // } // } // } // } finally { // if (zf != null) { // zf.close(); // } // } // } @Test public void testMisc() throws Exception { assertFalse(xf.equals(new Object())); assertTrue(xf.toString().startsWith("0x5455 Zip Extra Field")); assertTrue(!xf.toString().contains(" Modify:")); assertTrue(!xf.toString().contains(" Access:")); assertTrue(!xf.toString().contains(" Create:")); Object o = xf.clone(); assertEquals(o.hashCode(), xf.hashCode()); assertTrue(xf.equals(o)); xf.setModifyJavaTime(new Date(1111)); xf.setAccessJavaTime(new Date(2222)); xf.setCreateJavaTime(new Date(3333)); xf.setFlags((byte) 7); assertFalse(xf.equals(o)); assertTrue(xf.toString().startsWith("0x5455 Zip Extra Field")); assertTrue(xf.toString().contains(" Modify:")); assertTrue(xf.toString().contains(" Access:")); assertTrue(xf.toString().contains(" Create:")); o = xf.clone(); assertEquals(o.hashCode(), xf.hashCode()); assertTrue(xf.equals(o)); } @Test public void testGettersSetters() { // X5455 is concerned with time, so let's // get a timestamp to play with (Jan 1st, 2000). final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.YEAR, 2000); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); final long timeMillis = cal.getTimeInMillis(); final ZipLong time = new ZipLong(timeMillis / 1000); // set too big try { // Java time is 1000 x larger (milliseconds). xf.setModifyJavaTime(new Date(1000L * (MAX_TIME_SECONDS.getValue() + 1L))); fail("Time too big for 32 bits!"); } catch (final IllegalArgumentException iae) { // All is good. } // get/set modify time xf.setModifyTime(time); assertEquals(time, xf.getModifyTime()); Date xfModifyJavaTime = xf.getModifyJavaTime(); assertEquals(timeMillis, xfModifyJavaTime.getTime()); xf.setModifyJavaTime(new Date(timeMillis)); assertEquals(time, xf.getModifyTime()); assertEquals(timeMillis, xf.getModifyJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setModifyJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getModifyTime()); assertEquals(timeMillis, xf.getModifyJavaTime().getTime()); // Null xf.setModifyTime(null); assertNull(xf.getModifyJavaTime()); xf.setModifyJavaTime(null); assertNull(xf.getModifyTime()); // get/set access time xf.setAccessTime(time); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); xf.setAccessJavaTime(new Date(timeMillis)); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setAccessJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); // Null xf.setAccessTime(null); assertNull(xf.getAccessJavaTime()); xf.setAccessJavaTime(null); assertNull(xf.getAccessTime()); // get/set create time xf.setCreateTime(time); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); xf.setCreateJavaTime(new Date(timeMillis)); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setCreateJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); // Null xf.setCreateTime(null); assertNull(xf.getCreateJavaTime()); xf.setCreateJavaTime(null); assertNull(xf.getCreateTime()); // initialize for flags xf.setModifyTime(time); xf.setAccessTime(time); xf.setCreateTime(time); // get/set flags: 000 xf.setFlags((byte) 0); assertEquals(0, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=1, Central length=1 (flags only!) assertEquals(1, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 001 xf.setFlags((byte) 1); assertEquals(1, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=5, Central length=5 (flags + mod) assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); // get/set flags: 010 xf.setFlags((byte) 2); assertEquals(2, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=5, Central length=1 assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 100 xf.setFlags((byte) 4); assertEquals(4, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=5, Central length=1 assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 111 xf.setFlags((byte) 7); assertEquals(7, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=13, Central length=5 assertEquals(13, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); // get/set flags: 11111111 xf.setFlags((byte) -1); assertEquals(-1, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=13, Central length=5 assertEquals(13, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); } @Test public void testGetHeaderId() { assertEquals(X5455, xf.getHeaderId()); } @Test public void testParseReparse() throws ZipException { /* * Recall the spec: * * 0x5455 Short tag for this extra block type ("UT") * TSize Short total data size for this block * Flags Byte info bits * (ModTime) Long time of last modification (UTC/GMT) * (AcTime) Long time of last access (UTC/GMT) * (CrTime) Long time of original creation (UTC/GMT) */ final byte[] NULL_FLAGS = {0}; final byte[] AC_CENTRAL = {2}; // central data only contains the AC flag and no actual data final byte[] CR_CENTRAL = {4}; // central data only dontains the CR flag and no actual data final byte[] MOD_ZERO = {1, 0, 0, 0, 0}; final byte[] MOD_MAX = {1, -1, -1, -1, 0x7f}; final byte[] AC_ZERO = {2, 0, 0, 0, 0}; final byte[] AC_MAX = {2, -1, -1, -1, 0x7f}; final byte[] CR_ZERO = {4, 0, 0, 0, 0}; final byte[] CR_MAX = {4, -1, -1, -1, 0x7f}; final byte[] MOD_AC_ZERO = {3, 0, 0, 0, 0, 0, 0, 0, 0}; final byte[] MOD_AC_MAX = {3, -1, -1, -1, 0x7f, -1, -1, -1, 0x7f}; final byte[] MOD_AC_CR_ZERO = {7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; final byte[] MOD_AC_CR_MAX = {7, -1, -1, -1, 0x7f, -1, -1, -1, 0x7f, -1, -1, -1, 0x7f}; parseReparse(null, NULL_FLAGS, NULL_FLAGS); parseReparse(ZERO_TIME, MOD_ZERO, MOD_ZERO); parseReparse(MAX_TIME_SECONDS, MOD_MAX, MOD_MAX); parseReparse(ZERO_TIME, AC_ZERO, AC_CENTRAL); parseReparse(MAX_TIME_SECONDS, AC_MAX, AC_CENTRAL); parseReparse(ZERO_TIME, CR_ZERO, CR_CENTRAL); parseReparse(MAX_TIME_SECONDS, CR_MAX, CR_CENTRAL); parseReparse(ZERO_TIME, MOD_AC_ZERO, MOD_ZERO); parseReparse(MAX_TIME_SECONDS, MOD_AC_MAX, MOD_MAX); parseReparse(ZERO_TIME, MOD_AC_CR_ZERO, MOD_ZERO); parseReparse(MAX_TIME_SECONDS, MOD_AC_CR_MAX, MOD_MAX); // As far as the spec is concerned (December 2012) all of these flags // are spurious versions of 7 (a.k.a. binary 00000111). parseReparse((byte) 15, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 31, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 63, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 71, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 127, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) -1, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); } @Test public void testWriteReadRoundtrip() throws IOException { tmpDir = mkdir("X5455"); final File output = new File(tmpDir, "write_rewrite.zip"); final OutputStream out = new FileOutputStream(output); final Date d = new Date(97, 8, 24, 15, 10, 2); ZipArchiveOutputStream os = null; try { os = new ZipArchiveOutputStream(out); final ZipArchiveEntry ze = new ZipArchiveEntry("foo"); xf.setModifyJavaTime(d); xf.setFlags((byte) 1); ze.addExtraField(xf); os.putArchiveEntry(ze); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out.close(); final ZipFile zf = new ZipFile(output); final ZipArchiveEntry ze = zf.getEntry("foo"); final X5455_ExtendedTimestamp ext = (X5455_ExtendedTimestamp) ze.getExtraField(X5455); assertNotNull(ext); assertTrue(ext.isBit0_modifyTimePresent()); assertEquals(d, ext.getModifyJavaTime()); zf.close(); } @Test public void testBitsAreSetWithTime() { xf.setModifyJavaTime(new Date(1111)); assertTrue(xf.isBit0_modifyTimePresent()); assertEquals(1, xf.getFlags()); xf.setAccessJavaTime(new Date(2222)); assertTrue(xf.isBit1_accessTimePresent()); assertEquals(3, xf.getFlags()); xf.setCreateJavaTime(new Date(3333)); assertTrue(xf.isBit2_createTimePresent()); assertEquals(7, xf.getFlags()); xf.setModifyJavaTime(null); assertFalse(xf.isBit0_modifyTimePresent()); assertEquals(6, xf.getFlags()); xf.setAccessJavaTime(null); assertFalse(xf.isBit1_accessTimePresent()); assertEquals(4, xf.getFlags()); xf.setCreateJavaTime(null); assertFalse(xf.isBit2_createTimePresent()); assertEquals(0, xf.getFlags()); } private void parseReparse( final ZipLong time, final byte[] expectedLocal, final byte[] almostExpectedCentral ) throws ZipException { parseReparse(expectedLocal[0], time, expectedLocal[0], expectedLocal, almostExpectedCentral); } private void parseReparse( final byte providedFlags, final ZipLong time, final byte expectedFlags, final byte[] expectedLocal, final byte[] almostExpectedCentral ) throws ZipException { // We're responsible for expectedCentral's flags. Too annoying to set in caller. final byte[] expectedCentral = new byte[almostExpectedCentral.length]; System.arraycopy(almostExpectedCentral, 0, expectedCentral, 0, almostExpectedCentral.length); expectedCentral[0] = expectedFlags; xf.setModifyTime(time); xf.setAccessTime(time); xf.setCreateTime(time); xf.setFlags(providedFlags); byte[] result = xf.getLocalFileDataData(); assertTrue(Arrays.equals(expectedLocal, result)); // And now we re-parse: xf.parseFromLocalFileData(result, 0, result.length); assertEquals(expectedFlags, xf.getFlags()); if (isFlagSet(expectedFlags, MODIFY_TIME_BIT)) { assertTrue(xf.isBit0_modifyTimePresent()); assertEquals(time, xf.getModifyTime()); } if (isFlagSet(expectedFlags, ACCESS_TIME_BIT)) { assertTrue(xf.isBit1_accessTimePresent()); assertEquals(time, xf.getAccessTime()); } if (isFlagSet(expectedFlags, CREATE_TIME_BIT)) { assertTrue(xf.isBit2_createTimePresent()); assertEquals(time, xf.getCreateTime()); } // Do the same as above, but with Central Directory data: xf.setModifyTime(time); xf.setAccessTime(time); xf.setCreateTime(time); xf.setFlags(providedFlags); result = xf.getCentralDirectoryData(); assertTrue(Arrays.equals(expectedCentral, result)); // And now we re-parse: xf.parseFromCentralDirectoryData(result, 0, result.length); assertEquals(expectedFlags, xf.getFlags()); // Central Directory never contains ACCESS or CREATE, but // may contain MODIFY. if (isFlagSet(expectedFlags, MODIFY_TIME_BIT)) { assertTrue(xf.isBit0_modifyTimePresent()); assertEquals(time, xf.getModifyTime()); } } private static boolean isFlagSet(final byte data, final byte flag) { return (data & flag) == flag; } /** * InfoZIP seems to adjust the time stored inside the LFH and CD * to GMT when writing ZIPs while java.util.zip.ZipEntry thinks it * was in local time. * * The archive read in {@link #testSampleFile} has been created * with GMT-8 so we need to adjust for the difference. */ private static Date adjustFromGMTToExpectedOffset(final Date from) { final Calendar cal = Calendar.getInstance(); cal.setTime(from); cal.add(Calendar.MILLISECOND, cal.get(Calendar.ZONE_OFFSET)); if (cal.getTimeZone().inDaylightTime(from)) { cal.add(Calendar.MILLISECOND, cal.get(Calendar.DST_OFFSET)); } cal.add(Calendar.HOUR, 8); return cal.getTime(); } }
// You are a professional Java test case writer, please create a test case named `testGettersSetters` for the issue `Compress-COMPRESS-416`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-416 // // ## Issue-Title: // Tests failing under jdk 9 : one reflection issue, one change to ZipEntry related issue // // ## Issue-Description: // // X5455\_ExtendedTimestampTest is failing under JDK 9 , due to what appears to be a bogus value returned from getTime(). It seems like the test failure might be due to the changes introduced for this: // // <https://bugs.openjdk.java.net/browse/JDK-8073497> // // // Tests were run using intelliJ TestRunner, using the openjdk9 build from the tip of the jdk9 tree (not dev). I believe that this is at most one commit away from what will be the RC (which was delayed at the last minute due to two issues, one of which was javadoc related, and the other hotspot. // // // // // @Test public void testGettersSetters() {
339
46
198
src/test/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestampTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-416 ## Issue-Title: Tests failing under jdk 9 : one reflection issue, one change to ZipEntry related issue ## Issue-Description: X5455\_ExtendedTimestampTest is failing under JDK 9 , due to what appears to be a bogus value returned from getTime(). It seems like the test failure might be due to the changes introduced for this: <https://bugs.openjdk.java.net/browse/JDK-8073497> Tests were run using intelliJ TestRunner, using the openjdk9 build from the tip of the jdk9 tree (not dev). I believe that this is at most one commit away from what will be the RC (which was delayed at the last minute due to two issues, one of which was javadoc related, and the other hotspot. ``` You are a professional Java test case writer, please create a test case named `testGettersSetters` for the issue `Compress-COMPRESS-416`, utilizing the provided issue report information and the following function signature. ```java @Test public void testGettersSetters() { ```
198
[ "org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp" ]
f51c4f841f4e522795f38c8046f8617f348bf16f24a5b07683ee2d525499bb5b
@Test public void testGettersSetters()
// You are a professional Java test case writer, please create a test case named `testGettersSetters` for the issue `Compress-COMPRESS-416`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-416 // // ## Issue-Title: // Tests failing under jdk 9 : one reflection issue, one change to ZipEntry related issue // // ## Issue-Description: // // X5455\_ExtendedTimestampTest is failing under JDK 9 , due to what appears to be a bogus value returned from getTime(). It seems like the test failure might be due to the changes introduced for this: // // <https://bugs.openjdk.java.net/browse/JDK-8073497> // // // Tests were run using intelliJ TestRunner, using the openjdk9 build from the tip of the jdk9 tree (not dev). I believe that this is at most one commit away from what will be the RC (which was delayed at the last minute due to two issues, one of which was javadoc related, and the other hotspot. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.zip; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.TimeZone; import java.util.zip.ZipException; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.apache.commons.compress.AbstractTestCase.mkdir; import static org.apache.commons.compress.AbstractTestCase.rmdir; import static org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp.ACCESS_TIME_BIT; import static org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp.CREATE_TIME_BIT; import static org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp.MODIFY_TIME_BIT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class X5455_ExtendedTimestampTest { private final static ZipShort X5455 = new ZipShort(0x5455); private final static ZipLong ZERO_TIME = new ZipLong(0); private final static ZipLong MAX_TIME_SECONDS = new ZipLong(Integer.MAX_VALUE); private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss Z"); static { DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * The extended field (xf) we are testing. */ private X5455_ExtendedTimestamp xf; private File tmpDir; @Before public void before() { xf = new X5455_ExtendedTimestamp(); } @After public void removeTempFiles() { if (tmpDir != null) { rmdir(tmpDir); } } @Test public void testSampleFile() {} // Defects4J: flaky method // @Test // public void testSampleFile() throws Exception { // // /* // Contains entries with zipTime, accessTime, and modifyTime. // The file name tells you the year we tried to set the time to // (Jan 1st, Midnight, UTC). // // For example: // // COMPRESS-210_unix_time_zip_test/1999 // COMPRESS-210_unix_time_zip_test/2000 // COMPRESS-210_unix_time_zip_test/2108 // // File's last-modified is 1st second after midnight. // Zip-time's 2-second granularity rounds that up to 2nd second. // File's last-access is 3rd second after midnight. // // So, from example above: // // 1999's zip time: Jan 1st, 1999-01-01/00:00:02 // 1999's mod time: Jan 1st, 1999-01-01/00:00:01 // 1999's acc time: Jan 1st, 1999-01-01/00:00:03 // // Starting with a patch release of Java8, "zip time" actually // uses the extended time stamp field itself and should be the // same as "mod time". // http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/rev/90df6756406f // */ // // final File archive = getFile("COMPRESS-210_unix_time_zip_test.zip"); // ZipFile zf = null; // // try { // zf = new ZipFile(archive); // final Enumeration<ZipArchiveEntry> en = zf.getEntries(); // // // We expect EVERY entry of this zip file // // to contain extra field 0x5455. // while (en.hasMoreElements()) { // // final ZipArchiveEntry zae = en.nextElement(); // final String name = zae.getName(); // final X5455_ExtendedTimestamp xf = (X5455_ExtendedTimestamp) zae.getExtraField(X5455); // final Date rawZ = zae.getLastModifiedDate(); // final Date m = xf.getModifyJavaTime(); // final boolean zipTimeUsesExtendedTimestamp = rawZ.equals(m); // final Date z = zipTimeUsesExtendedTimestamp ? rawZ : adjustFromGMTToExpectedOffset(rawZ); // final Date a = xf.getAccessJavaTime(); // // final String zipTime = DATE_FORMAT.format(z); // final String modTime = DATE_FORMAT.format(m); // final String accTime = DATE_FORMAT.format(a); // // if (!zae.isDirectory()) { // final int x = name.lastIndexOf('/'); // final String yearString = name.substring(x + 1); // int year; // try { // year = Integer.parseInt(yearString); // } catch (final NumberFormatException nfe) { // year = -1; // } // if (year >= 0) { // switch (year) { // default: // if (!zipTimeUsesExtendedTimestamp) { // // X5455 time is good from epoch (1970) to 2037. // // Zip time is good from 1980 to 2107. // if (year < 1980) { // assertEquals("1980-01-01/08:00:00 +0000", zipTime); // } else { // assertEquals(year + "-01-01/00:00:02 +0000", zipTime); // } // }if(year <2038) { // assertEquals(year + "-01-01/00:00:01 +0000", modTime); // assertEquals(year + "-01-01/00:00:03 +0000", accTime); // } // break; // } // } // } // } // } finally { // if (zf != null) { // zf.close(); // } // } // } @Test public void testMisc() throws Exception { assertFalse(xf.equals(new Object())); assertTrue(xf.toString().startsWith("0x5455 Zip Extra Field")); assertTrue(!xf.toString().contains(" Modify:")); assertTrue(!xf.toString().contains(" Access:")); assertTrue(!xf.toString().contains(" Create:")); Object o = xf.clone(); assertEquals(o.hashCode(), xf.hashCode()); assertTrue(xf.equals(o)); xf.setModifyJavaTime(new Date(1111)); xf.setAccessJavaTime(new Date(2222)); xf.setCreateJavaTime(new Date(3333)); xf.setFlags((byte) 7); assertFalse(xf.equals(o)); assertTrue(xf.toString().startsWith("0x5455 Zip Extra Field")); assertTrue(xf.toString().contains(" Modify:")); assertTrue(xf.toString().contains(" Access:")); assertTrue(xf.toString().contains(" Create:")); o = xf.clone(); assertEquals(o.hashCode(), xf.hashCode()); assertTrue(xf.equals(o)); } @Test public void testGettersSetters() { // X5455 is concerned with time, so let's // get a timestamp to play with (Jan 1st, 2000). final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.YEAR, 2000); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); final long timeMillis = cal.getTimeInMillis(); final ZipLong time = new ZipLong(timeMillis / 1000); // set too big try { // Java time is 1000 x larger (milliseconds). xf.setModifyJavaTime(new Date(1000L * (MAX_TIME_SECONDS.getValue() + 1L))); fail("Time too big for 32 bits!"); } catch (final IllegalArgumentException iae) { // All is good. } // get/set modify time xf.setModifyTime(time); assertEquals(time, xf.getModifyTime()); Date xfModifyJavaTime = xf.getModifyJavaTime(); assertEquals(timeMillis, xfModifyJavaTime.getTime()); xf.setModifyJavaTime(new Date(timeMillis)); assertEquals(time, xf.getModifyTime()); assertEquals(timeMillis, xf.getModifyJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setModifyJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getModifyTime()); assertEquals(timeMillis, xf.getModifyJavaTime().getTime()); // Null xf.setModifyTime(null); assertNull(xf.getModifyJavaTime()); xf.setModifyJavaTime(null); assertNull(xf.getModifyTime()); // get/set access time xf.setAccessTime(time); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); xf.setAccessJavaTime(new Date(timeMillis)); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setAccessJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getAccessTime()); assertEquals(timeMillis, xf.getAccessJavaTime().getTime()); // Null xf.setAccessTime(null); assertNull(xf.getAccessJavaTime()); xf.setAccessJavaTime(null); assertNull(xf.getAccessTime()); // get/set create time xf.setCreateTime(time); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); xf.setCreateJavaTime(new Date(timeMillis)); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); // Make sure milliseconds get zeroed out: xf.setCreateJavaTime(new Date(timeMillis + 123)); assertEquals(time, xf.getCreateTime()); assertEquals(timeMillis, xf.getCreateJavaTime().getTime()); // Null xf.setCreateTime(null); assertNull(xf.getCreateJavaTime()); xf.setCreateJavaTime(null); assertNull(xf.getCreateTime()); // initialize for flags xf.setModifyTime(time); xf.setAccessTime(time); xf.setCreateTime(time); // get/set flags: 000 xf.setFlags((byte) 0); assertEquals(0, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=1, Central length=1 (flags only!) assertEquals(1, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 001 xf.setFlags((byte) 1); assertEquals(1, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=5, Central length=5 (flags + mod) assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); // get/set flags: 010 xf.setFlags((byte) 2); assertEquals(2, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertFalse(xf.isBit2_createTimePresent()); // Local length=5, Central length=1 assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 100 xf.setFlags((byte) 4); assertEquals(4, xf.getFlags()); assertFalse(xf.isBit0_modifyTimePresent()); assertFalse(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=5, Central length=1 assertEquals(5, xf.getLocalFileDataLength().getValue()); assertEquals(1, xf.getCentralDirectoryLength().getValue()); // get/set flags: 111 xf.setFlags((byte) 7); assertEquals(7, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=13, Central length=5 assertEquals(13, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); // get/set flags: 11111111 xf.setFlags((byte) -1); assertEquals(-1, xf.getFlags()); assertTrue(xf.isBit0_modifyTimePresent()); assertTrue(xf.isBit1_accessTimePresent()); assertTrue(xf.isBit2_createTimePresent()); // Local length=13, Central length=5 assertEquals(13, xf.getLocalFileDataLength().getValue()); assertEquals(5, xf.getCentralDirectoryLength().getValue()); } @Test public void testGetHeaderId() { assertEquals(X5455, xf.getHeaderId()); } @Test public void testParseReparse() throws ZipException { /* * Recall the spec: * * 0x5455 Short tag for this extra block type ("UT") * TSize Short total data size for this block * Flags Byte info bits * (ModTime) Long time of last modification (UTC/GMT) * (AcTime) Long time of last access (UTC/GMT) * (CrTime) Long time of original creation (UTC/GMT) */ final byte[] NULL_FLAGS = {0}; final byte[] AC_CENTRAL = {2}; // central data only contains the AC flag and no actual data final byte[] CR_CENTRAL = {4}; // central data only dontains the CR flag and no actual data final byte[] MOD_ZERO = {1, 0, 0, 0, 0}; final byte[] MOD_MAX = {1, -1, -1, -1, 0x7f}; final byte[] AC_ZERO = {2, 0, 0, 0, 0}; final byte[] AC_MAX = {2, -1, -1, -1, 0x7f}; final byte[] CR_ZERO = {4, 0, 0, 0, 0}; final byte[] CR_MAX = {4, -1, -1, -1, 0x7f}; final byte[] MOD_AC_ZERO = {3, 0, 0, 0, 0, 0, 0, 0, 0}; final byte[] MOD_AC_MAX = {3, -1, -1, -1, 0x7f, -1, -1, -1, 0x7f}; final byte[] MOD_AC_CR_ZERO = {7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; final byte[] MOD_AC_CR_MAX = {7, -1, -1, -1, 0x7f, -1, -1, -1, 0x7f, -1, -1, -1, 0x7f}; parseReparse(null, NULL_FLAGS, NULL_FLAGS); parseReparse(ZERO_TIME, MOD_ZERO, MOD_ZERO); parseReparse(MAX_TIME_SECONDS, MOD_MAX, MOD_MAX); parseReparse(ZERO_TIME, AC_ZERO, AC_CENTRAL); parseReparse(MAX_TIME_SECONDS, AC_MAX, AC_CENTRAL); parseReparse(ZERO_TIME, CR_ZERO, CR_CENTRAL); parseReparse(MAX_TIME_SECONDS, CR_MAX, CR_CENTRAL); parseReparse(ZERO_TIME, MOD_AC_ZERO, MOD_ZERO); parseReparse(MAX_TIME_SECONDS, MOD_AC_MAX, MOD_MAX); parseReparse(ZERO_TIME, MOD_AC_CR_ZERO, MOD_ZERO); parseReparse(MAX_TIME_SECONDS, MOD_AC_CR_MAX, MOD_MAX); // As far as the spec is concerned (December 2012) all of these flags // are spurious versions of 7 (a.k.a. binary 00000111). parseReparse((byte) 15, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 31, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 63, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 71, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) 127, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); parseReparse((byte) -1, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX); } @Test public void testWriteReadRoundtrip() throws IOException { tmpDir = mkdir("X5455"); final File output = new File(tmpDir, "write_rewrite.zip"); final OutputStream out = new FileOutputStream(output); final Date d = new Date(97, 8, 24, 15, 10, 2); ZipArchiveOutputStream os = null; try { os = new ZipArchiveOutputStream(out); final ZipArchiveEntry ze = new ZipArchiveEntry("foo"); xf.setModifyJavaTime(d); xf.setFlags((byte) 1); ze.addExtraField(xf); os.putArchiveEntry(ze); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out.close(); final ZipFile zf = new ZipFile(output); final ZipArchiveEntry ze = zf.getEntry("foo"); final X5455_ExtendedTimestamp ext = (X5455_ExtendedTimestamp) ze.getExtraField(X5455); assertNotNull(ext); assertTrue(ext.isBit0_modifyTimePresent()); assertEquals(d, ext.getModifyJavaTime()); zf.close(); } @Test public void testBitsAreSetWithTime() { xf.setModifyJavaTime(new Date(1111)); assertTrue(xf.isBit0_modifyTimePresent()); assertEquals(1, xf.getFlags()); xf.setAccessJavaTime(new Date(2222)); assertTrue(xf.isBit1_accessTimePresent()); assertEquals(3, xf.getFlags()); xf.setCreateJavaTime(new Date(3333)); assertTrue(xf.isBit2_createTimePresent()); assertEquals(7, xf.getFlags()); xf.setModifyJavaTime(null); assertFalse(xf.isBit0_modifyTimePresent()); assertEquals(6, xf.getFlags()); xf.setAccessJavaTime(null); assertFalse(xf.isBit1_accessTimePresent()); assertEquals(4, xf.getFlags()); xf.setCreateJavaTime(null); assertFalse(xf.isBit2_createTimePresent()); assertEquals(0, xf.getFlags()); } private void parseReparse( final ZipLong time, final byte[] expectedLocal, final byte[] almostExpectedCentral ) throws ZipException { parseReparse(expectedLocal[0], time, expectedLocal[0], expectedLocal, almostExpectedCentral); } private void parseReparse( final byte providedFlags, final ZipLong time, final byte expectedFlags, final byte[] expectedLocal, final byte[] almostExpectedCentral ) throws ZipException { // We're responsible for expectedCentral's flags. Too annoying to set in caller. final byte[] expectedCentral = new byte[almostExpectedCentral.length]; System.arraycopy(almostExpectedCentral, 0, expectedCentral, 0, almostExpectedCentral.length); expectedCentral[0] = expectedFlags; xf.setModifyTime(time); xf.setAccessTime(time); xf.setCreateTime(time); xf.setFlags(providedFlags); byte[] result = xf.getLocalFileDataData(); assertTrue(Arrays.equals(expectedLocal, result)); // And now we re-parse: xf.parseFromLocalFileData(result, 0, result.length); assertEquals(expectedFlags, xf.getFlags()); if (isFlagSet(expectedFlags, MODIFY_TIME_BIT)) { assertTrue(xf.isBit0_modifyTimePresent()); assertEquals(time, xf.getModifyTime()); } if (isFlagSet(expectedFlags, ACCESS_TIME_BIT)) { assertTrue(xf.isBit1_accessTimePresent()); assertEquals(time, xf.getAccessTime()); } if (isFlagSet(expectedFlags, CREATE_TIME_BIT)) { assertTrue(xf.isBit2_createTimePresent()); assertEquals(time, xf.getCreateTime()); } // Do the same as above, but with Central Directory data: xf.setModifyTime(time); xf.setAccessTime(time); xf.setCreateTime(time); xf.setFlags(providedFlags); result = xf.getCentralDirectoryData(); assertTrue(Arrays.equals(expectedCentral, result)); // And now we re-parse: xf.parseFromCentralDirectoryData(result, 0, result.length); assertEquals(expectedFlags, xf.getFlags()); // Central Directory never contains ACCESS or CREATE, but // may contain MODIFY. if (isFlagSet(expectedFlags, MODIFY_TIME_BIT)) { assertTrue(xf.isBit0_modifyTimePresent()); assertEquals(time, xf.getModifyTime()); } } private static boolean isFlagSet(final byte data, final byte flag) { return (data & flag) == flag; } /** * InfoZIP seems to adjust the time stored inside the LFH and CD * to GMT when writing ZIPs while java.util.zip.ZipEntry thinks it * was in local time. * * The archive read in {@link #testSampleFile} has been created * with GMT-8 so we need to adjust for the difference. */ private static Date adjustFromGMTToExpectedOffset(final Date from) { final Calendar cal = Calendar.getInstance(); cal.setTime(from); cal.add(Calendar.MILLISECOND, cal.get(Calendar.ZONE_OFFSET)); if (cal.getTimeZone().inDaylightTime(from)) { cal.add(Calendar.MILLISECOND, cal.get(Calendar.DST_OFFSET)); } cal.add(Calendar.HOUR, 8); return cal.getTime(); } }
public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {}; goog.dom = {};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); }
com.google.javascript.jscomp.CommandLineRunnerTest::testProcessClosurePrimitives
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
158
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
testProcessClosurePrimitives
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import org.kohsuke.args4j.CmdLineException; import java.io.IOException; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author nicksantos@google.com (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final JSSourceFile[] externs = new JSSourceFile[] { JSSourceFile.fromCode("externs", "var arguments;" + "/** @constructor \n * @param {...*} var_args \n " + "* @return {!Array} */ " + "function Array(var_args) {}\n" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") }; @Override public void setUp() throws Exception { super.setUp(); lastCompiler = null; useStringComparison = false; args.clear(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeCheckOverride1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=checkTypes"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); } public void testTypeCheckOverride2() { args.add("--warning_level=DEFAULT"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); args.add("--jscomp_warning=checkTypes"); test("var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testCheckSymbolsOffForDefault() { args.add("--warning_level=DEFAULT"); test("x = 3; var y; var y;", "x=3; var y;"); } public void testCheckSymbolsOnForVerbose() { args.add("--warning_level=VERBOSE"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckUndefinedProperties() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function (a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM); assertTrue(lastCompiler.hasHaltingErrors()); } public void testDefineFlag() { args.add("--define=FOO"); args.add("--define=\"BAR=5\""); args.add("--D"); args.add("CCC"); args.add("-D"); args.add("DDD"); test("/** @define {boolean} */ var FOO = false;" + "/** @define {number} */ var BAR = 3;" + "/** @define {boolean} */ var CCC = false;" + "/** @define {boolean} */ var DDD = false;", "var FOO = true, BAR = 5, CCC = true, DDD = true;"); } public void testScriptStrictModeNoWarning() { test("'use strict';", ""); test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR); } public void testFunctionStrictModeNoWarning() { test("function f() {'use strict';}", "function f() {}"); test("function f() {'no use strict';}", CheckSideEffects.USELESS_CODE_ERROR); } public void testQuietMode() { args.add("--warning_level=DEFAULT"); test("/** @type { not a type name } */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @type { not a type name } */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {}; goog.dom = {};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue81() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); useStringComparison = true; test("eval('1'); var x = eval; x('2');", "eval(\"1\");(0,eval)(\"2\");"); } public void testIssue115() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--warning_level=VERBOSE"); test("function f() { " + " var arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}", "function f() { " + " arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); testSame("function foo(a) {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {}", "function foo($a$$) {}"); } public void testDebugFlag3() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=false"); test("function Foo() {};" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "function a() {};" + "throw new a().a;"); } public void testDebugFlag4() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=true"); test("function Foo() {};" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "function $Foo$$() {};" + "throw new $Foo$$().$x$;"); } /* Helper functions */ private void testSame(String original) { testSame(new String[] { original }); } private void testSame(String[] original) { test(original, original); } private void test(String original, String compiled) { test(new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(String[] original, String[] compiled) { Compiler compiler = compile(original); assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertEquals(Joiner.on("").join(compiled), compiler.toSource()); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling, there is an error or warning. */ private void test(String original, DiagnosticType warning) { test(new String[] { original }, warning); } /** * Asserts that when compiling, there is an error or warning. */ private void test(String[] original, DiagnosticType warning) { Compiler compiler = compile(original); assertEquals("Expected exactly one warning or error " + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 1, compiler.getErrors().length + compiler.getWarnings().length); if (compiler.getErrors().length > 0) { assertEquals(warning, compiler.getErrors()[0].getType()); } else { assertEquals(warning, compiler.getWarnings()[0].getType()); } } private Compiler compile(String original) { return compile( new String[] { original }); } private Compiler compile(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = null; try { runner = new CommandLineRunner(argStrings); } catch (CmdLineException e) { throw new RuntimeException(e); } Compiler compiler = runner.createCompiler(); lastCompiler = compiler; JSSourceFile[] inputs = new JSSourceFile[original.length]; for (int i = 0; i < original.length; i++) { inputs[i] = JSSourceFile.fromCode("input" + i, original[i]); } CompilerOptions options = runner.createOptions(); try { runner.setRunOptions(options); } catch (AbstractCommandLineRunner.FlagUsageException e) { fail("Unexpected exception " + e); } catch (IOException e) { assert(false); } compiler.compile( externs, CompilerTestCase.createModuleChain(original), options); return compiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = null; try { runner = new CommandLineRunner(argStrings); } catch (CmdLineException e) { throw new RuntimeException(e); } Compiler compiler = runner.createCompiler(); JSSourceFile[] inputs = new JSSourceFile[original.length]; for (int i = 0; i < inputs.length; i++) { inputs[i] = JSSourceFile.fromCode("input" + i, original[i]); } compiler.init(externs, inputs, new CompilerOptions()); Node all = compiler.parseInputs(); Node n = all.getLastChild(); return n; } }
// You are a professional Java test case writer, please create a test case named `testProcessClosurePrimitives` for the issue `Closure-130`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-130 // // ## Issue-Title: // --process_closure_primitives can't be set to false // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. compile a file with "--process\_closure\_primitives false" // 2. compile a file with "--process\_closure\_primitives true" (default) // 3. result: primitives are processed in both cases. // // **What is the expected output? What do you see instead?** // The file should still have its goog.provide/require tags in place. // Instead they are processed. // // **What version of the product are you using? On what operating system?** // current SVN (also tried two of the preceding binary releases with same // result) // // **Please provide any additional information below.** // Flag can't be set to false due to a missing "else" in the command-line // parser. // // public void testProcessClosurePrimitives() {
158
101
153
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
test
```markdown ## Issue-ID: Closure-130 ## Issue-Title: --process_closure_primitives can't be set to false ## Issue-Description: **What steps will reproduce the problem?** 1. compile a file with "--process\_closure\_primitives false" 2. compile a file with "--process\_closure\_primitives true" (default) 3. result: primitives are processed in both cases. **What is the expected output? What do you see instead?** The file should still have its goog.provide/require tags in place. Instead they are processed. **What version of the product are you using? On what operating system?** current SVN (also tried two of the preceding binary releases with same result) **Please provide any additional information below.** Flag can't be set to false due to a missing "else" in the command-line parser. ``` You are a professional Java test case writer, please create a test case named `testProcessClosurePrimitives` for the issue `Closure-130`, utilizing the provided issue report information and the following function signature. ```java public void testProcessClosurePrimitives() { ```
153
[ "com.google.javascript.jscomp.CommandLineRunner" ]
f547896e58c6bf89d52c37239ceaa07662fb2ad6aa6cf698b3ac8312e598ef2f
public void testProcessClosurePrimitives()
// You are a professional Java test case writer, please create a test case named `testProcessClosurePrimitives` for the issue `Closure-130`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-130 // // ## Issue-Title: // --process_closure_primitives can't be set to false // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. compile a file with "--process\_closure\_primitives false" // 2. compile a file with "--process\_closure\_primitives true" (default) // 3. result: primitives are processed in both cases. // // **What is the expected output? What do you see instead?** // The file should still have its goog.provide/require tags in place. // Instead they are processed. // // **What version of the product are you using? On what operating system?** // current SVN (also tried two of the preceding binary releases with same // result) // // **Please provide any additional information below.** // Flag can't be set to false due to a missing "else" in the command-line // parser. // //
Closure
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import org.kohsuke.args4j.CmdLineException; import java.io.IOException; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author nicksantos@google.com (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final JSSourceFile[] externs = new JSSourceFile[] { JSSourceFile.fromCode("externs", "var arguments;" + "/** @constructor \n * @param {...*} var_args \n " + "* @return {!Array} */ " + "function Array(var_args) {}\n" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") }; @Override public void setUp() throws Exception { super.setUp(); lastCompiler = null; useStringComparison = false; args.clear(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeCheckOverride1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=checkTypes"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); } public void testTypeCheckOverride2() { args.add("--warning_level=DEFAULT"); testSame("var x = x || {}; x.f = function() {}; x.f(3);"); args.add("--jscomp_warning=checkTypes"); test("var x = x || {}; x.f = function() {}; x.f(3);", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testCheckSymbolsOffForDefault() { args.add("--warning_level=DEFAULT"); test("x = 3; var y; var y;", "x=3; var y;"); } public void testCheckSymbolsOnForVerbose() { args.add("--warning_level=VERBOSE"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); test("var y; var y;", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckUndefinedProperties() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function (a, a) {}", RhinoErrorReporter.DUPLICATE_PARAM); assertTrue(lastCompiler.hasHaltingErrors()); } public void testDefineFlag() { args.add("--define=FOO"); args.add("--define=\"BAR=5\""); args.add("--D"); args.add("CCC"); args.add("-D"); args.add("DDD"); test("/** @define {boolean} */ var FOO = false;" + "/** @define {number} */ var BAR = 3;" + "/** @define {boolean} */ var CCC = false;" + "/** @define {boolean} */ var DDD = false;", "var FOO = true, BAR = 5, CCC = true, DDD = true;"); } public void testScriptStrictModeNoWarning() { test("'use strict';", ""); test("'no use strict';", CheckSideEffects.USELESS_CODE_ERROR); } public void testFunctionStrictModeNoWarning() { test("function f() {'use strict';}", "function f() {}"); test("function f() {'no use strict';}", CheckSideEffects.USELESS_CODE_ERROR); } public void testQuietMode() { args.add("--warning_level=DEFAULT"); test("/** @type { not a type name } */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @type { not a type name } */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {}; goog.dom = {};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue81() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); useStringComparison = true; test("eval('1'); var x = eval; x('2');", "eval(\"1\");(0,eval)(\"2\");"); } public void testIssue115() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--warning_level=VERBOSE"); test("function f() { " + " var arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}", "function f() { " + " arguments = Array.prototype.slice.call(arguments, 0);" + " return arguments[0]; " + "}"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); testSame("function foo(a) {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {}", "function foo($a$$) {}"); } public void testDebugFlag3() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=false"); test("function Foo() {};" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "function a() {};" + "throw new a().a;"); } public void testDebugFlag4() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--warning_level=QUIET"); args.add("--debug=true"); test("function Foo() {};" + "Foo.x = 1;" + "function f() {throw new Foo().x;} f();", "function $Foo$$() {};" + "throw new $Foo$$().$x$;"); } /* Helper functions */ private void testSame(String original) { testSame(new String[] { original }); } private void testSame(String[] original) { test(original, original); } private void test(String original, String compiled) { test(new String[] { original }, new String[] { compiled }); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. */ private void test(String[] original, String[] compiled) { Compiler compiler = compile(original); assertEquals("Expected no warnings or errors\n" + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 0, compiler.getErrors().length + compiler.getWarnings().length); Node root = compiler.getRoot().getLastChild(); if (useStringComparison) { assertEquals(Joiner.on("").join(compiled), compiler.toSource()); } else { Node expectedRoot = parse(compiled); String explanation = expectedRoot.checkTreeEquals(root); assertNull("\nExpected: " + compiler.toSource(expectedRoot) + "\nResult: " + compiler.toSource(root) + "\n" + explanation, explanation); } } /** * Asserts that when compiling, there is an error or warning. */ private void test(String original, DiagnosticType warning) { test(new String[] { original }, warning); } /** * Asserts that when compiling, there is an error or warning. */ private void test(String[] original, DiagnosticType warning) { Compiler compiler = compile(original); assertEquals("Expected exactly one warning or error " + "Errors: \n" + Joiner.on("\n").join(compiler.getErrors()) + "Warnings: \n" + Joiner.on("\n").join(compiler.getWarnings()), 1, compiler.getErrors().length + compiler.getWarnings().length); if (compiler.getErrors().length > 0) { assertEquals(warning, compiler.getErrors()[0].getType()); } else { assertEquals(warning, compiler.getWarnings()[0].getType()); } } private Compiler compile(String original) { return compile( new String[] { original }); } private Compiler compile(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = null; try { runner = new CommandLineRunner(argStrings); } catch (CmdLineException e) { throw new RuntimeException(e); } Compiler compiler = runner.createCompiler(); lastCompiler = compiler; JSSourceFile[] inputs = new JSSourceFile[original.length]; for (int i = 0; i < original.length; i++) { inputs[i] = JSSourceFile.fromCode("input" + i, original[i]); } CompilerOptions options = runner.createOptions(); try { runner.setRunOptions(options); } catch (AbstractCommandLineRunner.FlagUsageException e) { fail("Unexpected exception " + e); } catch (IOException e) { assert(false); } compiler.compile( externs, CompilerTestCase.createModuleChain(original), options); return compiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = null; try { runner = new CommandLineRunner(argStrings); } catch (CmdLineException e) { throw new RuntimeException(e); } Compiler compiler = runner.createCompiler(); JSSourceFile[] inputs = new JSSourceFile[original.length]; for (int i = 0; i < inputs.length; i++) { inputs[i] = JSSourceFile.fromCode("input" + i, original[i]); } compiler.init(externs, inputs, new CompilerOptions()); Node all = compiler.parseInputs(); Node n = all.getLastChild(); return n; } }
@Test public void shortTextFilesAreNoTARs() throws Exception { try { new ArchiveStreamFactory() .createArchiveInputStream(new ByteArrayInputStream("This certainly is not a tar archive, really, no kidding".getBytes())); fail("created an input stream for a non-archive"); } catch (ArchiveException ae) { assertTrue(ae.getMessage().startsWith("No Archiver found")); } }
org.apache.commons.compress.archivers.ArchiveStreamFactoryTest::shortTextFilesAreNoTARs
src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java
39
src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java
shortTextFilesAreNoTARs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.archivers; import java.io.ByteArrayInputStream; import org.junit.Test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ArchiveStreamFactoryTest { /** * see https://issues.apache.org/jira/browse/COMPRESS-171 */ @Test public void shortTextFilesAreNoTARs() throws Exception { try { new ArchiveStreamFactory() .createArchiveInputStream(new ByteArrayInputStream("This certainly is not a tar archive, really, no kidding".getBytes())); fail("created an input stream for a non-archive"); } catch (ArchiveException ae) { assertTrue(ae.getMessage().startsWith("No Archiver found")); } } }
// You are a professional Java test case writer, please create a test case named `shortTextFilesAreNoTARs` for the issue `Compress-COMPRESS-171`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-171 // // ## Issue-Title: // createArchiveInputStream detects text files less than 100 bytes as tar archives // // ## Issue-Description: // // The fix for [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") which modified ArchiveStreamFactory().createArchiveInputStream(inputstream) results in short text files (empirically seems to be those <= 100 bytes) being detected as tar archives which obviously is not desirable if one wants to know whether or not the files are archives. // // I'm not an expert on compressed archives but perhaps the heuristic that if a stream is interpretable as a tar file without an exception being thrown should only be applied on archives greater than 100 bytes? // // // // // @Test public void shortTextFilesAreNoTARs() throws Exception {
39
/** * see https://issues.apache.org/jira/browse/COMPRESS-171 */
11
30
src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-171 ## Issue-Title: createArchiveInputStream detects text files less than 100 bytes as tar archives ## Issue-Description: The fix for [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") which modified ArchiveStreamFactory().createArchiveInputStream(inputstream) results in short text files (empirically seems to be those <= 100 bytes) being detected as tar archives which obviously is not desirable if one wants to know whether or not the files are archives. I'm not an expert on compressed archives but perhaps the heuristic that if a stream is interpretable as a tar file without an exception being thrown should only be applied on archives greater than 100 bytes? ``` You are a professional Java test case writer, please create a test case named `shortTextFilesAreNoTARs` for the issue `Compress-COMPRESS-171`, utilizing the provided issue report information and the following function signature. ```java @Test public void shortTextFilesAreNoTARs() throws Exception { ```
30
[ "org.apache.commons.compress.archivers.ArchiveStreamFactory" ]
f55593eff8fc3370d997e5f954bcb6694fda3c98c5b3d0a120112bca1cecc352
@Test public void shortTextFilesAreNoTARs() throws Exception
// You are a professional Java test case writer, please create a test case named `shortTextFilesAreNoTARs` for the issue `Compress-COMPRESS-171`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-171 // // ## Issue-Title: // createArchiveInputStream detects text files less than 100 bytes as tar archives // // ## Issue-Description: // // The fix for [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") which modified ArchiveStreamFactory().createArchiveInputStream(inputstream) results in short text files (empirically seems to be those <= 100 bytes) being detected as tar archives which obviously is not desirable if one wants to know whether or not the files are archives. // // I'm not an expert on compressed archives but perhaps the heuristic that if a stream is interpretable as a tar file without an exception being thrown should only be applied on archives greater than 100 bytes? // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.compress.archivers; import java.io.ByteArrayInputStream; import org.junit.Test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ArchiveStreamFactoryTest { /** * see https://issues.apache.org/jira/browse/COMPRESS-171 */ @Test public void shortTextFilesAreNoTARs() throws Exception { try { new ArchiveStreamFactory() .createArchiveInputStream(new ByteArrayInputStream("This certainly is not a tar archive, really, no kidding".getBytes())); fail("created an input stream for a non-archive"); } catch (ArchiveException ae) { assertTrue(ae.getMessage().startsWith("No Archiver found")); } } }
public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:\n" + " org.apache.comm\n" + " ons.cli.bug.Bug\n" + " CLI162Test\n" + "Header\n" + "-x,--extralongarg\n" + " T\n" + " h\n" + " i\n" + " s\n" + " d\n" + " e\n" + " s\n" + " c\n" + " r\n" + " i\n" + " p\n" + " t\n" + " i\n" + " o\n" + " n\n" + " i\n" + " s\n" + " L\n" + " o\n" + " n\n" + " g\n" + " .\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); }
org.apache.commons.cli.bug.BugCLI162Test::testLongLineChunkingIndentIgnored
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
299
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
testLongLineChunkingIndentIgnored
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli.bug; import java.io.IOException; import java.io.StringWriter; import java.io.PrintWriter; import java.sql.ParameterMetaData; import java.sql.Types; import junit.framework.TestCase; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class BugCLI162Test extends TestCase { public void testInfiniteLoop() { Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } public void testPrintHelpLongLines() throws ParseException, IOException { // Constants used for options final String OPT = "-"; final String OPT_COLUMN_NAMES = "l"; final String OPT_CONNECTION = "c"; final String OPT_DESCRIPTION = "e"; final String OPT_DRIVER = "d"; final String OPT_DRIVER_INFO = "n"; final String OPT_FILE_BINDING = "b"; final String OPT_FILE_JDBC = "j"; final String OPT_FILE_SFMD = "f"; final String OPT_HELP = "h"; final String OPT_HELP_ = "help"; final String OPT_INTERACTIVE = "i"; final String OPT_JDBC_TO_SFMD = "2"; final String OPT_JDBC_TO_SFMD_L = "jdbc2sfmd"; final String OPT_METADATA = "m"; final String OPT_PARAM_MODES_INT = "o"; final String OPT_PARAM_MODES_NAME = "O"; final String OPT_PARAM_NAMES = "a"; final String OPT_PARAM_TYPES_INT = "y"; final String OPT_PARAM_TYPES_NAME = "Y"; final String OPT_PASSWORD = "p"; final String OPT_PASSWORD_L = "password"; final String OPT_SQL = "s"; final String OPT_SQL_L = "sql"; final String OPT_SQL_SPLIT_DEFAULT = "###"; final String OPT_SQL_SPLIT_L = "splitSql"; final String OPT_STACK_TRACE = "t"; final String OPT_TIMING = "g"; final String OPT_TRIM_L = "trim"; final String OPT_USER = "u"; final String OPT_WRITE_TO_FILE = "w"; final String _PMODE_IN = "IN"; final String _PMODE_INOUT = "INOUT"; final String _PMODE_OUT = "OUT"; final String _PMODE_UNK = "Unknown"; final String PMODES = _PMODE_IN + ", " + _PMODE_INOUT + ", " + _PMODE_OUT + ", " + _PMODE_UNK; // Options build Options commandLineOptions; commandLineOptions = new Options(); commandLineOptions.addOption(OPT_HELP, OPT_HELP_, false, "Prints help and quits"); commandLineOptions.addOption(OPT_DRIVER, "driver", true, "JDBC driver class name"); commandLineOptions.addOption(OPT_DRIVER_INFO, "info", false, "Prints driver information and properties. If " + OPT + OPT_CONNECTION + " is not specified, all drivers on the classpath are displayed."); commandLineOptions.addOption(OPT_CONNECTION, "url", true, "Connection URL"); commandLineOptions.addOption(OPT_USER, "user", true, "A database user name"); commandLineOptions .addOption( OPT_PASSWORD, OPT_PASSWORD_L, true, "The database password for the user specified with the " + OPT + OPT_USER + " option. You can obfuscate the password with org.mortbay.jetty.security.Password, see http://docs.codehaus.org/display/JETTY/Securing+Passwords"); commandLineOptions.addOption(OPT_SQL, OPT_SQL_L, true, "Runs SQL or {call stored_procedure(?, ?)} or {?=call function(?, ?)}"); commandLineOptions.addOption(OPT_FILE_SFMD, "sfmd", true, "Writes a SFMD file for the given SQL"); commandLineOptions.addOption(OPT_FILE_BINDING, "jdbc", true, "Writes a JDBC binding node file for the given SQL"); commandLineOptions.addOption(OPT_FILE_JDBC, "node", true, "Writes a JDBC node file for the given SQL (internal debugging)"); commandLineOptions.addOption(OPT_WRITE_TO_FILE, "outfile", true, "Writes the SQL output to the given file"); commandLineOptions.addOption(OPT_DESCRIPTION, "description", true, "SFMD description. A default description is used if omited. Example: " + OPT + OPT_DESCRIPTION + " \"Runs such and such\""); commandLineOptions.addOption(OPT_INTERACTIVE, "interactive", false, "Runs in interactive mode, reading and writing from the console, 'go' or '/' sends a statement"); commandLineOptions.addOption(OPT_TIMING, "printTiming", false, "Prints timing information"); commandLineOptions.addOption(OPT_METADATA, "printMetaData", false, "Prints metadata information"); commandLineOptions.addOption(OPT_STACK_TRACE, "printStack", false, "Prints stack traces on errors"); Option option = new Option(OPT_COLUMN_NAMES, "columnNames", true, "Column XML names; default names column labels. Example: " + OPT + OPT_COLUMN_NAMES + " \"cname1 cname2\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_NAMES, "paramNames", true, "Parameter XML names; default names are param1, param2, etc. Example: " + OPT + OPT_PARAM_NAMES + " \"pname1 pname2\""); commandLineOptions.addOption(option); // OptionGroup pOutTypesOptionGroup = new OptionGroup(); String pOutTypesOptionGroupDoc = OPT + OPT_PARAM_TYPES_INT + " and " + OPT + OPT_PARAM_TYPES_NAME + " are mutually exclusive."; final String typesClassName = Types.class.getName(); option = new Option(OPT_PARAM_TYPES_INT, "paramTypes", true, "Parameter types from " + typesClassName + ". " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_INT + " \"-10 12\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_TYPES_NAME, "paramTypeNames", true, "Parameter " + typesClassName + " names. " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_NAME + " \"CURSOR VARCHAR\""); commandLineOptions.addOption(option); commandLineOptions.addOptionGroup(pOutTypesOptionGroup); // OptionGroup modesOptionGroup = new OptionGroup(); String modesOptionGroupDoc = OPT + OPT_PARAM_MODES_INT + " and " + OPT + OPT_PARAM_MODES_NAME + " are mutually exclusive."; option = new Option(OPT_PARAM_MODES_INT, "paramModes", true, "Parameters modes (" + ParameterMetaData.parameterModeIn + "=IN, " + ParameterMetaData.parameterModeInOut + "=INOUT, " + ParameterMetaData.parameterModeOut + "=OUT, " + ParameterMetaData.parameterModeUnknown + "=Unknown" + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_INT + " \"" + ParameterMetaData.parameterModeOut + " " + ParameterMetaData.parameterModeIn + "\""); modesOptionGroup.addOption(option); option = new Option(OPT_PARAM_MODES_NAME, "paramModeNames", true, "Parameters mode names (" + PMODES + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_NAME + " \"" + _PMODE_OUT + " " + _PMODE_IN + "\""); modesOptionGroup.addOption(option); commandLineOptions.addOptionGroup(modesOptionGroup); option = new Option(null, OPT_TRIM_L, true, "Trims leading and trailing spaces from all column values. Column XML names can be optionally specified to set which columns to trim."); option.setOptionalArg(true); commandLineOptions.addOption(option); option = new Option(OPT_JDBC_TO_SFMD, OPT_JDBC_TO_SFMD_L, true, "Converts the JDBC file in the first argument to an SMFD file specified in the second argument."); option.setArgs(2); commandLineOptions.addOption(option); new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); } public void testLongLineChunking() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + "and also other ReallyLongValuesThatAreHugerAndBiggerThanTheWidthOfTheColumnsBob, " + "yes. "); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 35, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:\n" + " org.apache.commons.cli.bug.B\n" + " ugCLI162Test\n" + "Header\n" + "-x,--extralongarg This\n" + " description\n" + " has\n" + " ReallyLongVal\n" + " uesThatAreLon\n" + " gerThanTheWid\n" + " thOfTheColumn\n" + " s and also\n" + " other\n" + " ReallyLongVal\n" + " uesThatAreHug\n" + " erAndBiggerTh\n" + " anTheWidthOfT\n" + " heColumnsBob,\n" + " yes.\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:\n" + " org.apache.comm\n" + " ons.cli.bug.Bug\n" + " CLI162Test\n" + "Header\n" + "-x,--extralongarg\n" + " T\n" + " h\n" + " i\n" + " s\n" + " d\n" + " e\n" + " s\n" + " c\n" + " r\n" + " i\n" + " p\n" + " t\n" + " i\n" + " o\n" + " n\n" + " i\n" + " s\n" + " L\n" + " o\n" + " n\n" + " g\n" + " .\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } }
// You are a professional Java test case writer, please create a test case named `testLongLineChunkingIndentIgnored` for the issue `Cli-CLI-162`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-162 // // ## Issue-Title: // infinite loop in the wrapping code of HelpFormatter // // ## Issue-Description: // // If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError. // // // Test case: // // // // // ``` // Options options = new Options(); // options.addOption("h", "help", false, "This is a looooong description"); // // HelpFormatter formatter = new HelpFormatter(); // formatter.setWidth(20); // formatter.printHelp("app", options); // hang & crash // // ``` // // // An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError. // // // // // public void testLongLineChunkingIndentIgnored() throws ParseException, IOException {
299
24
263
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
src/test
```markdown ## Issue-ID: Cli-CLI-162 ## Issue-Title: infinite loop in the wrapping code of HelpFormatter ## Issue-Description: If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError. Test case: ``` Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // hang & crash ``` An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError. ``` You are a professional Java test case writer, please create a test case named `testLongLineChunkingIndentIgnored` for the issue `Cli-CLI-162`, utilizing the provided issue report information and the following function signature. ```java public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { ```
263
[ "org.apache.commons.cli.HelpFormatter" ]
f63432c2b52a60a65a1af5fa80484bd8b308e5c4e0b8eddea9149eec5c1650e0
public void testLongLineChunkingIndentIgnored() throws ParseException, IOException
// You are a professional Java test case writer, please create a test case named `testLongLineChunkingIndentIgnored` for the issue `Cli-CLI-162`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-162 // // ## Issue-Title: // infinite loop in the wrapping code of HelpFormatter // // ## Issue-Description: // // If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError. // // // Test case: // // // // // ``` // Options options = new Options(); // options.addOption("h", "help", false, "This is a looooong description"); // // HelpFormatter formatter = new HelpFormatter(); // formatter.setWidth(20); // formatter.printHelp("app", options); // hang & crash // // ``` // // // An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError. // // // // //
Cli
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.cli.bug; import java.io.IOException; import java.io.StringWriter; import java.io.PrintWriter; import java.sql.ParameterMetaData; import java.sql.Types; import junit.framework.TestCase; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class BugCLI162Test extends TestCase { public void testInfiniteLoop() { Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } public void testPrintHelpLongLines() throws ParseException, IOException { // Constants used for options final String OPT = "-"; final String OPT_COLUMN_NAMES = "l"; final String OPT_CONNECTION = "c"; final String OPT_DESCRIPTION = "e"; final String OPT_DRIVER = "d"; final String OPT_DRIVER_INFO = "n"; final String OPT_FILE_BINDING = "b"; final String OPT_FILE_JDBC = "j"; final String OPT_FILE_SFMD = "f"; final String OPT_HELP = "h"; final String OPT_HELP_ = "help"; final String OPT_INTERACTIVE = "i"; final String OPT_JDBC_TO_SFMD = "2"; final String OPT_JDBC_TO_SFMD_L = "jdbc2sfmd"; final String OPT_METADATA = "m"; final String OPT_PARAM_MODES_INT = "o"; final String OPT_PARAM_MODES_NAME = "O"; final String OPT_PARAM_NAMES = "a"; final String OPT_PARAM_TYPES_INT = "y"; final String OPT_PARAM_TYPES_NAME = "Y"; final String OPT_PASSWORD = "p"; final String OPT_PASSWORD_L = "password"; final String OPT_SQL = "s"; final String OPT_SQL_L = "sql"; final String OPT_SQL_SPLIT_DEFAULT = "###"; final String OPT_SQL_SPLIT_L = "splitSql"; final String OPT_STACK_TRACE = "t"; final String OPT_TIMING = "g"; final String OPT_TRIM_L = "trim"; final String OPT_USER = "u"; final String OPT_WRITE_TO_FILE = "w"; final String _PMODE_IN = "IN"; final String _PMODE_INOUT = "INOUT"; final String _PMODE_OUT = "OUT"; final String _PMODE_UNK = "Unknown"; final String PMODES = _PMODE_IN + ", " + _PMODE_INOUT + ", " + _PMODE_OUT + ", " + _PMODE_UNK; // Options build Options commandLineOptions; commandLineOptions = new Options(); commandLineOptions.addOption(OPT_HELP, OPT_HELP_, false, "Prints help and quits"); commandLineOptions.addOption(OPT_DRIVER, "driver", true, "JDBC driver class name"); commandLineOptions.addOption(OPT_DRIVER_INFO, "info", false, "Prints driver information and properties. If " + OPT + OPT_CONNECTION + " is not specified, all drivers on the classpath are displayed."); commandLineOptions.addOption(OPT_CONNECTION, "url", true, "Connection URL"); commandLineOptions.addOption(OPT_USER, "user", true, "A database user name"); commandLineOptions .addOption( OPT_PASSWORD, OPT_PASSWORD_L, true, "The database password for the user specified with the " + OPT + OPT_USER + " option. You can obfuscate the password with org.mortbay.jetty.security.Password, see http://docs.codehaus.org/display/JETTY/Securing+Passwords"); commandLineOptions.addOption(OPT_SQL, OPT_SQL_L, true, "Runs SQL or {call stored_procedure(?, ?)} or {?=call function(?, ?)}"); commandLineOptions.addOption(OPT_FILE_SFMD, "sfmd", true, "Writes a SFMD file for the given SQL"); commandLineOptions.addOption(OPT_FILE_BINDING, "jdbc", true, "Writes a JDBC binding node file for the given SQL"); commandLineOptions.addOption(OPT_FILE_JDBC, "node", true, "Writes a JDBC node file for the given SQL (internal debugging)"); commandLineOptions.addOption(OPT_WRITE_TO_FILE, "outfile", true, "Writes the SQL output to the given file"); commandLineOptions.addOption(OPT_DESCRIPTION, "description", true, "SFMD description. A default description is used if omited. Example: " + OPT + OPT_DESCRIPTION + " \"Runs such and such\""); commandLineOptions.addOption(OPT_INTERACTIVE, "interactive", false, "Runs in interactive mode, reading and writing from the console, 'go' or '/' sends a statement"); commandLineOptions.addOption(OPT_TIMING, "printTiming", false, "Prints timing information"); commandLineOptions.addOption(OPT_METADATA, "printMetaData", false, "Prints metadata information"); commandLineOptions.addOption(OPT_STACK_TRACE, "printStack", false, "Prints stack traces on errors"); Option option = new Option(OPT_COLUMN_NAMES, "columnNames", true, "Column XML names; default names column labels. Example: " + OPT + OPT_COLUMN_NAMES + " \"cname1 cname2\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_NAMES, "paramNames", true, "Parameter XML names; default names are param1, param2, etc. Example: " + OPT + OPT_PARAM_NAMES + " \"pname1 pname2\""); commandLineOptions.addOption(option); // OptionGroup pOutTypesOptionGroup = new OptionGroup(); String pOutTypesOptionGroupDoc = OPT + OPT_PARAM_TYPES_INT + " and " + OPT + OPT_PARAM_TYPES_NAME + " are mutually exclusive."; final String typesClassName = Types.class.getName(); option = new Option(OPT_PARAM_TYPES_INT, "paramTypes", true, "Parameter types from " + typesClassName + ". " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_INT + " \"-10 12\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_TYPES_NAME, "paramTypeNames", true, "Parameter " + typesClassName + " names. " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_NAME + " \"CURSOR VARCHAR\""); commandLineOptions.addOption(option); commandLineOptions.addOptionGroup(pOutTypesOptionGroup); // OptionGroup modesOptionGroup = new OptionGroup(); String modesOptionGroupDoc = OPT + OPT_PARAM_MODES_INT + " and " + OPT + OPT_PARAM_MODES_NAME + " are mutually exclusive."; option = new Option(OPT_PARAM_MODES_INT, "paramModes", true, "Parameters modes (" + ParameterMetaData.parameterModeIn + "=IN, " + ParameterMetaData.parameterModeInOut + "=INOUT, " + ParameterMetaData.parameterModeOut + "=OUT, " + ParameterMetaData.parameterModeUnknown + "=Unknown" + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_INT + " \"" + ParameterMetaData.parameterModeOut + " " + ParameterMetaData.parameterModeIn + "\""); modesOptionGroup.addOption(option); option = new Option(OPT_PARAM_MODES_NAME, "paramModeNames", true, "Parameters mode names (" + PMODES + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_NAME + " \"" + _PMODE_OUT + " " + _PMODE_IN + "\""); modesOptionGroup.addOption(option); commandLineOptions.addOptionGroup(modesOptionGroup); option = new Option(null, OPT_TRIM_L, true, "Trims leading and trailing spaces from all column values. Column XML names can be optionally specified to set which columns to trim."); option.setOptionalArg(true); commandLineOptions.addOption(option); option = new Option(OPT_JDBC_TO_SFMD, OPT_JDBC_TO_SFMD_L, true, "Converts the JDBC file in the first argument to an SMFD file specified in the second argument."); option.setArgs(2); commandLineOptions.addOption(option); new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); } public void testLongLineChunking() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + "and also other ReallyLongValuesThatAreHugerAndBiggerThanTheWidthOfTheColumnsBob, " + "yes. "); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 35, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:\n" + " org.apache.commons.cli.bug.B\n" + " ugCLI162Test\n" + "Header\n" + "-x,--extralongarg This\n" + " description\n" + " has\n" + " ReallyLongVal\n" + " uesThatAreLon\n" + " gerThanTheWid\n" + " thOfTheColumn\n" + " s and also\n" + " other\n" + " ReallyLongVal\n" + " uesThatAreHug\n" + " erAndBiggerTh\n" + " anTheWidthOfT\n" + " heColumnsBob,\n" + " yes.\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:\n" + " org.apache.comm\n" + " ons.cli.bug.Bug\n" + " CLI162Test\n" + "Header\n" + "-x,--extralongarg\n" + " T\n" + " h\n" + " i\n" + " s\n" + " d\n" + " e\n" + " s\n" + " c\n" + " r\n" + " i\n" + " p\n" + " t\n" + " i\n" + " o\n" + " n\n" + " i\n" + " s\n" + " L\n" + " o\n" + " n\n" + " g\n" + " .\n" + "Footer\n"; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } }
@Test public void testIssue716() { BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-10, 1.0e-22, 5); UnivariateFunction sharpTurn = new UnivariateFunction() { public double value(double x) { return (2 * x + 1) / (1.0e9 * (x + 1)); } }; double result = solver.solve(100, sharpTurn, -0.9999999, 30, 15, AllowedSolution.RIGHT_SIDE); Assert.assertEquals(0, sharpTurn.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(sharpTurn.value(result) >= 0); Assert.assertEquals(-0.5, result, 1.0e-10); }
org.apache.commons.math.analysis.solvers.BracketingNthOrderBrentSolverTest::testIssue716
src/test/java/org/apache/commons/math/analysis/solvers/BracketingNthOrderBrentSolverTest.java
96
src/test/java/org/apache/commons/math/analysis/solvers/BracketingNthOrderBrentSolverTest.java
testIssue716
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import org.apache.commons.math.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.UnivariateFunction; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.exception.TooManyEvaluationsException; import org.apache.commons.math.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Test case for {@link BracketingNthOrderBrentSolver bracketing n<sup>th</sup> order Brent} solver. * * @version $Id$ */ public final class BracketingNthOrderBrentSolverTest extends BaseSecantSolverAbstractTest { /** {@inheritDoc} */ @Override protected UnivariateRealSolver getSolver() { return new BracketingNthOrderBrentSolver(); } /** {@inheritDoc} */ @Override protected int[] getQuinticEvalCounts() { return new int[] {1, 3, 8, 1, 9, 4, 8, 1, 12, 1, 16}; } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder1() { new BracketingNthOrderBrentSolver(1.0e-10, 1); } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder2() { new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1); } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder3() { new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1.0e-10, 1); } @Test public void testConstructorsOK() { Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 2).getMaximalOrder()); Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 2).getMaximalOrder()); Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1.0e-10, 2).getMaximalOrder()); } @Test public void testConvergenceOnFunctionAccuracy() { BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-10, 0.001, 3); QuinticFunction f = new QuinticFunction(); double result = solver.solve(20, f, 0.2, 0.9, 0.4, AllowedSolution.BELOW_SIDE); Assert.assertEquals(0, f.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(f.value(result) <= 0); Assert.assertTrue(result - 0.5 > solver.getAbsoluteAccuracy()); result = solver.solve(20, f, -0.9, -0.2, -0.4, AllowedSolution.ABOVE_SIDE); Assert.assertEquals(0, f.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(f.value(result) >= 0); Assert.assertTrue(result + 0.5 < -solver.getAbsoluteAccuracy()); } @Test public void testIssue716() { BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-10, 1.0e-22, 5); UnivariateFunction sharpTurn = new UnivariateFunction() { public double value(double x) { return (2 * x + 1) / (1.0e9 * (x + 1)); } }; double result = solver.solve(100, sharpTurn, -0.9999999, 30, 15, AllowedSolution.RIGHT_SIDE); Assert.assertEquals(0, sharpTurn.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(sharpTurn.value(result) >= 0); Assert.assertEquals(-0.5, result, 1.0e-10); } @Test public void testFasterThanNewton() { // the following test functions come from Beny Neta's paper: // "Several New Methods for solving Equations" // intern J. Computer Math Vol 23 pp 265-282 // available here: http://www.math.nps.navy.mil/~bneta/SeveralNewMethods.PDF // the reference roots have been computed by the Dfp solver to more than // 80 digits and checked with emacs (only the first 20 digits are reproduced here) compare(new TestFunction(0.0, -2, 2) { @Override public double value(double x) { return FastMath.sin(x) - 0.5 * x; } @Override public double derivative(double x) { return FastMath.cos(x) - 0.5; } }); compare(new TestFunction(6.3087771299726890947, -5, 10) { @Override public double value(double x) { return FastMath.pow(x, 5) + x - 10000; } @Override public double derivative(double x) { return 5 * FastMath.pow(x, 4) + 1; } }); compare(new TestFunction(9.6335955628326951924, 0.001, 10) { @Override public double value(double x) { return FastMath.sqrt(x) - 1 / x - 3; } @Override public double derivative(double x) { return 0.5 / FastMath.sqrt(x) + 1 / (x * x); } }); compare(new TestFunction(2.8424389537844470678, -5, 5) { @Override public double value(double x) { return FastMath.exp(x) + x - 20; } @Override public double derivative(double x) { return FastMath.exp(x) + 1; } }); compare(new TestFunction(8.3094326942315717953, 0.001, 10) { @Override public double value(double x) { return FastMath.log(x) + FastMath.sqrt(x) - 5; } @Override public double derivative(double x) { return 1 / x + 0.5 / FastMath.sqrt(x); } }); compare(new TestFunction(1.4655712318767680266, -0.5, 1.5) { @Override public double value(double x) { return (x - 1) * x * x - 1; } @Override public double derivative(double x) { return (3 * x - 2) * x; } }); } private void compare(TestFunction f) { compare(f, f.getRoot(), f.getMin(), f.getMax()); } private void compare(DifferentiableUnivariateFunction f, double root, double min, double max) { NewtonSolver newton = new NewtonSolver(1.0e-12); BracketingNthOrderBrentSolver bracketing = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-12, 1.0e-18, 5); double resultN; try { resultN = newton.solve(100, f, min, max); } catch (TooManyEvaluationsException tmee) { resultN = Double.NaN; } double resultB; try { resultB = bracketing.solve(100, f, min, max); } catch (TooManyEvaluationsException tmee) { resultB = Double.NaN; } Assert.assertEquals(root, resultN, newton.getAbsoluteAccuracy()); Assert.assertEquals(root, resultB, bracketing.getAbsoluteAccuracy()); Assert.assertTrue(bracketing.getEvaluations() < newton.getEvaluations()); } private static abstract class TestFunction implements DifferentiableUnivariateFunction { private final double root; private final double min; private final double max; protected TestFunction(final double root, final double min, final double max) { this.root = root; this.min = min; this.max = max; } public double getRoot() { return root; } public double getMin() { return min; } public double getMax() { return max; } public abstract double value(double x); public abstract double derivative(double x); public UnivariateFunction derivative() { return new UnivariateFunction() { public double value(double x) { return derivative(x); } }; } } }
// You are a professional Java test case writer, please create a test case named `testIssue716` for the issue `Math-MATH-716`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-716 // // ## Issue-Title: // BracketingNthOrderBrentSolver exceeds maxIterationCount while updating always the same boundary // // ## Issue-Description: // // In some cases, the aging feature in BracketingNthOrderBrentSolver fails. // // It attempts to balance the bracketing points by targeting a non-zero value instead of the real root. However, the chosen target is too close too zero, and the inverse polynomial approximation is always on the same side, thus always updates the same bracket. // // In the real used case for a large program, I had a bracket point xA = 12500.0, yA = 3.7e-16, agingA = 0, which is the (really good) estimate of the zero on one side of the root and xB = 12500.03, yB = -7.0e-5, agingB = 97. This shows that the bracketing interval is completely unbalanced, and we never succeed to rebalance it as we always updates (xA, yA) and never updates (xB, yB). // // // // // @Test public void testIssue716() {
96
40
83
src/test/java/org/apache/commons/math/analysis/solvers/BracketingNthOrderBrentSolverTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-716 ## Issue-Title: BracketingNthOrderBrentSolver exceeds maxIterationCount while updating always the same boundary ## Issue-Description: In some cases, the aging feature in BracketingNthOrderBrentSolver fails. It attempts to balance the bracketing points by targeting a non-zero value instead of the real root. However, the chosen target is too close too zero, and the inverse polynomial approximation is always on the same side, thus always updates the same bracket. In the real used case for a large program, I had a bracket point xA = 12500.0, yA = 3.7e-16, agingA = 0, which is the (really good) estimate of the zero on one side of the root and xB = 12500.03, yB = -7.0e-5, agingB = 97. This shows that the bracketing interval is completely unbalanced, and we never succeed to rebalance it as we always updates (xA, yA) and never updates (xB, yB). ``` You are a professional Java test case writer, please create a test case named `testIssue716` for the issue `Math-MATH-716`, utilizing the provided issue report information and the following function signature. ```java @Test public void testIssue716() { ```
83
[ "org.apache.commons.math.analysis.solvers.BracketingNthOrderBrentSolver" ]
f6c6873476534d59df4930d59000eb7ae94fdeae070bf66a4c7308d593d296d7
@Test public void testIssue716()
// You are a professional Java test case writer, please create a test case named `testIssue716` for the issue `Math-MATH-716`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-716 // // ## Issue-Title: // BracketingNthOrderBrentSolver exceeds maxIterationCount while updating always the same boundary // // ## Issue-Description: // // In some cases, the aging feature in BracketingNthOrderBrentSolver fails. // // It attempts to balance the bracketing points by targeting a non-zero value instead of the real root. However, the chosen target is too close too zero, and the inverse polynomial approximation is always on the same side, thus always updates the same bracket. // // In the real used case for a large program, I had a bracket point xA = 12500.0, yA = 3.7e-16, agingA = 0, which is the (really good) estimate of the zero on one side of the root and xB = 12500.03, yB = -7.0e-5, agingB = 97. This shows that the bracketing interval is completely unbalanced, and we never succeed to rebalance it as we always updates (xA, yA) and never updates (xB, yB). // // // // //
Math
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.solvers; import org.apache.commons.math.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.UnivariateFunction; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.exception.TooManyEvaluationsException; import org.apache.commons.math.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Test case for {@link BracketingNthOrderBrentSolver bracketing n<sup>th</sup> order Brent} solver. * * @version $Id$ */ public final class BracketingNthOrderBrentSolverTest extends BaseSecantSolverAbstractTest { /** {@inheritDoc} */ @Override protected UnivariateRealSolver getSolver() { return new BracketingNthOrderBrentSolver(); } /** {@inheritDoc} */ @Override protected int[] getQuinticEvalCounts() { return new int[] {1, 3, 8, 1, 9, 4, 8, 1, 12, 1, 16}; } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder1() { new BracketingNthOrderBrentSolver(1.0e-10, 1); } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder2() { new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1); } @Test(expected=NumberIsTooSmallException.class) public void testInsufficientOrder3() { new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1.0e-10, 1); } @Test public void testConstructorsOK() { Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 2).getMaximalOrder()); Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 2).getMaximalOrder()); Assert.assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1.0e-10, 2).getMaximalOrder()); } @Test public void testConvergenceOnFunctionAccuracy() { BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-10, 0.001, 3); QuinticFunction f = new QuinticFunction(); double result = solver.solve(20, f, 0.2, 0.9, 0.4, AllowedSolution.BELOW_SIDE); Assert.assertEquals(0, f.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(f.value(result) <= 0); Assert.assertTrue(result - 0.5 > solver.getAbsoluteAccuracy()); result = solver.solve(20, f, -0.9, -0.2, -0.4, AllowedSolution.ABOVE_SIDE); Assert.assertEquals(0, f.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(f.value(result) >= 0); Assert.assertTrue(result + 0.5 < -solver.getAbsoluteAccuracy()); } @Test public void testIssue716() { BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-10, 1.0e-22, 5); UnivariateFunction sharpTurn = new UnivariateFunction() { public double value(double x) { return (2 * x + 1) / (1.0e9 * (x + 1)); } }; double result = solver.solve(100, sharpTurn, -0.9999999, 30, 15, AllowedSolution.RIGHT_SIDE); Assert.assertEquals(0, sharpTurn.value(result), solver.getFunctionValueAccuracy()); Assert.assertTrue(sharpTurn.value(result) >= 0); Assert.assertEquals(-0.5, result, 1.0e-10); } @Test public void testFasterThanNewton() { // the following test functions come from Beny Neta's paper: // "Several New Methods for solving Equations" // intern J. Computer Math Vol 23 pp 265-282 // available here: http://www.math.nps.navy.mil/~bneta/SeveralNewMethods.PDF // the reference roots have been computed by the Dfp solver to more than // 80 digits and checked with emacs (only the first 20 digits are reproduced here) compare(new TestFunction(0.0, -2, 2) { @Override public double value(double x) { return FastMath.sin(x) - 0.5 * x; } @Override public double derivative(double x) { return FastMath.cos(x) - 0.5; } }); compare(new TestFunction(6.3087771299726890947, -5, 10) { @Override public double value(double x) { return FastMath.pow(x, 5) + x - 10000; } @Override public double derivative(double x) { return 5 * FastMath.pow(x, 4) + 1; } }); compare(new TestFunction(9.6335955628326951924, 0.001, 10) { @Override public double value(double x) { return FastMath.sqrt(x) - 1 / x - 3; } @Override public double derivative(double x) { return 0.5 / FastMath.sqrt(x) + 1 / (x * x); } }); compare(new TestFunction(2.8424389537844470678, -5, 5) { @Override public double value(double x) { return FastMath.exp(x) + x - 20; } @Override public double derivative(double x) { return FastMath.exp(x) + 1; } }); compare(new TestFunction(8.3094326942315717953, 0.001, 10) { @Override public double value(double x) { return FastMath.log(x) + FastMath.sqrt(x) - 5; } @Override public double derivative(double x) { return 1 / x + 0.5 / FastMath.sqrt(x); } }); compare(new TestFunction(1.4655712318767680266, -0.5, 1.5) { @Override public double value(double x) { return (x - 1) * x * x - 1; } @Override public double derivative(double x) { return (3 * x - 2) * x; } }); } private void compare(TestFunction f) { compare(f, f.getRoot(), f.getMin(), f.getMax()); } private void compare(DifferentiableUnivariateFunction f, double root, double min, double max) { NewtonSolver newton = new NewtonSolver(1.0e-12); BracketingNthOrderBrentSolver bracketing = new BracketingNthOrderBrentSolver(1.0e-12, 1.0e-12, 1.0e-18, 5); double resultN; try { resultN = newton.solve(100, f, min, max); } catch (TooManyEvaluationsException tmee) { resultN = Double.NaN; } double resultB; try { resultB = bracketing.solve(100, f, min, max); } catch (TooManyEvaluationsException tmee) { resultB = Double.NaN; } Assert.assertEquals(root, resultN, newton.getAbsoluteAccuracy()); Assert.assertEquals(root, resultB, bracketing.getAbsoluteAccuracy()); Assert.assertTrue(bracketing.getEvaluations() < newton.getEvaluations()); } private static abstract class TestFunction implements DifferentiableUnivariateFunction { private final double root; private final double min; private final double max; protected TestFunction(final double root, final double min, final double max) { this.root = root; this.min = min; this.max = max; } public double getRoot() { return root; } public double getMin() { return min; } public double getMax() { return max; } public abstract double value(double x); public abstract double derivative(double x); public UnivariateFunction derivative() { return new UnivariateFunction() { public double value(double x) { return derivative(x); } }; } } }
public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); }
com.google.javascript.jscomp.TypeCheckTest::testThisTypeOfFunction2
test/com/google/javascript/jscomp/TypeCheckTest.java
4,557
test/com/google/javascript/jscomp/TypeCheckTest.java
testThisTypeOfFunction2
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, new DefaultCodingConvention()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck7() throws Exception { testTypes("function foo() {delete 'abc';}", TypeCheck.BAD_DELETE); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferrable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode] :2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testTypes("/** @enum */var a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum9() throws Exception { testTypes( "var goog = {};" + "/** @enum */goog.a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse5() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @type {string} */ var MyTypedef = goog.typedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Tehnically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "null has no properties\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "goog.asserts = {};" + "/** @return {*} */ goog.asserts.assert = function(x) { return x; };" + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes thru this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {boolean} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of (Object|null|number)\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypesMultipleWarnings( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", Lists.newArrayList( "variable x.abc redefined with type " + "function (string): undefined, " + "original definition at [testcode] :1 with type " + "function (boolean): undefined", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined")); } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testMalformedOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testMalformedOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @typedef {boolean} */ goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testDuplicateOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @constructor */ goog.Bar = function() {};" + "/** @type {number} */ goog.Bar = goog.typedef", "variable goog.Bar redefined with type number, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testOldTypeDef1() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testOldTypeDef3() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ var Bar = goog.typedef;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number|Array.<goog.Bar>} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // ok, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format(), true); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format(), true); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format(), true); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralUnreadThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, {});", "Function literal argument does not refer to bound this argument"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput("[testcode]").getAstRoot(compiler); Node externsNode = compiler.getInput("[externs]").getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testThisTypeOfFunction2` for the issue `Closure-440`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-440 // // ## Issue-Title: // Compiler should warn/error when instance methods are operated on // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile and run the following code: // goog.require('goog.graphics.Path'); // function demo() { // var path = new goog.graphics.Path(); // var points = [[1,1], [2,2]]; // for (var i = 0; i < points.length; i++) { // (i == 0 ? path.moveTo : path.lineTo)(points[i][0], points[i][1]); // } // } // goog.exportSymbol('demo', demo); // // **What is the expected output? What do you see instead?** // I expect it to either work or produce a warning. In this case, the latter since there's an error in the javascript - when calling path.moveTo(x, y), "this" is set correctly to the path element in the moveTo function. But when the function is operated on, as in (i == 0 ? path.moveTo : path.lineTo)(x, y), it's no longer an instance method invocation, so "this" reverts to the window object. In this case, an error results because moveTo references a field in Path that is now "undefined". Better would be to issue a warning/error that an instance method is being converted to a normal function (perhaps only if it references this). // // **What version of the product are you using? On what operating system?** // Unknown (it's built into my build tools) - I presume this issue is present in all builds. Running on ubuntu. // // **Please provide any additional information below.** // // public void testThisTypeOfFunction2() throws Exception {
4,557
69
4,551
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-440 ## Issue-Title: Compiler should warn/error when instance methods are operated on ## Issue-Description: **What steps will reproduce the problem?** 1. Compile and run the following code: goog.require('goog.graphics.Path'); function demo() { var path = new goog.graphics.Path(); var points = [[1,1], [2,2]]; for (var i = 0; i < points.length; i++) { (i == 0 ? path.moveTo : path.lineTo)(points[i][0], points[i][1]); } } goog.exportSymbol('demo', demo); **What is the expected output? What do you see instead?** I expect it to either work or produce a warning. In this case, the latter since there's an error in the javascript - when calling path.moveTo(x, y), "this" is set correctly to the path element in the moveTo function. But when the function is operated on, as in (i == 0 ? path.moveTo : path.lineTo)(x, y), it's no longer an instance method invocation, so "this" reverts to the window object. In this case, an error results because moveTo references a field in Path that is now "undefined". Better would be to issue a warning/error that an instance method is being converted to a normal function (perhaps only if it references this). **What version of the product are you using? On what operating system?** Unknown (it's built into my build tools) - I presume this issue is present in all builds. Running on ubuntu. **Please provide any additional information below.** ``` You are a professional Java test case writer, please create a test case named `testThisTypeOfFunction2` for the issue `Closure-440`, utilizing the provided issue report information and the following function signature. ```java public void testThisTypeOfFunction2() throws Exception { ```
4,551
[ "com.google.javascript.jscomp.TypeCheck" ]
f6da714c2a13ff4d106fbc8d33b2c17b6203613375e6c3cf9b336da7ea32fb51
public void testThisTypeOfFunction2() throws Exception
// You are a professional Java test case writer, please create a test case named `testThisTypeOfFunction2` for the issue `Closure-440`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-440 // // ## Issue-Title: // Compiler should warn/error when instance methods are operated on // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile and run the following code: // goog.require('goog.graphics.Path'); // function demo() { // var path = new goog.graphics.Path(); // var points = [[1,1], [2,2]]; // for (var i = 0; i < points.length; i++) { // (i == 0 ? path.moveTo : path.lineTo)(points[i][0], points[i][1]); // } // } // goog.exportSymbol('demo', demo); // // **What is the expected output? What do you see instead?** // I expect it to either work or produce a warning. In this case, the latter since there's an error in the javascript - when calling path.moveTo(x, y), "this" is set correctly to the path element in the moveTo function. But when the function is operated on, as in (i == 0 ? path.moveTo : path.lineTo)(x, y), it's no longer an instance method invocation, so "this" reverts to the window object. In this case, an error results because moveTo references a field in Path that is now "undefined". Better would be to issue a warning/error that an instance method is being converted to a normal function (perhaps only if it references this). // // **What version of the product are you using? On what operating system?** // Unknown (it's built into my build tools) - I presume this issue is present in all builds. Running on ubuntu. // // **Please provide any additional information below.** // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, new DefaultCodingConvention()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck7() throws Exception { testTypes("function foo() {delete 'abc';}", TypeCheck.BAD_DELETE); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferrable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode] :2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testTypes("/** @enum */var a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum9() throws Exception { testTypes( "var goog = {};" + "/** @enum */goog.a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse1() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {string} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: string"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse3() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {(Date|string)} */ var MyTypedef;", "@this type of a function must be an object\n" + "Actual type: (Date|null|string)"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse5() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @type {string} */ var MyTypedef = goog.typedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Tehnically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "null has no properties\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "goog.asserts = {};" + "/** @return {*} */ goog.asserts.assert = function(x) { return x; };" + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes thru this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", "Bad type annotation. Unknown type ns.Foo"); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a runtime cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {boolean} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of (Object|null|number)\n" + "found : number\n" + "required: string"); } public void testCast17() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}"); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ foo;\n" + "foo.bar();"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypesMultipleWarnings( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", Lists.newArrayList( "variable x.abc redefined with type " + "function (string): undefined, " + "original definition at [testcode] :1 with type " + "function (boolean): undefined", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined")); } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testMalformedOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testMalformedOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @typedef {boolean} */ goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testDuplicateOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @constructor */ goog.Bar = function() {};" + "/** @type {number} */ goog.Bar = goog.typedef", "variable goog.Bar redefined with type number, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testOldTypeDef1() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testOldTypeDef3() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ var Bar = goog.typedef;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number|Array.<goog.Bar>} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // ok, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format(), true); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format(), true); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format(), true); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testFunctionLiteralUndefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralUnreadThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, {});", "Function literal argument does not refer to bound this argument"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; a constructor can only extend " + "objects and an interface can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); for (int i = 0; i < descriptions.size(); i++) { assertEquals(descriptions.get(i), compiler.getWarnings()[i].description); } } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput("[testcode]").getAstRoot(compiler); Node externsNode = compiler.getInput("[externs]").getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
@Test public void consumeToNonexistentEndWhenAtAnd() { CharacterReader r = new CharacterReader("<!"); assertTrue(r.matchConsume("<!")); assertTrue(r.isEmpty()); String after = r.consumeTo('>'); assertEquals("", after); assertTrue(r.isEmpty()); }
org.jsoup.parser.CharacterReaderTest::consumeToNonexistentEndWhenAtAnd
src/test/java/org/jsoup/parser/CharacterReaderTest.java
268
src/test/java/org/jsoup/parser/CharacterReaderTest.java
consumeToNonexistentEndWhenAtAnd
package org.jsoup.parser; import org.junit.Test; import static org.junit.Assert.*; /** * Test suite for character reader. * * @author Jonathan Hedley, jonathan@hedley.net */ public class CharacterReaderTest { @Test public void consume() { CharacterReader r = new CharacterReader("one"); assertEquals(0, r.pos()); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals(1, r.pos()); assertEquals('n', r.current()); assertEquals(1, r.pos()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); } @Test public void unconsume() { CharacterReader r = new CharacterReader("one"); assertEquals('o', r.consume()); assertEquals('n', r.current()); r.unconsume(); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.unconsume(); assertFalse(r.isEmpty()); assertEquals('e', r.current()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); r.unconsume(); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.current()); } @Test public void mark() { CharacterReader r = new CharacterReader("one"); r.consume(); r.mark(); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.rewindToMark(); assertEquals('n', r.consume()); } @Test public void consumeToEnd() { String in = "one two three"; CharacterReader r = new CharacterReader(in); String toEnd = r.consumeToEnd(); assertEquals(in, toEnd); assertTrue(r.isEmpty()); } @Test public void nextIndexOfChar() { String in = "blah blah"; CharacterReader r = new CharacterReader(in); assertEquals(-1, r.nextIndexOf('x')); assertEquals(3, r.nextIndexOf('h')); String pull = r.consumeTo('h'); assertEquals("bla", pull); r.consume(); assertEquals(2, r.nextIndexOf('l')); assertEquals(" blah", r.consumeToEnd()); assertEquals(-1, r.nextIndexOf('x')); } @Test public void nextIndexOfString() { String in = "One Two something Two Three Four"; CharacterReader r = new CharacterReader(in); assertEquals(-1, r.nextIndexOf("Foo")); assertEquals(4, r.nextIndexOf("Two")); assertEquals("One Two ", r.consumeTo("something")); assertEquals(10, r.nextIndexOf("Two")); assertEquals("something Two Three Four", r.consumeToEnd()); assertEquals(-1, r.nextIndexOf("Two")); } @Test public void nextIndexOfUnmatched() { CharacterReader r = new CharacterReader("<[[one]]"); assertEquals(-1, r.nextIndexOf("]]>")); } @Test public void consumeToChar() { CharacterReader r = new CharacterReader("One Two Three"); assertEquals("One ", r.consumeTo('T')); assertEquals("", r.consumeTo('T')); // on Two assertEquals('T', r.consume()); assertEquals("wo ", r.consumeTo('T')); assertEquals('T', r.consume()); assertEquals("hree", r.consumeTo('T')); // consume to end } @Test public void consumeToString() { CharacterReader r = new CharacterReader("One Two Two Four"); assertEquals("One ", r.consumeTo("Two")); assertEquals('T', r.consume()); assertEquals("wo ", r.consumeTo("Two")); assertEquals('T', r.consume()); assertEquals("wo Four", r.consumeTo("Qux")); } @Test public void advance() { CharacterReader r = new CharacterReader("One Two Three"); assertEquals('O', r.consume()); r.advance(); assertEquals('e', r.consume()); } @Test public void consumeToAny() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One ", r.consumeToAny('&', ';')); assertTrue(r.matches('&')); assertTrue(r.matches("&bar;")); assertEquals('&', r.consume()); assertEquals("bar", r.consumeToAny('&', ';')); assertEquals(';', r.consume()); assertEquals(" qux", r.consumeToAny('&', ';')); } @Test public void consumeLetterSequence() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One", r.consumeLetterSequence()); assertEquals(" &", r.consumeTo("bar;")); assertEquals("bar", r.consumeLetterSequence()); assertEquals("; qux", r.consumeToEnd()); } @Test public void consumeLetterThenDigitSequence() { CharacterReader r = new CharacterReader("One12 Two &bar; qux"); assertEquals("One12", r.consumeLetterThenDigitSequence()); assertEquals(' ', r.consume()); assertEquals("Two", r.consumeLetterThenDigitSequence()); assertEquals(" &bar; qux", r.consumeToEnd()); } @Test public void matches() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matches('O')); assertTrue(r.matches("One Two Three")); assertTrue(r.matches("One")); assertFalse(r.matches("one")); assertEquals('O', r.consume()); assertFalse(r.matches("One")); assertTrue(r.matches("ne Two Three")); assertFalse(r.matches("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matches("ne")); assertTrue(r.isEmpty()); } @Test public void matchesIgnoreCase() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matchesIgnoreCase("O")); assertTrue(r.matchesIgnoreCase("o")); assertTrue(r.matches('O')); assertFalse(r.matches('o')); assertTrue(r.matchesIgnoreCase("One Two Three")); assertTrue(r.matchesIgnoreCase("ONE two THREE")); assertTrue(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("one")); assertEquals('O', r.consume()); assertFalse(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("NE Two Three")); assertFalse(r.matchesIgnoreCase("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matchesIgnoreCase("ne")); } @Test public void containsIgnoreCase() { CharacterReader r = new CharacterReader("One TWO three"); assertTrue(r.containsIgnoreCase("two")); assertTrue(r.containsIgnoreCase("three")); // weird one: does not find one, because it scans for consistent case only assertFalse(r.containsIgnoreCase("one")); } @Test public void matchesAny() { char[] scan = {' ', '\n', '\t'}; CharacterReader r = new CharacterReader("One\nTwo\tThree"); assertFalse(r.matchesAny(scan)); assertEquals("One", r.consumeToAny(scan)); assertTrue(r.matchesAny(scan)); assertEquals('\n', r.consume()); assertFalse(r.matchesAny(scan)); } @Test public void cachesStrings() { CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE\tA string that is longer than 16 chars"); String one = r.consumeTo('\t'); r.consume(); String two = r.consumeTo('\t'); r.consume(); String three = r.consumeTo('\t'); r.consume(); String four = r.consumeTo('\t'); r.consume(); String five = r.consumeTo('\t'); assertEquals("Check", one); assertEquals("Check", two); assertEquals("Check", three); assertEquals("CHOKE", four); assertTrue(one == two); assertTrue(two == three); assertTrue(three != four); assertTrue(four != five); assertEquals(five, "A string that is longer than 16 chars"); } @Test public void rangeEquals() { CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE"); assertTrue(r.rangeEquals(0, 5, "Check")); assertFalse(r.rangeEquals(0, 5, "CHOKE")); assertFalse(r.rangeEquals(0, 5, "Chec")); assertTrue(r.rangeEquals(6, 5, "Check")); assertFalse(r.rangeEquals(6, 5, "Chuck")); assertTrue(r.rangeEquals(12, 5, "Check")); assertFalse(r.rangeEquals(12, 5, "Cheeky")); assertTrue(r.rangeEquals(18, 5, "CHOKE")); assertFalse(r.rangeEquals(18, 5, "CHIKE")); } @Test public void empty() { CharacterReader r = new CharacterReader("One"); assertTrue(r.matchConsume("One")); assertTrue(r.isEmpty()); r = new CharacterReader("Two"); String two = r.consumeToEnd(); assertEquals("Two", two); } @Test public void consumeToNonexistentEndWhenAtAnd() { CharacterReader r = new CharacterReader("<!"); assertTrue(r.matchConsume("<!")); assertTrue(r.isEmpty()); String after = r.consumeTo('>'); assertEquals("", after); assertTrue(r.isEmpty()); } }
// You are a professional Java test case writer, please create a test case named `consumeToNonexistentEndWhenAtAnd` for the issue `Jsoup-972`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-972 // // ## Issue-Title: // StringIndexOutOfBoundsException as of jsoup 1.11.1 // // ## Issue-Description: // Example: // // // // ``` // Jsoup.parse(new URL("https://gist.githubusercontent.com/valodzka/91ed27043628e9023009e503d41f1aad/raw/a15f68671e6f0517e48fdac812983b85fea27c16/test.html"), 10_000); // // ``` // // // @Test public void consumeToNonexistentEndWhenAtAnd() {
268
72
258
src/test/java/org/jsoup/parser/CharacterReaderTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-972 ## Issue-Title: StringIndexOutOfBoundsException as of jsoup 1.11.1 ## Issue-Description: Example: ``` Jsoup.parse(new URL("https://gist.githubusercontent.com/valodzka/91ed27043628e9023009e503d41f1aad/raw/a15f68671e6f0517e48fdac812983b85fea27c16/test.html"), 10_000); ``` ``` You are a professional Java test case writer, please create a test case named `consumeToNonexistentEndWhenAtAnd` for the issue `Jsoup-972`, utilizing the provided issue report information and the following function signature. ```java @Test public void consumeToNonexistentEndWhenAtAnd() { ```
258
[ "org.jsoup.parser.CharacterReader" ]
f79066f7d91a1f159be25085b7c6ef51ac4a68a311f0bd0c07a1adb2615eb34c
@Test public void consumeToNonexistentEndWhenAtAnd()
// You are a professional Java test case writer, please create a test case named `consumeToNonexistentEndWhenAtAnd` for the issue `Jsoup-972`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-972 // // ## Issue-Title: // StringIndexOutOfBoundsException as of jsoup 1.11.1 // // ## Issue-Description: // Example: // // // // ``` // Jsoup.parse(new URL("https://gist.githubusercontent.com/valodzka/91ed27043628e9023009e503d41f1aad/raw/a15f68671e6f0517e48fdac812983b85fea27c16/test.html"), 10_000); // // ``` // // //
Jsoup
package org.jsoup.parser; import org.junit.Test; import static org.junit.Assert.*; /** * Test suite for character reader. * * @author Jonathan Hedley, jonathan@hedley.net */ public class CharacterReaderTest { @Test public void consume() { CharacterReader r = new CharacterReader("one"); assertEquals(0, r.pos()); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals(1, r.pos()); assertEquals('n', r.current()); assertEquals(1, r.pos()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); } @Test public void unconsume() { CharacterReader r = new CharacterReader("one"); assertEquals('o', r.consume()); assertEquals('n', r.current()); r.unconsume(); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.unconsume(); assertFalse(r.isEmpty()); assertEquals('e', r.current()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); r.unconsume(); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.current()); } @Test public void mark() { CharacterReader r = new CharacterReader("one"); r.consume(); r.mark(); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.rewindToMark(); assertEquals('n', r.consume()); } @Test public void consumeToEnd() { String in = "one two three"; CharacterReader r = new CharacterReader(in); String toEnd = r.consumeToEnd(); assertEquals(in, toEnd); assertTrue(r.isEmpty()); } @Test public void nextIndexOfChar() { String in = "blah blah"; CharacterReader r = new CharacterReader(in); assertEquals(-1, r.nextIndexOf('x')); assertEquals(3, r.nextIndexOf('h')); String pull = r.consumeTo('h'); assertEquals("bla", pull); r.consume(); assertEquals(2, r.nextIndexOf('l')); assertEquals(" blah", r.consumeToEnd()); assertEquals(-1, r.nextIndexOf('x')); } @Test public void nextIndexOfString() { String in = "One Two something Two Three Four"; CharacterReader r = new CharacterReader(in); assertEquals(-1, r.nextIndexOf("Foo")); assertEquals(4, r.nextIndexOf("Two")); assertEquals("One Two ", r.consumeTo("something")); assertEquals(10, r.nextIndexOf("Two")); assertEquals("something Two Three Four", r.consumeToEnd()); assertEquals(-1, r.nextIndexOf("Two")); } @Test public void nextIndexOfUnmatched() { CharacterReader r = new CharacterReader("<[[one]]"); assertEquals(-1, r.nextIndexOf("]]>")); } @Test public void consumeToChar() { CharacterReader r = new CharacterReader("One Two Three"); assertEquals("One ", r.consumeTo('T')); assertEquals("", r.consumeTo('T')); // on Two assertEquals('T', r.consume()); assertEquals("wo ", r.consumeTo('T')); assertEquals('T', r.consume()); assertEquals("hree", r.consumeTo('T')); // consume to end } @Test public void consumeToString() { CharacterReader r = new CharacterReader("One Two Two Four"); assertEquals("One ", r.consumeTo("Two")); assertEquals('T', r.consume()); assertEquals("wo ", r.consumeTo("Two")); assertEquals('T', r.consume()); assertEquals("wo Four", r.consumeTo("Qux")); } @Test public void advance() { CharacterReader r = new CharacterReader("One Two Three"); assertEquals('O', r.consume()); r.advance(); assertEquals('e', r.consume()); } @Test public void consumeToAny() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One ", r.consumeToAny('&', ';')); assertTrue(r.matches('&')); assertTrue(r.matches("&bar;")); assertEquals('&', r.consume()); assertEquals("bar", r.consumeToAny('&', ';')); assertEquals(';', r.consume()); assertEquals(" qux", r.consumeToAny('&', ';')); } @Test public void consumeLetterSequence() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One", r.consumeLetterSequence()); assertEquals(" &", r.consumeTo("bar;")); assertEquals("bar", r.consumeLetterSequence()); assertEquals("; qux", r.consumeToEnd()); } @Test public void consumeLetterThenDigitSequence() { CharacterReader r = new CharacterReader("One12 Two &bar; qux"); assertEquals("One12", r.consumeLetterThenDigitSequence()); assertEquals(' ', r.consume()); assertEquals("Two", r.consumeLetterThenDigitSequence()); assertEquals(" &bar; qux", r.consumeToEnd()); } @Test public void matches() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matches('O')); assertTrue(r.matches("One Two Three")); assertTrue(r.matches("One")); assertFalse(r.matches("one")); assertEquals('O', r.consume()); assertFalse(r.matches("One")); assertTrue(r.matches("ne Two Three")); assertFalse(r.matches("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matches("ne")); assertTrue(r.isEmpty()); } @Test public void matchesIgnoreCase() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matchesIgnoreCase("O")); assertTrue(r.matchesIgnoreCase("o")); assertTrue(r.matches('O')); assertFalse(r.matches('o')); assertTrue(r.matchesIgnoreCase("One Two Three")); assertTrue(r.matchesIgnoreCase("ONE two THREE")); assertTrue(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("one")); assertEquals('O', r.consume()); assertFalse(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("NE Two Three")); assertFalse(r.matchesIgnoreCase("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matchesIgnoreCase("ne")); } @Test public void containsIgnoreCase() { CharacterReader r = new CharacterReader("One TWO three"); assertTrue(r.containsIgnoreCase("two")); assertTrue(r.containsIgnoreCase("three")); // weird one: does not find one, because it scans for consistent case only assertFalse(r.containsIgnoreCase("one")); } @Test public void matchesAny() { char[] scan = {' ', '\n', '\t'}; CharacterReader r = new CharacterReader("One\nTwo\tThree"); assertFalse(r.matchesAny(scan)); assertEquals("One", r.consumeToAny(scan)); assertTrue(r.matchesAny(scan)); assertEquals('\n', r.consume()); assertFalse(r.matchesAny(scan)); } @Test public void cachesStrings() { CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE\tA string that is longer than 16 chars"); String one = r.consumeTo('\t'); r.consume(); String two = r.consumeTo('\t'); r.consume(); String three = r.consumeTo('\t'); r.consume(); String four = r.consumeTo('\t'); r.consume(); String five = r.consumeTo('\t'); assertEquals("Check", one); assertEquals("Check", two); assertEquals("Check", three); assertEquals("CHOKE", four); assertTrue(one == two); assertTrue(two == three); assertTrue(three != four); assertTrue(four != five); assertEquals(five, "A string that is longer than 16 chars"); } @Test public void rangeEquals() { CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE"); assertTrue(r.rangeEquals(0, 5, "Check")); assertFalse(r.rangeEquals(0, 5, "CHOKE")); assertFalse(r.rangeEquals(0, 5, "Chec")); assertTrue(r.rangeEquals(6, 5, "Check")); assertFalse(r.rangeEquals(6, 5, "Chuck")); assertTrue(r.rangeEquals(12, 5, "Check")); assertFalse(r.rangeEquals(12, 5, "Cheeky")); assertTrue(r.rangeEquals(18, 5, "CHOKE")); assertFalse(r.rangeEquals(18, 5, "CHIKE")); } @Test public void empty() { CharacterReader r = new CharacterReader("One"); assertTrue(r.matchConsume("One")); assertTrue(r.isEmpty()); r = new CharacterReader("Two"); String two = r.consumeToEnd(); assertEquals("Two", two); } @Test public void consumeToNonexistentEndWhenAtAnd() { CharacterReader r = new CharacterReader("<!"); assertTrue(r.matchConsume("<!")); assertTrue(r.isEmpty()); String after = r.consumeTo('>'); assertEquals("", after); assertTrue(r.isEmpty()); } }
@Test public void handlesFramesets() { String dirty = "<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\" /><frame src=\"foo\" /></frameset></html>"; String clean = Jsoup.clean(dirty, Whitelist.basic()); assertEquals("", clean); // nothing good can come out of that Document dirtyDoc = Jsoup.parse(dirty); Document cleanDoc = new Cleaner(Whitelist.basic()).clean(dirtyDoc); assertFalse(cleanDoc == null); assertEquals(0, cleanDoc.body().childNodes().size()); }
org.jsoup.safety.CleanerTest::handlesFramesets
src/test/java/org/jsoup/safety/CleanerTest.java
178
src/test/java/org/jsoup/safety/CleanerTest.java
handlesFramesets
package org.jsoup.safety; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Document; import org.jsoup.nodes.Entities; import org.jsoup.safety.Whitelist; import org.junit.Test; import static org.junit.Assert.*; /** Tests for the cleaner. @author Jonathan Hedley, jonathan@hedley.net */ public class CleanerTest { @Test public void simpleBehaviourTest() { String h = "<div><p class=foo><a href='http://evil.com'>Hello <b id=bar>there</b>!</a></div>"; String cleanHtml = Jsoup.clean(h, Whitelist.simpleText()); assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml)); } @Test public void simpleBehaviourTest2() { String h = "Hello <b>there</b>!"; String cleanHtml = Jsoup.clean(h, Whitelist.simpleText()); assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml)); } @Test public void basicBehaviourTest() { String h = "<div><p><a href='javascript:sendAllMoney()'>Dodgy</a> <A HREF='HTTP://nice.com'>Nice</a></p><blockquote>Hello</blockquote>"; String cleanHtml = Jsoup.clean(h, Whitelist.basic()); assertEquals("<p><a rel=\"nofollow\">Dodgy</a> <a href=\"http://nice.com\" rel=\"nofollow\">Nice</a></p><blockquote>Hello</blockquote>", TextUtil.stripNewlines(cleanHtml)); } @Test public void basicWithImagesTest() { String h = "<div><p><img src='http://example.com/' alt=Image></p><p><img src='ftp://ftp.example.com'></p></div>"; String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages()); assertEquals("<p><img src=\"http://example.com/\" alt=\"Image\" /></p><p><img /></p>", TextUtil.stripNewlines(cleanHtml)); } @Test public void testRelaxed() { String h = "<h1>Head</h1><table><tr><td>One<td>Two</td></tr></table>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<h1>Head</h1><table><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(cleanHtml)); } @Test public void testDropComments() { String h = "<p>Hello<!-- no --></p>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<p>Hello</p>", cleanHtml); } @Test public void testDropXmlProc() { String h = "<?import namespace=\"xss\"><p>Hello</p>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<p>Hello</p>", cleanHtml); } @Test public void testDropScript() { String h = "<SCRIPT SRC=//ha.ckers.org/.j><SCRIPT>alert(/XSS/.source)</SCRIPT>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("", cleanHtml); } @Test public void testDropImageScript() { String h = "<IMG SRC=\"javascript:alert('XSS')\">"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<img />", cleanHtml); } @Test public void testCleanJavascriptHref() { String h = "<A HREF=\"javascript:document.location='http://www.google.com/'\">XSS</A>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<a>XSS</a>", cleanHtml); } @Test public void testDropsUnknownTags() { String h = "<p><custom foo=true>Test</custom></p>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<p>Test</p>", cleanHtml); } @Test public void testHandlesEmptyAttributes() { String h = "<img alt=\"\" src= unknown=''>"; String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages()); assertEquals("<img alt=\"\" />", cleanHtml); } @Test public void testIsValid() { String ok = "<p>Test <b><a href='http://example.com/'>OK</a></b></p>"; String nok1 = "<p><script></script>Not <b>OK</b></p>"; String nok2 = "<p align=right>Test Not <b>OK</b></p>"; assertTrue(Jsoup.isValid(ok, Whitelist.basic())); assertFalse(Jsoup.isValid(nok1, Whitelist.basic())); assertFalse(Jsoup.isValid(nok2, Whitelist.basic())); } @Test public void resolvesRelativeLinks() { String html = "<a href='/foo'>Link</a><img src='/bar'>"; String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages()); assertEquals("<a href=\"http://example.com/foo\" rel=\"nofollow\">Link</a>\n<img src=\"http://example.com/bar\" />", clean); } @Test public void preservesRelatedLinksIfConfigured() { String html = "<a href='/foo'>Link</a><img src='/bar'> <img src='javascript:alert()'>"; String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages().preserveRelativeLinks(true)); assertEquals("<a href=\"/foo\" rel=\"nofollow\">Link</a>\n<img src=\"/bar\" /> \n<img />", clean); } @Test public void dropsUnresolvableRelativeLinks() { String html = "<a href='/foo'>Link</a>"; String clean = Jsoup.clean(html, Whitelist.basic()); assertEquals("<a rel=\"nofollow\">Link</a>", clean); } @Test public void handlesCustomProtocols() { String html = "<img src='cid:12345' /> <img src='data:gzzt' />"; String dropped = Jsoup.clean(html, Whitelist.basicWithImages()); assertEquals("<img /> \n<img />", dropped); String preserved = Jsoup.clean(html, Whitelist.basicWithImages().addProtocols("img", "src", "cid", "data")); assertEquals("<img src=\"cid:12345\" /> \n<img src=\"data:gzzt\" />", preserved); } @Test public void handlesAllPseudoTag() { String html = "<p class='foo' src='bar'><a class='qux'>link</a></p>"; Whitelist whitelist = new Whitelist() .addAttributes(":all", "class") .addAttributes("p", "style") .addTags("p", "a"); String clean = Jsoup.clean(html, whitelist); assertEquals("<p class=\"foo\"><a class=\"qux\">link</a></p>", clean); } @Test public void addsTagOnAttributesIfNotSet() { String html = "<p class='foo' src='bar'>One</p>"; Whitelist whitelist = new Whitelist() .addAttributes("p", "class"); // ^^ whitelist does not have explicit tag add for p, inferred from add attributes. String clean = Jsoup.clean(html, whitelist); assertEquals("<p class=\"foo\">One</p>", clean); } @Test public void supplyOutputSettings() { // test that one can override the default document output settings Document.OutputSettings os = new Document.OutputSettings(); os.prettyPrint(false); os.escapeMode(Entities.EscapeMode.extended); String html = "<div><p>&bernou;</p></div>"; String customOut = Jsoup.clean(html, "http://foo.com/", Whitelist.relaxed(), os); String defaultOut = Jsoup.clean(html, "http://foo.com/", Whitelist.relaxed()); assertNotSame(defaultOut, customOut); assertEquals("<div><p>&bernou;</p></div>", customOut); assertEquals("<div>\n" + " <p>ℬ</p>\n" + "</div>", defaultOut); os.charset("ASCII"); os.escapeMode(Entities.EscapeMode.base); String customOut2 = Jsoup.clean(html, "http://foo.com/", Whitelist.relaxed(), os); assertEquals("<div><p>&#8492;</p></div>", customOut2); } @Test public void handlesFramesets() { String dirty = "<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\" /><frame src=\"foo\" /></frameset></html>"; String clean = Jsoup.clean(dirty, Whitelist.basic()); assertEquals("", clean); // nothing good can come out of that Document dirtyDoc = Jsoup.parse(dirty); Document cleanDoc = new Cleaner(Whitelist.basic()).clean(dirtyDoc); assertFalse(cleanDoc == null); assertEquals(0, cleanDoc.body().childNodes().size()); } }
// You are a professional Java test case writer, please create a test case named `handlesFramesets` for the issue `Jsoup-154`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-154 // // ## Issue-Title: // NullpointerException when applying Cleaner to a frameset // // ## Issue-Description: // To reproduce: // // // 1. Create/find a html document of a frameset. // 2. Parse the html. // 3. Create a Cleaner instance and call the clean method with the document from step 2. // 4. NullPointerException // // // Cause: // // In Cleaner.clean(Document) (<https://github.com/jhy/jsoup/blob/master/src/main/java/org/jsoup/safety/Cleaner.java#L43>) the copySafeNodes is called with the document.body(). However, this is null when handling a frameset document. // // // Expected: // // An empty document or perhaps null returned. But not a nullpointerException. // // // // @Test public void handlesFramesets() {
178
26
169
src/test/java/org/jsoup/safety/CleanerTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-154 ## Issue-Title: NullpointerException when applying Cleaner to a frameset ## Issue-Description: To reproduce: 1. Create/find a html document of a frameset. 2. Parse the html. 3. Create a Cleaner instance and call the clean method with the document from step 2. 4. NullPointerException Cause: In Cleaner.clean(Document) (<https://github.com/jhy/jsoup/blob/master/src/main/java/org/jsoup/safety/Cleaner.java#L43>) the copySafeNodes is called with the document.body(). However, this is null when handling a frameset document. Expected: An empty document or perhaps null returned. But not a nullpointerException. ``` You are a professional Java test case writer, please create a test case named `handlesFramesets` for the issue `Jsoup-154`, utilizing the provided issue report information and the following function signature. ```java @Test public void handlesFramesets() { ```
169
[ "org.jsoup.safety.Cleaner" ]
f8e577863d701f80d266aeb57617bbbd0e10b11eeebb68c8879bf49289a853c6
@Test public void handlesFramesets()
// You are a professional Java test case writer, please create a test case named `handlesFramesets` for the issue `Jsoup-154`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-154 // // ## Issue-Title: // NullpointerException when applying Cleaner to a frameset // // ## Issue-Description: // To reproduce: // // // 1. Create/find a html document of a frameset. // 2. Parse the html. // 3. Create a Cleaner instance and call the clean method with the document from step 2. // 4. NullPointerException // // // Cause: // // In Cleaner.clean(Document) (<https://github.com/jhy/jsoup/blob/master/src/main/java/org/jsoup/safety/Cleaner.java#L43>) the copySafeNodes is called with the document.body(). However, this is null when handling a frameset document. // // // Expected: // // An empty document or perhaps null returned. But not a nullpointerException. // // // //
Jsoup
package org.jsoup.safety; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Document; import org.jsoup.nodes.Entities; import org.jsoup.safety.Whitelist; import org.junit.Test; import static org.junit.Assert.*; /** Tests for the cleaner. @author Jonathan Hedley, jonathan@hedley.net */ public class CleanerTest { @Test public void simpleBehaviourTest() { String h = "<div><p class=foo><a href='http://evil.com'>Hello <b id=bar>there</b>!</a></div>"; String cleanHtml = Jsoup.clean(h, Whitelist.simpleText()); assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml)); } @Test public void simpleBehaviourTest2() { String h = "Hello <b>there</b>!"; String cleanHtml = Jsoup.clean(h, Whitelist.simpleText()); assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml)); } @Test public void basicBehaviourTest() { String h = "<div><p><a href='javascript:sendAllMoney()'>Dodgy</a> <A HREF='HTTP://nice.com'>Nice</a></p><blockquote>Hello</blockquote>"; String cleanHtml = Jsoup.clean(h, Whitelist.basic()); assertEquals("<p><a rel=\"nofollow\">Dodgy</a> <a href=\"http://nice.com\" rel=\"nofollow\">Nice</a></p><blockquote>Hello</blockquote>", TextUtil.stripNewlines(cleanHtml)); } @Test public void basicWithImagesTest() { String h = "<div><p><img src='http://example.com/' alt=Image></p><p><img src='ftp://ftp.example.com'></p></div>"; String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages()); assertEquals("<p><img src=\"http://example.com/\" alt=\"Image\" /></p><p><img /></p>", TextUtil.stripNewlines(cleanHtml)); } @Test public void testRelaxed() { String h = "<h1>Head</h1><table><tr><td>One<td>Two</td></tr></table>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<h1>Head</h1><table><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(cleanHtml)); } @Test public void testDropComments() { String h = "<p>Hello<!-- no --></p>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<p>Hello</p>", cleanHtml); } @Test public void testDropXmlProc() { String h = "<?import namespace=\"xss\"><p>Hello</p>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<p>Hello</p>", cleanHtml); } @Test public void testDropScript() { String h = "<SCRIPT SRC=//ha.ckers.org/.j><SCRIPT>alert(/XSS/.source)</SCRIPT>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("", cleanHtml); } @Test public void testDropImageScript() { String h = "<IMG SRC=\"javascript:alert('XSS')\">"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<img />", cleanHtml); } @Test public void testCleanJavascriptHref() { String h = "<A HREF=\"javascript:document.location='http://www.google.com/'\">XSS</A>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<a>XSS</a>", cleanHtml); } @Test public void testDropsUnknownTags() { String h = "<p><custom foo=true>Test</custom></p>"; String cleanHtml = Jsoup.clean(h, Whitelist.relaxed()); assertEquals("<p>Test</p>", cleanHtml); } @Test public void testHandlesEmptyAttributes() { String h = "<img alt=\"\" src= unknown=''>"; String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages()); assertEquals("<img alt=\"\" />", cleanHtml); } @Test public void testIsValid() { String ok = "<p>Test <b><a href='http://example.com/'>OK</a></b></p>"; String nok1 = "<p><script></script>Not <b>OK</b></p>"; String nok2 = "<p align=right>Test Not <b>OK</b></p>"; assertTrue(Jsoup.isValid(ok, Whitelist.basic())); assertFalse(Jsoup.isValid(nok1, Whitelist.basic())); assertFalse(Jsoup.isValid(nok2, Whitelist.basic())); } @Test public void resolvesRelativeLinks() { String html = "<a href='/foo'>Link</a><img src='/bar'>"; String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages()); assertEquals("<a href=\"http://example.com/foo\" rel=\"nofollow\">Link</a>\n<img src=\"http://example.com/bar\" />", clean); } @Test public void preservesRelatedLinksIfConfigured() { String html = "<a href='/foo'>Link</a><img src='/bar'> <img src='javascript:alert()'>"; String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages().preserveRelativeLinks(true)); assertEquals("<a href=\"/foo\" rel=\"nofollow\">Link</a>\n<img src=\"/bar\" /> \n<img />", clean); } @Test public void dropsUnresolvableRelativeLinks() { String html = "<a href='/foo'>Link</a>"; String clean = Jsoup.clean(html, Whitelist.basic()); assertEquals("<a rel=\"nofollow\">Link</a>", clean); } @Test public void handlesCustomProtocols() { String html = "<img src='cid:12345' /> <img src='data:gzzt' />"; String dropped = Jsoup.clean(html, Whitelist.basicWithImages()); assertEquals("<img /> \n<img />", dropped); String preserved = Jsoup.clean(html, Whitelist.basicWithImages().addProtocols("img", "src", "cid", "data")); assertEquals("<img src=\"cid:12345\" /> \n<img src=\"data:gzzt\" />", preserved); } @Test public void handlesAllPseudoTag() { String html = "<p class='foo' src='bar'><a class='qux'>link</a></p>"; Whitelist whitelist = new Whitelist() .addAttributes(":all", "class") .addAttributes("p", "style") .addTags("p", "a"); String clean = Jsoup.clean(html, whitelist); assertEquals("<p class=\"foo\"><a class=\"qux\">link</a></p>", clean); } @Test public void addsTagOnAttributesIfNotSet() { String html = "<p class='foo' src='bar'>One</p>"; Whitelist whitelist = new Whitelist() .addAttributes("p", "class"); // ^^ whitelist does not have explicit tag add for p, inferred from add attributes. String clean = Jsoup.clean(html, whitelist); assertEquals("<p class=\"foo\">One</p>", clean); } @Test public void supplyOutputSettings() { // test that one can override the default document output settings Document.OutputSettings os = new Document.OutputSettings(); os.prettyPrint(false); os.escapeMode(Entities.EscapeMode.extended); String html = "<div><p>&bernou;</p></div>"; String customOut = Jsoup.clean(html, "http://foo.com/", Whitelist.relaxed(), os); String defaultOut = Jsoup.clean(html, "http://foo.com/", Whitelist.relaxed()); assertNotSame(defaultOut, customOut); assertEquals("<div><p>&bernou;</p></div>", customOut); assertEquals("<div>\n" + " <p>ℬ</p>\n" + "</div>", defaultOut); os.charset("ASCII"); os.escapeMode(Entities.EscapeMode.base); String customOut2 = Jsoup.clean(html, "http://foo.com/", Whitelist.relaxed(), os); assertEquals("<div><p>&#8492;</p></div>", customOut2); } @Test public void handlesFramesets() { String dirty = "<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\" /><frame src=\"foo\" /></frameset></html>"; String clean = Jsoup.clean(dirty, Whitelist.basic()); assertEquals("", clean); // nothing good can come out of that Document dirtyDoc = Jsoup.parse(dirty); Document cleanDoc = new Cleaner(Whitelist.basic()).clean(dirtyDoc); assertFalse(cleanDoc == null); assertEquals(0, cleanDoc.body().childNodes().size()); } }
@Test public void fallbackToUtfIfCantEncode() throws IOException { // that charset can't be encoded, so make sure we flip to utf String in = "<html><meta charset=\"ISO-2022-CN\"/>One</html>"; Document doc = Jsoup.parse(new ByteArrayInputStream(in.getBytes()), null, ""); assertEquals("UTF-8", doc.charset().name()); assertEquals("One", doc.text()); String html = doc.outerHtml(); assertEquals("<html><head><meta charset=\"UTF-8\"></head><body>One</body></html>", TextUtil.stripNewlines(html)); }
org.jsoup.parser.HtmlParserTest::fallbackToUtfIfCantEncode
src/test/java/org/jsoup/parser/HtmlParserTest.java
1,211
src/test/java/org/jsoup/parser/HtmlParserTest.java
fallbackToUtfIfCantEncode
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.CDataNode; import org.jsoup.nodes.Comment; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Entities; import org.jsoup.nodes.FormElement; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import org.junit.Ignore; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** Tests for the Parser @author Jonathan Hedley, jonathan@hedley.net */ public class HtmlParserTest { @Test public void parsesSimpleDocument() { String html = "<html><head><title>First!</title></head><body><p>First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); Element img = p.child(0); assertEquals("foo.png", img.attr("src")); assertEquals("img", img.tagName()); } @Test public void parsesRoughAttributes() { String html = "<html><head><title>First!</title></head><body><p class=\"foo > bar\">First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); assertEquals("foo > bar", p.attr("class")); } @Test public void parsesQuiteRoughAttributes() { String html = "<p =a>One<a <p>Something</p>Else"; // this gets a <p> with attr '=a' and an <a tag with an attribue named '<p'; and then auto-recreated Document doc = Jsoup.parse(html); assertEquals("<p =a>One<a <p>Something</a></p>\n" + "<a <p>Else</a>", doc.body().html()); doc = Jsoup.parse("<p .....>"); assertEquals("<p .....></p>", doc.body().html()); } @Test public void parsesComments() { String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --><p>Hello</p></body></html>"; Document doc = Jsoup.parse(html); Element body = doc.body(); Comment comment = (Comment) body.childNode(1); // comment should not be sub of img, as it's an empty tag assertEquals(" <table><tr><td></table> ", comment.getData()); Element p = body.child(1); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); } @Test public void parsesUnterminatedComments() { String html = "<p>Hello<!-- <tr><td>"; Document doc = Jsoup.parse(html); Element p = doc.getElementsByTag("p").get(0); assertEquals("Hello", p.text()); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); Comment comment = (Comment) p.childNode(1); assertEquals(" <tr><td>", comment.getData()); } @Test public void dropsUnterminatedTag() { // jsoup used to parse this to <p>, but whatwg, webkit will drop. String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(0, doc.getElementsByTag("p").size()); assertEquals("", doc.text()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); assertEquals("", doc.text()); } @Test public void dropsUnterminatedAttribute() { // jsoup used to parse this to <p id="foo">, but whatwg, webkit will drop. String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); assertEquals("", doc.text()); } @Test public void parsesUnterminatedTextarea() { // don't parse right to end, but break on <p> Document doc = Jsoup.parse("<body><p><textarea>one<p>two"); Element t = doc.select("textarea").first(); assertEquals("one", t.text()); assertEquals("two", doc.select("p").get(1).text()); } @Test public void parsesUnterminatedOption() { // bit weird this -- browsers and spec get stuck in select until there's a </select> Document doc = Jsoup.parse("<body><p><select><option>One<option>Two</p><p>Three</p>"); Elements options = doc.select("option"); assertEquals(2, options.size()); assertEquals("One", options.first().text()); assertEquals("TwoThree", options.last().text()); } @Test public void testSelectWithOption() { Parser parser = Parser.htmlParser(); parser.setTrackErrors(10); Document document = parser.parseInput("<select><option>Option 1</option></select>", "http://jsoup.org"); assertEquals(0, parser.getErrors().size()); } @Test public void testSpaceAfterTag() { Document doc = Jsoup.parse("<div > <a name=\"top\"></a ><p id=1 >Hello</p></div>"); assertEquals("<div> <a name=\"top\"></a><p id=\"1\">Hello</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void createsDocumentStructure() { String html = "<meta name=keywords /><link rel=stylesheet /><title>jsoup</title><p>Hello world</p>"; Document doc = Jsoup.parse(html); Element head = doc.head(); Element body = doc.body(); assertEquals(1, doc.children().size()); // root node: contains html node assertEquals(2, doc.child(0).children().size()); // html node: head and body assertEquals(3, head.children().size()); assertEquals(1, body.children().size()); assertEquals("keywords", head.getElementsByTag("meta").get(0).attr("name")); assertEquals(0, body.getElementsByTag("meta").size()); assertEquals("jsoup", doc.title()); assertEquals("Hello world", body.text()); assertEquals("Hello world", body.children().get(0).text()); } @Test public void createsStructureFromBodySnippet() { // the bar baz stuff naturally goes into the body, but the 'foo' goes into root, and the normalisation routine // needs to move into the start of the body String html = "foo <b>bar</b> baz"; Document doc = Jsoup.parse(html); assertEquals("foo bar baz", doc.text()); } @Test public void handlesEscapedData() { String html = "<div title='Surf &amp; Turf'>Reef &amp; Beef</div>"; Document doc = Jsoup.parse(html); Element div = doc.getElementsByTag("div").get(0); assertEquals("Surf & Turf", div.attr("title")); assertEquals("Reef & Beef", div.text()); } @Test public void handlesDataOnlyTags() { String t = "<style>font-family: bold</style>"; List<Element> tels = Jsoup.parse(t).getElementsByTag("style"); assertEquals("font-family: bold", tels.get(0).data()); assertEquals("", tels.get(0).text()); String s = "<p>Hello</p><script>obj.insert('<a rel=\"none\" />');\ni++;</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("obj.insert('<a rel=\"none\" />');\ni++;", doc.data()); } @Test public void handlesTextAfterData() { String h = "<html><body>pre <script>inner</script> aft</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head></head><body>pre <script>inner</script> aft</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesTextArea() { Document doc = Jsoup.parse("<textarea>Hello</textarea>"); Elements els = doc.select("textarea"); assertEquals("Hello", els.text()); assertEquals("Hello", els.val()); } @Test public void preservesSpaceInTextArea() { // preserve because the tag is marked as preserve white space Document doc = Jsoup.parse("<textarea>\n\tOne\n\tTwo\n\tThree\n</textarea>"); String expect = "One\n\tTwo\n\tThree"; // the leading and trailing spaces are dropped as a convenience to authors Element el = doc.select("textarea").first(); assertEquals(expect, el.text()); assertEquals(expect, el.val()); assertEquals(expect, el.html()); assertEquals("<textarea>\n\t" + expect + "\n</textarea>", el.outerHtml()); // but preserved in round-trip html } @Test public void preservesSpaceInScript() { // preserve because it's content is a data node Document doc = Jsoup.parse("<script>\nOne\n\tTwo\n\tThree\n</script>"); String expect = "\nOne\n\tTwo\n\tThree\n"; Element el = doc.select("script").first(); assertEquals(expect, el.data()); assertEquals("One\n\tTwo\n\tThree", el.html()); assertEquals("<script>" + expect + "</script>", el.outerHtml()); } @Test public void doesNotCreateImplicitLists() { // old jsoup used to wrap this in <ul>, but that's not to spec String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should NOT have created a default ul. assertEquals(0, ol.size()); Elements lis = doc.select("li"); assertEquals(2, lis.size()); assertEquals("body", lis.first().parent().tagName()); // no fiddling with non-implicit lists String h2 = "<ol><li><p>Point the first<li><p>Point the second"; Document doc2 = Jsoup.parse(h2); assertEquals(0, doc2.select("ul").size()); assertEquals(1, doc2.select("ol").size()); assertEquals(2, doc2.select("ol li").size()); assertEquals(2, doc2.select("ol li p").size()); assertEquals(1, doc2.select("ol li").get(0).children().size()); // one p in first li } @Test public void discardsNakedTds() { // jsoup used to make this into an implicit table; but browsers make it into a text run String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("Hello<p>There</p><p>now</p>", TextUtil.stripNewlines(doc.body().html())); // <tbody> is introduced if no implicitly creating table, but allows tr to be directly under table } @Test public void handlesNestedImplicitTable() { Document doc = Jsoup.parse("<table><td>1</td></tr> <td>2</td></tr> <td> <table><td>3</td> <td>4</td></table> <tr><td>5</table>"); assertEquals("<table><tbody><tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td> <table><tbody><tr><td>3</td> <td>4</td></tr></tbody></table> </td></tr><tr><td>5</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesWhatWgExpensesTableExample() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/tabular-data.html#examples-0 Document doc = Jsoup.parse("<table> <colgroup> <col> <colgroup> <col> <col> <col> <thead> <tr> <th> <th>2008 <th>2007 <th>2006 <tbody> <tr> <th scope=rowgroup> Research and development <td> $ 1,109 <td> $ 782 <td> $ 712 <tr> <th scope=row> Percentage of net sales <td> 3.4% <td> 3.3% <td> 3.7% <tbody> <tr> <th scope=rowgroup> Selling, general, and administrative <td> $ 3,761 <td> $ 2,963 <td> $ 2,433 <tr> <th scope=row> Percentage of net sales <td> 11.6% <td> 12.3% <td> 12.6% </table>"); assertEquals("<table> <colgroup> <col> </colgroup><colgroup> <col> <col> <col> </colgroup><thead> <tr> <th> </th><th>2008 </th><th>2007 </th><th>2006 </th></tr></thead><tbody> <tr> <th scope=\"rowgroup\"> Research and development </th><td> $ 1,109 </td><td> $ 782 </td><td> $ 712 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 3.4% </td><td> 3.3% </td><td> 3.7% </td></tr></tbody><tbody> <tr> <th scope=\"rowgroup\"> Selling, general, and administrative </th><td> $ 3,761 </td><td> $ 2,963 </td><td> $ 2,433 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 11.6% </td><td> 12.3% </td><td> 12.6% </td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesTbodyTable() { Document doc = Jsoup.parse("<html><head></head><body><table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table></body></html>"); assertEquals("<table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesImplicitCaptionClose() { Document doc = Jsoup.parse("<table><caption>A caption<td>One<td>Two"); assertEquals("<table><caption>A caption</caption><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void noTableDirectInTable() { Document doc = Jsoup.parse("<table> <td>One <td><table><td>Two</table> <table><td>Three"); assertEquals("<table> <tbody><tr><td>One </td><td><table><tbody><tr><td>Two</td></tr></tbody></table> <table><tbody><tr><td>Three</td></tr></tbody></table></td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void ignoresDupeEndTrTag() { Document doc = Jsoup.parse("<table><tr><td>One</td><td><table><tr><td>Two</td></tr></tr></table></td><td>Three</td></tr></table>"); // two </tr></tr>, must ignore or will close table assertEquals("<table><tbody><tr><td>One</td><td><table><tbody><tr><td>Two</td></tr></tbody></table></td><td>Three</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { // only listen to the first base href String h = "<a href=1>#</a><base href='/2/'><a href='3'>#</a><base href='http://bar'><a href=/4>#</a>"; Document doc = Jsoup.parse(h, "http://foo/"); assertEquals("http://foo/2/", doc.baseUri()); // gets set once, so doc and descendants have first only Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/2/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://foo/2/", anchors.get(2).baseUri()); assertEquals("http://foo/2/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://foo/4", anchors.get(2).absUrl("href")); } @Test public void handlesProtocolRelativeUrl() { String base = "https://example.com/"; String html = "<img src='//example.net/img.jpg'>"; Document doc = Jsoup.parse(html, base); Element el = doc.select("img").first(); assertEquals("https://example.net/img.jpg", el.absUrl("src")); } @Test public void handlesCdata() { // todo: as this is html namespace, should actually treat as bogus comment, not cdata. keep as cdata for now String h = "<div id=1><![CDATA[<html>\n <foo><&amp;]]></div>"; // the &amp; in there should remain literal Document doc = Jsoup.parse(h); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node } @Test public void roundTripsCdata() { String h = "<div id=1><![CDATA[\n<html>\n <foo><&amp;]]></div>"; Document doc = Jsoup.parse(h); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&amp;]]>\n</div>", div.outerHtml()); CDataNode cdata = (CDataNode) div.textNodes().get(0); assertEquals("\n<html>\n <foo><&amp;", cdata.text()); } @Test public void handlesCdataAcrossBuffer() { StringBuilder sb = new StringBuilder(); while (sb.length() <= CharacterReader.maxBufferLen) { sb.append("A suitable amount of CData.\n"); } String cdata = sb.toString(); String h = "<div><![CDATA[" + cdata + "]]></div>"; Document doc = Jsoup.parse(h); Element div = doc.selectFirst("div"); CDataNode node = (CDataNode) div.textNodes().get(0); assertEquals(cdata, node.text()); } @Test public void handlesCdataInScript() { String html = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>"; Document doc = Jsoup.parse(html); String data = "//<![CDATA[\n\n foo();\n//]]>"; Element script = doc.selectFirst("script"); assertEquals("", script.text()); // won't be parsed as cdata because in script data section assertEquals(data, script.data()); assertEquals(html, script.outerHtml()); DataNode dataNode = (DataNode) script.childNode(0); assertEquals(data, dataNode.getWholeData()); // see - not a cdata node, because in script. contrast with XmlTreeBuilder - will be cdata. } @Test public void handlesUnclosedCdataAtEOF() { // https://github.com/jhy/jsoup/issues/349 would crash, as character reader would try to seek past EOF String h = "<![CDATA[]]"; Document doc = Jsoup.parse(h); assertEquals(1, doc.body().childNodeSize()); } @Test public void handleCDataInText() { String h = "<p>One <![CDATA[Two <&]]> Three</p>"; Document doc = Jsoup.parse(h); Element p = doc.selectFirst("p"); List<Node> nodes = p.childNodes(); assertEquals("One ", ((TextNode) nodes.get(0)).getWholeText()); assertEquals("Two <&", ((TextNode) nodes.get(1)).getWholeText()); assertEquals("Two <&", ((CDataNode) nodes.get(1)).getWholeText()); assertEquals(" Three", ((TextNode) nodes.get(2)).getWholeText()); assertEquals(h, p.outerHtml()); } @Test public void cdataNodesAreTextNodes() { String h = "<p>One <![CDATA[ Two <& ]]> Three</p>"; Document doc = Jsoup.parse(h); Element p = doc.selectFirst("p"); List<TextNode> nodes = p.textNodes(); assertEquals("One ", nodes.get(0).text()); assertEquals(" Two <& ", nodes.get(1).text()); assertEquals(" Three", nodes.get(2).text()); } @Test public void handlesInvalidStartTags() { String h = "<div>Hello < There <&amp;></div>"; // parse to <div {#text=Hello < There <&>}> Document doc = Jsoup.parse(h); assertEquals("Hello < There <&>", doc.select("div").first().text()); } @Test public void handlesUnknownTags() { String h = "<div><foo title=bar>Hello<foo title=qux>there</foo></div>"; Document doc = Jsoup.parse(h); Elements foos = doc.select("foo"); assertEquals(2, foos.size()); assertEquals("bar", foos.first().attr("title")); assertEquals("qux", foos.last().attr("title")); assertEquals("there", foos.last().text()); } @Test public void handlesUnknownInlineTags() { String h = "<p><cust>Test</cust></p><p><cust><cust>Test</cust></cust></p>"; Document doc = Jsoup.parseBodyFragment(h); String out = doc.body().html(); assertEquals(h, TextUtil.stripNewlines(out)); } @Test public void parsesBodyFragment() { String h = "<!-- comment --><p><a href='foo'>One</a></p>"; Document doc = Jsoup.parseBodyFragment(h, "http://example.com"); assertEquals("<body><!-- comment --><p><a href=\"foo\">One</a></p></body>", TextUtil.stripNewlines(doc.body().outerHtml())); assertEquals("http://example.com/foo", doc.select("a").first().absUrl("href")); } @Test public void handlesUnknownNamespaceTags() { // note that the first foo:bar should not really be allowed to be self closing, if parsed in html mode. String h = "<foo:bar id='1' /><abc:def id=2>Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>"; Document doc = Jsoup.parse(h); assertEquals("<foo:bar id=\"1\" /><abc:def id=\"2\">Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesKnownEmptyBlocks() { // if a known tag, allow self closing outside of spec, but force an end tag. unknown tags can be self closing. String h = "<div id='1' /><script src='/foo' /><div id=2><img /><img></div><a id=3 /><i /><foo /><foo>One</foo> <hr /> hr text <hr> hr text two"; Document doc = Jsoup.parse(h); assertEquals("<div id=\"1\"></div><script src=\"/foo\"></script><div id=\"2\"><img><img></div><a id=\"3\"></a><i></i><foo /><foo>One</foo> <hr> hr text <hr> hr text two", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesKnownEmptyNoFrames() { String h = "<html><head><noframes /><meta name=foo></head><body>One</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><noframes></noframes><meta name=\"foo\"></head><body>One</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesKnownEmptyStyle() { String h = "<html><head><style /><meta name=foo></head><body>One</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><style></style><meta name=\"foo\"></head><body>One</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesKnownEmptyTitle() { String h = "<html><head><title /><meta name=foo></head><body>One</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><title></title><meta name=\"foo\"></head><body>One</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesKnownEmptyIframe() { String h = "<p>One</p><iframe id=1 /><p>Two"; Document doc = Jsoup.parse(h); assertEquals("<html><head></head><body><p>One</p><iframe id=\"1\"></iframe><p>Two</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesSolidusAtAttributeEnd() { // this test makes sure [<a href=/>link</a>] is parsed as [<a href="/">link</a>], not [<a href="" /><a>link</a>] String h = "<a href=/>link</a>"; Document doc = Jsoup.parse(h); assertEquals("<a href=\"/\">link</a>", doc.body().html()); } @Test public void handlesMultiClosingBody() { String h = "<body><p>Hello</body><p>there</p></body></body></html><p>now"; Document doc = Jsoup.parse(h); assertEquals(3, doc.select("p").size()); assertEquals(3, doc.body().children().size()); } @Test public void handlesUnclosedDefinitionLists() { // jsoup used to create a <dl>, but that's not to spec String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(0, doc.select("dl").size()); // no auto dl assertEquals(4, doc.select("dt, dd").size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @Test public void handlesBlocksInDefinitions() { // per the spec, dt and dd are inline, but in practise are block String h = "<dl><dt><div id=1>Term</div></dt><dd><div id=2>Def</div></dd></dl>"; Document doc = Jsoup.parse(h); assertEquals("dt", doc.select("#1").first().parent().tagName()); assertEquals("dd", doc.select("#2").first().parent().tagName()); assertEquals("<dl><dt><div id=\"1\">Term</div></dt><dd><div id=\"2\">Def</div></dd></dl>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesFrames() { String h = "<html><head><script></script><noscript></noscript></head><frameset><frame src=foo></frame><frame src=foo></frameset></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\"><frame src=\"foo\"></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body auto vivification } @Test public void ignoresContentAfterFrameset() { String h = "<html><head><title>One</title></head><frameset><frame /><frame /></frameset><table></table></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><title>One</title></head><frameset><frame><frame></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body, no table. No crash! } @Test public void handlesJavadocFont() { String h = "<TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A>&nbsp;</TD>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("Deprecated", a.text()); assertEquals("font", a.child(0).tagName()); assertEquals("b", a.child(0).child(0).tagName()); } @Test public void handlesBaseWithoutHref() { String h = "<head><base target='_blank'></head><body><a href=/foo>Test</a></body>"; Document doc = Jsoup.parse(h, "http://example.com/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://example.com/foo", a.attr("abs:href")); } @Test public void normalisesDocument() { String h = "<!doctype html>One<html>Two<head>Three<link></head>Four<body>Five </body>Six </html>Seven "; Document doc = Jsoup.parse(h); assertEquals("<!doctype html><html><head></head><body>OneTwoThree<link>FourFive Six Seven </body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesEmptyDocument() { Document doc = Jsoup.parse(""); assertEquals("<html><head></head><body></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesHeadlessBody() { Document doc = Jsoup.parse("<html><body><span class=\"foo\">bar</span>"); assertEquals("<html><head></head><body><span class=\"foo\">bar</span></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisedBodyAfterContent() { Document doc = Jsoup.parse("<font face=Arial><body class=name><div>One</div></body></font>"); assertEquals("<html><head></head><body class=\"name\"><font face=\"Arial\"><div>One</div></font></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void findsCharsetInMalformedMeta() { String h = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"; // example cited for reason of html5's <meta charset> element Document doc = Jsoup.parse(h); assertEquals("gb2312", doc.select("meta").attr("charset")); } @Test public void testHgroup() { // jsoup used to not allow hroup in h{n}, but that's not in spec, and browsers are OK Document doc = Jsoup.parse("<h1>Hello <h2>There <hgroup><h1>Another<h2>headline</hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup>"); assertEquals("<h1>Hello </h1><h2>There <hgroup><h1>Another</h1><h2>headline</h2></hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup></h2>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def>There</abc-def>"); assertEquals("<abc_def id=\"1\">Hello</abc_def> <abc-def>There</abc-def>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHeaderContents() { // h* tags (h1 .. h9) in browsers can handle any internal content other than other h*. which is not per any // spec, which defines them as containing phrasing content only. so, reality over theory. Document doc = Jsoup.parse("<h1>Hello <div>There</div> now</h1> <h2>More <h3>Content</h3></h2>"); assertEquals("<h1>Hello <div>There</div> now</h1> <h2>More </h2><h3>Content</h3>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testSpanContents() { // like h1 tags, the spec says SPAN is phrasing only, but browsers and publisher treat span as a block tag Document doc = Jsoup.parse("<span>Hello <div>there</div> <span>now</span></span>"); assertEquals("<span>Hello <div>there</div> <span>now</span></span>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testNoImagesInNoScriptInHead() { // jsoup used to allow, but against spec if parsing with noscript Document doc = Jsoup.parse("<html><head><noscript><img src='foo'></noscript></head><body><p>Hello</p></body></html>"); assertEquals("<html><head><noscript>&lt;img src=\"foo\"&gt;</noscript></head><body><p>Hello</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testAFlowContents() { // html5 has <a> as either phrasing or block Document doc = Jsoup.parse("<a>Hello <div>there</div> <span>now</span></a>"); assertEquals("<a>Hello <div>there</div> <span>now</span></a>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testFontFlowContents() { // html5 has no definition of <font>; often used as flow Document doc = Jsoup.parse("<font>Hello <div>there</div> <span>now</span></font>"); assertEquals("<font>Hello <div>there</div> <span>now</span></font>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesMisnestedTagsBI() { // whatwg: <b><i></b></i> String h = "<p>1<b>2<i>3</b>4</i>5</p>"; Document doc = Jsoup.parse(h); assertEquals("<p>1<b>2<i>3</i></b><i>4</i>5</p>", doc.body().html()); // adoption agency on </b>, reconstruction of formatters on 4. } @Test public void handlesMisnestedTagsBP() { // whatwg: <b><p></b></p> String h = "<b>1<p>2</b>3</p>"; Document doc = Jsoup.parse(h); assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html()); } @Ignore // todo: test case for https://github.com/jhy/jsoup/issues/845. Doesn't work yet. @Test public void handlesMisnestedAInDivs() { String h = "<a href='#1'><div><div><a href='#2'>child</a</div</div></a>"; String w = "<a href=\"#1\"></a><div><a href=\"#1\"></a><div><a href=\"#1\"></a><a href=\"#2\">child</a></div></div>"; Document doc = Jsoup.parse(h); assertEquals( StringUtil.normaliseWhitespace(w), StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void handlesUnexpectedMarkupInTables() { // whatwg - tests markers in active formatting (if they didn't work, would get in in table) // also tests foster parenting String h = "<table><b><tr><td>aaa</td></tr>bbb</table>ccc"; Document doc = Jsoup.parse(h); assertEquals("<b></b><b>bbb</b><table><tbody><tr><td>aaa</td></tr></tbody></table><b>ccc</b>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesUnclosedFormattingElements() { // whatwg: formatting elements get collected and applied, but excess elements are thrown away String h = "<!DOCTYPE html>\n" + "<p><b class=x><b class=x><b><b class=x><b class=x><b>X\n" + "<p>X\n" + "<p><b><b class=x><b>X\n" + "<p></b></b></b></b></b></b>X"; Document doc = Jsoup.parse(h); doc.outputSettings().indentAmount(0); String want = "<!doctype html>\n" + "<html>\n" + "<head></head>\n" + "<body>\n" + "<p><b class=\"x\"><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b><b><b class=\"x\"><b>X </b></b></b></b></b></b></b></b></p>\n" + "<p>X</p>\n" + "</body>\n" + "</html>"; assertEquals(want, doc.html()); } @Test public void handlesUnclosedAnchors() { String h = "<a href='http://example.com/'>Link<p>Error link</a>"; Document doc = Jsoup.parse(h); String want = "<a href=\"http://example.com/\">Link</a>\n<p><a href=\"http://example.com/\">Error link</a></p>"; assertEquals(want, doc.body().html()); } @Test public void reconstructFormattingElements() { // tests attributes and multi b String h = "<p><b class=one>One <i>Two <b>Three</p><p>Hello</p>"; Document doc = Jsoup.parse(h); assertEquals("<p><b class=\"one\">One <i>Two <b>Three</b></i></b></p>\n<p><b class=\"one\"><i><b>Hello</b></i></b></p>", doc.body().html()); } @Test public void reconstructFormattingElementsInTable() { // tests that tables get formatting markers -- the <b> applies outside the table and does not leak in, // and the <i> inside the table and does not leak out. String h = "<p><b>One</p> <table><tr><td><p><i>Three<p>Four</i></td></tr></table> <p>Five</p>"; Document doc = Jsoup.parse(h); String want = "<p><b>One</b></p>\n" + "<b> \n" + " <table>\n" + " <tbody>\n" + " <tr>\n" + " <td><p><i>Three</i></p><p><i>Four</i></p></td>\n" + " </tr>\n" + " </tbody>\n" + " </table> <p>Five</p></b>"; assertEquals(want, doc.body().html()); } @Test public void commentBeforeHtml() { String h = "<!-- comment --><!-- comment 2 --><p>One</p>"; Document doc = Jsoup.parse(h); assertEquals("<!-- comment --><!-- comment 2 --><html><head></head><body><p>One</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void emptyTdTag() { String h = "<table><tr><td>One</td><td id='2' /></tr></table>"; Document doc = Jsoup.parse(h); assertEquals("<td>One</td>\n<td id=\"2\"></td>", doc.select("tr").first().html()); } @Test public void handlesSolidusInA() { // test for bug #66 String h = "<a class=lp href=/lib/14160711/>link text</a>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("link text", a.text()); assertEquals("/lib/14160711/", a.attr("href")); } @Test public void handlesSpanInTbody() { // test for bug 64 String h = "<table><tbody><span class='1'><tr><td>One</td></tr><tr><td>Two</td></tr></span></tbody></table>"; Document doc = Jsoup.parse(h); assertEquals(doc.select("span").first().children().size(), 0); // the span gets closed assertEquals(doc.select("table").size(), 1); // only one table } @Test public void handlesUnclosedTitleAtEof() { assertEquals("Data", Jsoup.parse("<title>Data").title()); assertEquals("Data<", Jsoup.parse("<title>Data<").title()); assertEquals("Data</", Jsoup.parse("<title>Data</").title()); assertEquals("Data</t", Jsoup.parse("<title>Data</t").title()); assertEquals("Data</ti", Jsoup.parse("<title>Data</ti").title()); assertEquals("Data", Jsoup.parse("<title>Data</title>").title()); assertEquals("Data", Jsoup.parse("<title>Data</title >").title()); } @Test public void handlesUnclosedTitle() { Document one = Jsoup.parse("<title>One <b>Two <b>Three</TITLE><p>Test</p>"); // has title, so <b> is plain text assertEquals("One <b>Two <b>Three", one.title()); assertEquals("Test", one.select("p").first().text()); Document two = Jsoup.parse("<title>One<b>Two <p>Test</p>"); // no title, so <b> causes </title> breakout assertEquals("One", two.title()); assertEquals("<b>Two <p>Test</p></b>", two.body().html()); } @Test public void handlesUnclosedScriptAtEof() { assertEquals("Data", Jsoup.parse("<script>Data").select("script").first().data()); assertEquals("Data<", Jsoup.parse("<script>Data<").select("script").first().data()); assertEquals("Data</sc", Jsoup.parse("<script>Data</sc").select("script").first().data()); assertEquals("Data</-sc", Jsoup.parse("<script>Data</-sc").select("script").first().data()); assertEquals("Data</sc-", Jsoup.parse("<script>Data</sc-").select("script").first().data()); assertEquals("Data</sc--", Jsoup.parse("<script>Data</sc--").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script>").select("script").first().data()); assertEquals("Data</script", Jsoup.parse("<script>Data</script").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script ").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"p").select("script").first().data()); } @Test public void handlesUnclosedRawtextAtEof() { assertEquals("Data", Jsoup.parse("<style>Data").select("style").first().data()); assertEquals("Data</st", Jsoup.parse("<style>Data</st").select("style").first().data()); assertEquals("Data", Jsoup.parse("<style>Data</style>").select("style").first().data()); assertEquals("Data</style", Jsoup.parse("<style>Data</style").select("style").first().data()); assertEquals("Data</-style", Jsoup.parse("<style>Data</-style").select("style").first().data()); assertEquals("Data</style-", Jsoup.parse("<style>Data</style-").select("style").first().data()); assertEquals("Data</style--", Jsoup.parse("<style>Data</style--").select("style").first().data()); } @Test public void noImplicitFormForTextAreas() { // old jsoup parser would create implicit forms for form children like <textarea>, but no more Document doc = Jsoup.parse("<textarea>One</textarea>"); assertEquals("<textarea>One</textarea>", doc.body().html()); } @Test public void handlesEscapedScript() { Document doc = Jsoup.parse("<script><!-- one <script>Blah</script> --></script>"); assertEquals("<!-- one <script>Blah</script> -->", doc.select("script").first().data()); } @Test public void handles0CharacterAsText() { Document doc = Jsoup.parse("0<p>0</p>"); assertEquals("0\n<p>0</p>", doc.body().html()); } @Test public void handlesNullInData() { Document doc = Jsoup.parse("<p id=\u0000>Blah \u0000</p>"); assertEquals("<p id=\"\uFFFD\">Blah \u0000</p>", doc.body().html()); // replaced in attr, NOT replaced in data } @Test public void handlesNullInComments() { Document doc = Jsoup.parse("<body><!-- \u0000 \u0000 -->"); assertEquals("<!-- \uFFFD \uFFFD -->", doc.body().html()); } @Test public void handlesNewlinesAndWhitespaceInTag() { Document doc = Jsoup.parse("<a \n href=\"one\" \r\n id=\"two\" \f >"); assertEquals("<a href=\"one\" id=\"two\"></a>", doc.body().html()); } @Test public void handlesWhitespaceInoDocType() { String html = "<!DOCTYPE html\r\n" + " PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n" + " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; Document doc = Jsoup.parse(html); assertEquals("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">", doc.childNode(0).outerHtml()); } @Test public void tracksErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(500); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(5, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); assertEquals("50: Tag cannot be self closing; not a void tag", errors.get(3).toString()); assertEquals("61: Unexpectedly reached end of file (EOF) in input state [TagName]", errors.get(4).toString()); } @Test public void tracksLimitedErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(3); Document doc = parser.parseInput(html, "http://example.com"); List<ParseError> errors = parser.getErrors(); assertEquals(3, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); } @Test public void noErrorsByDefault() { String html = "<p>One</p href='no'>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser(); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(0, errors.size()); } @Test public void handlesCommentsInTable() { String html = "<table><tr><td>text</td><!-- Comment --></tr></table>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<html><head></head><body><table><tbody><tr><td>text</td><!-- Comment --></tr></tbody></table></body></html>", TextUtil.stripNewlines(node.outerHtml())); } @Test public void handlesQuotesInCommentsInScripts() { String html = "<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>", node.body().html()); } @Test public void handleNullContextInParseFragment() { String html = "<ol><li>One</li></ol><p>Two</p>"; List<Node> nodes = Parser.parseFragment(html, null, "http://example.com/"); assertEquals(1, nodes.size()); // returns <html> node (not document) -- no context means doc gets created assertEquals("html", nodes.get(0).nodeName()); assertEquals("<html> <head></head> <body> <ol> <li>One</li> </ol> <p>Two</p> </body> </html>", StringUtil.normaliseWhitespace(nodes.get(0).outerHtml())); } @Test public void doesNotFindShortestMatchingEntity() { // previous behaviour was to identify a possible entity, then chomp down the string until a match was found. // (as defined in html5.) However in practise that lead to spurious matches against the author's intent. String html = "One &clubsuite; &clubsuit;"; Document doc = Jsoup.parse(html); assertEquals(StringUtil.normaliseWhitespace("One &amp;clubsuite; ♣"), doc.body().html()); } @Test public void relaxedBaseEntityMatchAndStrictExtendedMatch() { // extended entities need a ; at the end to match, base does not String html = "&amp &quot &reg &icy &hopf &icy; &hopf;"; Document doc = Jsoup.parse(html); doc.outputSettings().escapeMode(Entities.EscapeMode.extended).charset("ascii"); // modifies output only to clarify test assertEquals("&amp; \" &reg; &amp;icy &amp;hopf &icy; &hopf;", doc.body().html()); } @Test public void handlesXmlDeclarationAsBogusComment() { String html = "<?xml encoding='UTF-8' ?><body>One</body>"; Document doc = Jsoup.parse(html); assertEquals("<!--?xml encoding='UTF-8' ?--> <html> <head></head> <body> One </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesTagsInTextarea() { String html = "<textarea><p>Jsoup</p></textarea>"; Document doc = Jsoup.parse(html); assertEquals("<textarea>&lt;p&gt;Jsoup&lt;/p&gt;</textarea>", doc.body().html()); } // form tests @Test public void createsFormElements() { String html = "<body><form><input id=1><input id=2></form></body>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); } @Test public void associatedFormControlsWithDisjointForms() { // form gets closed, isn't parent of controls String html = "<table><tr><form><input type=hidden id=1><td><input type=text id=2></td><tr></table>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); assertEquals("<table><tbody><tr><form></form><input type=\"hidden\" id=\"1\"><td><input type=\"text\" id=\"2\"></td></tr><tr></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesInputInTable() { String h = "<body>\n" + "<input type=\"hidden\" name=\"a\" value=\"\">\n" + "<table>\n" + "<input type=\"hidden\" name=\"b\" value=\"\" />\n" + "</table>\n" + "</body>"; Document doc = Jsoup.parse(h); assertEquals(1, doc.select("table input").size()); assertEquals(2, doc.select("input").size()); } @Test public void convertsImageToImg() { // image to img, unless in a svg. old html cruft. String h = "<body><image><svg><image /></svg></body>"; Document doc = Jsoup.parse(h); assertEquals("<img>\n<svg>\n <image />\n</svg>", doc.body().html()); } @Test public void handlesInvalidDoctypes() { // would previously throw invalid name exception on empty doctype Document doc = Jsoup.parse("<!DOCTYPE>"); assertEquals( "<!doctype> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE><html><p>Foo</p></html>"); assertEquals( "<!doctype> <html> <head></head> <body> <p>Foo</p> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE \u0000>"); assertEquals( "<!doctype �> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesManyChildren() { // Arrange StringBuilder longBody = new StringBuilder(500000); for (int i = 0; i < 25000; i++) { longBody.append(i).append("<br>"); } // Act long start = System.currentTimeMillis(); Document doc = Parser.parseBodyFragment(longBody.toString(), ""); // Assert assertEquals(50000, doc.body().childNodeSize()); assertTrue(System.currentTimeMillis() - start < 1000); } @Test public void handlesDeepStack() {} // Defects4J: flaky method // @Test public void handlesDeepStack() { // // inspired by http://sv.stargate.wikia.com/wiki/M2J and https://github.com/jhy/jsoup/issues/955 // // I didn't put it in the integration tests, because explorer and intellij kept dieing trying to preview/index it // // // Arrange // StringBuilder longBody = new StringBuilder(500000); // for (int i = 0; i < 25000; i++) { // longBody.append(i).append("<dl><dd>"); // } // for (int i = 0; i < 25000; i++) { // longBody.append(i).append("</dd></dl>"); // } // // // Act // long start = System.currentTimeMillis(); // Document doc = Parser.parseBodyFragment(longBody.toString(), ""); // // // Assert // assertEquals(2, doc.body().childNodeSize()); // assertEquals(25000, doc.select("dd").size()); // assertTrue(System.currentTimeMillis() - start < 2000); // } @Test public void testInvalidTableContents() throws IOException { File in = ParseTest.getFile("/htmltests/table-invalid-elements.html"); Document doc = Jsoup.parse(in, "UTF-8"); doc.outputSettings().prettyPrint(true); String rendered = doc.toString(); int endOfEmail = rendered.indexOf("Comment"); int guarantee = rendered.indexOf("Why am I here?"); assertTrue("Comment not found", endOfEmail > -1); assertTrue("Search text not found", guarantee > -1); assertTrue("Search text did not come after comment", guarantee > endOfEmail); } @Test public void testNormalisesIsIndex() { Document doc = Jsoup.parse("<body><isindex action='/submit'></body>"); String html = doc.outerHtml(); assertEquals("<form action=\"/submit\"> <hr> <label>This is a searchable index. Enter search keywords: <input name=\"isindex\"></label> <hr> </form>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void testReinsertionModeForThCelss() { String body = "<body> <table> <tr> <th> <table><tr><td></td></tr></table> <div> <table><tr><td></td></tr></table> </div> <div></div> <div></div> <div></div> </th> </tr> </table> </body>"; Document doc = Jsoup.parse(body); assertEquals(1, doc.body().children().size()); } @Test public void testUsingSingleQuotesInQueries() { String body = "<body> <div class='main'>hello</div></body>"; Document doc = Jsoup.parse(body); Elements main = doc.select("div[class='main']"); assertEquals("hello", main.text()); } @Test public void testSupportsNonAsciiTags() { String body = "<進捗推移グラフ>Yes</進捗推移グラフ><русский-тэг>Correct</<русский-тэг>"; Document doc = Jsoup.parse(body); Elements els = doc.select("進捗推移グラフ"); assertEquals("Yes", els.text()); els = doc.select("русский-тэг"); assertEquals("Correct", els.text()); } @Test public void testSupportsPartiallyNonAsciiTags() { String body = "<div>Check</divá>"; Document doc = Jsoup.parse(body); Elements els = doc.select("div"); assertEquals("Check", els.text()); } @Test public void testFragment() { // make sure when parsing a body fragment, a script tag at start goes into the body String html = "<script type=\"text/javascript\">console.log('foo');</script>\n" + "<div id=\"somecontent\">some content</div>\n" + "<script type=\"text/javascript\">console.log('bar');</script>"; Document body = Jsoup.parseBodyFragment(html); assertEquals("<script type=\"text/javascript\">console.log('foo');</script> \n" + "<div id=\"somecontent\">\n" + " some content\n" + "</div> \n" + "<script type=\"text/javascript\">console.log('bar');</script>", body.body().html()); } @Test public void testHtmlLowerCase() { String html = "<!doctype HTML><DIV ID=1>One</DIV>"; Document doc = Jsoup.parse(html); assertEquals("<!doctype html> <html> <head></head> <body> <div id=\"1\"> One </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG>One</TaG>"); assertEquals("<tag>One</tag>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void canPreserveTagCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, false)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN id=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG ID=one>One</TaG>"); assertEquals("<TaG id=\"one\">One</TaG>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void canPreserveAttributeCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(false, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <span ID=\"2\"></span> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG ID=one>One</TaG>"); assertEquals("<tag ID=\"one\">One</tag>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void canPreserveBothCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN ID=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG ID=one>One</TaG>"); assertEquals("<TaG ID=\"one\">One</TaG>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void handlesControlCodeInAttributeName() { Document doc = Jsoup.parse("<p><a \06=foo>One</a><a/\06=bar><a foo\06=bar>Two</a></p>"); assertEquals("<p><a>One</a><a></a><a foo=\"bar\">Two</a></p>", doc.body().html()); } @Test public void caseSensitiveParseTree() { String html = "<r><X>A</X><y>B</y></r>"; Parser parser = Parser.htmlParser(); parser.settings(ParseSettings.preserveCase); Document doc = parser.parseInput(html, ""); assertEquals("<r> <X> A </X> <y> B </y> </r>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void caseInsensitiveParseTree() { String html = "<r><X>A</X><y>B</y></r>"; Parser parser = Parser.htmlParser(); Document doc = parser.parseInput(html, ""); assertEquals("<r> <x> A </x> <y> B </y> </r>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void normalizesDiscordantTags() { Document document = Jsoup.parse("<div>test</DIV><p></p>"); assertEquals("<div>\n test\n</div>\n<p></p>", document.body().html()); } @Test public void selfClosingVoidIsNotAnError() { String html = "<p>test<br/>test<br/></p>"; Parser parser = Parser.htmlParser().setTrackErrors(5); parser.parseInput(html, ""); assertEquals(0, parser.getErrors().size()); assertTrue(Jsoup.isValid(html, Whitelist.basic())); String clean = Jsoup.clean(html, Whitelist.basic()); assertEquals("<p>test<br>test<br></p>", clean); } @Test public void selfClosingOnNonvoidIsError() { String html = "<p>test</p><div /><div>Two</div>"; Parser parser = Parser.htmlParser().setTrackErrors(5); parser.parseInput(html, ""); assertEquals(1, parser.getErrors().size()); assertEquals("18: Tag cannot be self closing; not a void tag", parser.getErrors().get(0).toString()); assertFalse(Jsoup.isValid(html, Whitelist.relaxed())); String clean = Jsoup.clean(html, Whitelist.relaxed()); assertEquals("<p>test</p> <div></div> <div> Two </div>", StringUtil.normaliseWhitespace(clean)); } @Test public void testTemplateInsideTable() throws IOException { File in = ParseTest.getFile("/htmltests/table-polymer-template.html"); Document doc = Jsoup.parse(in, "UTF-8"); doc.outputSettings().prettyPrint(true); Elements templates = doc.body().getElementsByTag("template"); for (Element template : templates) { assertTrue(template.childNodes().size() > 1); } } @Test public void testHandlesDeepSpans() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 200; i++) { sb.append("<span>"); } sb.append("<p>One</p>"); Document doc = Jsoup.parse(sb.toString()); assertEquals(200, doc.select("span").size()); assertEquals(1, doc.select("p").size()); } @Test public void commentAtEnd() throws Exception { Document doc = Jsoup.parse("<!"); assertTrue(doc.childNode(0) instanceof Comment); } @Test public void preSkipsFirstNewline() { Document doc = Jsoup.parse("<pre>\n\nOne\nTwo\n</pre>"); Element pre = doc.selectFirst("pre"); assertEquals("One\nTwo", pre.text()); assertEquals("\nOne\nTwo\n", pre.wholeText()); } @Test public void handlesXmlDeclAndCommentsBeforeDoctype() throws IOException { File in = ParseTest.getFile("/htmltests/comments.html"); Document doc = Jsoup.parse(in, "UTF-8"); assertEquals("<!--?xml version=\"1.0\" encoding=\"utf-8\"?--> <!-- so --><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <!-- what --> <html xml:lang=\"en\" lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"> <!-- now --> <head> <!-- then --> <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\"> <title>A Certain Kind of Test</title> </head> <body> <h1>Hello</h1>h1&gt; (There is a UTF8 hidden BOM at the top of this file.) </body> </html>", StringUtil.normaliseWhitespace(doc.html())); assertEquals("A Certain Kind of Test", doc.head().select("title").text()); } @Test public void fallbackToUtfIfCantEncode() throws IOException { // that charset can't be encoded, so make sure we flip to utf String in = "<html><meta charset=\"ISO-2022-CN\"/>One</html>"; Document doc = Jsoup.parse(new ByteArrayInputStream(in.getBytes()), null, ""); assertEquals("UTF-8", doc.charset().name()); assertEquals("One", doc.text()); String html = doc.outerHtml(); assertEquals("<html><head><meta charset=\"UTF-8\"></head><body>One</body></html>", TextUtil.stripNewlines(html)); } }
// You are a professional Java test case writer, please create a test case named `fallbackToUtfIfCantEncode` for the issue `Jsoup-1007`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1007 // // ## Issue-Title: // UnsupportedOperationException thrown for charsets that don't support encoding // // ## Issue-Description: // // ``` // public static void main(String[] args) throws IOException { // // String html = "<html><meta charset=\"ISO-2022-CN\"/></html>"; // // System.out.println( // Jsoup.parse(new ByteArrayInputStream(html.getBytes()), null, "") // ); // // } // // ``` // // throws // // // // ``` // Exception in thread "main" java.lang.UnsupportedOperationException // at sun.nio.cs.ext.ISO2022_CN.newEncoder(ISO2022_CN.java:76) // at org.jsoup.nodes.Document$OutputSettings.prepareEncoder(Document.java:443) // at org.jsoup.nodes.Node$OuterHtmlVisitor.(Node.java:704) // at org.jsoup.nodes.Node.outerHtml(Node.java:573) // at org.jsoup.nodes.Element.html(Element.java:1395) // at org.jsoup.nodes.Element.html(Element.java:1389) // at org.jsoup.nodes.Document.outerHtml(Document.java:195) // at org.jsoup.nodes.Element.toString(Element.java:1422) // at java.lang.String.valueOf(String.java:2982) // at java.io.PrintStream.println(PrintStream.java:821) // // ``` // // // @Test public void fallbackToUtfIfCantEncode() throws IOException {
1,211
82
1,200
src/test/java/org/jsoup/parser/HtmlParserTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-1007 ## Issue-Title: UnsupportedOperationException thrown for charsets that don't support encoding ## Issue-Description: ``` public static void main(String[] args) throws IOException { String html = "<html><meta charset=\"ISO-2022-CN\"/></html>"; System.out.println( Jsoup.parse(new ByteArrayInputStream(html.getBytes()), null, "") ); } ``` throws ``` Exception in thread "main" java.lang.UnsupportedOperationException at sun.nio.cs.ext.ISO2022_CN.newEncoder(ISO2022_CN.java:76) at org.jsoup.nodes.Document$OutputSettings.prepareEncoder(Document.java:443) at org.jsoup.nodes.Node$OuterHtmlVisitor.(Node.java:704) at org.jsoup.nodes.Node.outerHtml(Node.java:573) at org.jsoup.nodes.Element.html(Element.java:1395) at org.jsoup.nodes.Element.html(Element.java:1389) at org.jsoup.nodes.Document.outerHtml(Document.java:195) at org.jsoup.nodes.Element.toString(Element.java:1422) at java.lang.String.valueOf(String.java:2982) at java.io.PrintStream.println(PrintStream.java:821) ``` ``` You are a professional Java test case writer, please create a test case named `fallbackToUtfIfCantEncode` for the issue `Jsoup-1007`, utilizing the provided issue report information and the following function signature. ```java @Test public void fallbackToUtfIfCantEncode() throws IOException { ```
1,200
[ "org.jsoup.helper.DataUtil" ]
f8eb0b3aa2554d42e7ed966329113c8b3b77de3661646f8d80b1ab74d267900e
@Test public void fallbackToUtfIfCantEncode() throws IOException
// You are a professional Java test case writer, please create a test case named `fallbackToUtfIfCantEncode` for the issue `Jsoup-1007`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1007 // // ## Issue-Title: // UnsupportedOperationException thrown for charsets that don't support encoding // // ## Issue-Description: // // ``` // public static void main(String[] args) throws IOException { // // String html = "<html><meta charset=\"ISO-2022-CN\"/></html>"; // // System.out.println( // Jsoup.parse(new ByteArrayInputStream(html.getBytes()), null, "") // ); // // } // // ``` // // throws // // // // ``` // Exception in thread "main" java.lang.UnsupportedOperationException // at sun.nio.cs.ext.ISO2022_CN.newEncoder(ISO2022_CN.java:76) // at org.jsoup.nodes.Document$OutputSettings.prepareEncoder(Document.java:443) // at org.jsoup.nodes.Node$OuterHtmlVisitor.(Node.java:704) // at org.jsoup.nodes.Node.outerHtml(Node.java:573) // at org.jsoup.nodes.Element.html(Element.java:1395) // at org.jsoup.nodes.Element.html(Element.java:1389) // at org.jsoup.nodes.Document.outerHtml(Document.java:195) // at org.jsoup.nodes.Element.toString(Element.java:1422) // at java.lang.String.valueOf(String.java:2982) // at java.io.PrintStream.println(PrintStream.java:821) // // ``` // // //
Jsoup
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.CDataNode; import org.jsoup.nodes.Comment; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Entities; import org.jsoup.nodes.FormElement; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import org.junit.Ignore; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** Tests for the Parser @author Jonathan Hedley, jonathan@hedley.net */ public class HtmlParserTest { @Test public void parsesSimpleDocument() { String html = "<html><head><title>First!</title></head><body><p>First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); Element img = p.child(0); assertEquals("foo.png", img.attr("src")); assertEquals("img", img.tagName()); } @Test public void parsesRoughAttributes() { String html = "<html><head><title>First!</title></head><body><p class=\"foo > bar\">First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); assertEquals("foo > bar", p.attr("class")); } @Test public void parsesQuiteRoughAttributes() { String html = "<p =a>One<a <p>Something</p>Else"; // this gets a <p> with attr '=a' and an <a tag with an attribue named '<p'; and then auto-recreated Document doc = Jsoup.parse(html); assertEquals("<p =a>One<a <p>Something</a></p>\n" + "<a <p>Else</a>", doc.body().html()); doc = Jsoup.parse("<p .....>"); assertEquals("<p .....></p>", doc.body().html()); } @Test public void parsesComments() { String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --><p>Hello</p></body></html>"; Document doc = Jsoup.parse(html); Element body = doc.body(); Comment comment = (Comment) body.childNode(1); // comment should not be sub of img, as it's an empty tag assertEquals(" <table><tr><td></table> ", comment.getData()); Element p = body.child(1); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); } @Test public void parsesUnterminatedComments() { String html = "<p>Hello<!-- <tr><td>"; Document doc = Jsoup.parse(html); Element p = doc.getElementsByTag("p").get(0); assertEquals("Hello", p.text()); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); Comment comment = (Comment) p.childNode(1); assertEquals(" <tr><td>", comment.getData()); } @Test public void dropsUnterminatedTag() { // jsoup used to parse this to <p>, but whatwg, webkit will drop. String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(0, doc.getElementsByTag("p").size()); assertEquals("", doc.text()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); assertEquals("", doc.text()); } @Test public void dropsUnterminatedAttribute() { // jsoup used to parse this to <p id="foo">, but whatwg, webkit will drop. String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); assertEquals("", doc.text()); } @Test public void parsesUnterminatedTextarea() { // don't parse right to end, but break on <p> Document doc = Jsoup.parse("<body><p><textarea>one<p>two"); Element t = doc.select("textarea").first(); assertEquals("one", t.text()); assertEquals("two", doc.select("p").get(1).text()); } @Test public void parsesUnterminatedOption() { // bit weird this -- browsers and spec get stuck in select until there's a </select> Document doc = Jsoup.parse("<body><p><select><option>One<option>Two</p><p>Three</p>"); Elements options = doc.select("option"); assertEquals(2, options.size()); assertEquals("One", options.first().text()); assertEquals("TwoThree", options.last().text()); } @Test public void testSelectWithOption() { Parser parser = Parser.htmlParser(); parser.setTrackErrors(10); Document document = parser.parseInput("<select><option>Option 1</option></select>", "http://jsoup.org"); assertEquals(0, parser.getErrors().size()); } @Test public void testSpaceAfterTag() { Document doc = Jsoup.parse("<div > <a name=\"top\"></a ><p id=1 >Hello</p></div>"); assertEquals("<div> <a name=\"top\"></a><p id=\"1\">Hello</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void createsDocumentStructure() { String html = "<meta name=keywords /><link rel=stylesheet /><title>jsoup</title><p>Hello world</p>"; Document doc = Jsoup.parse(html); Element head = doc.head(); Element body = doc.body(); assertEquals(1, doc.children().size()); // root node: contains html node assertEquals(2, doc.child(0).children().size()); // html node: head and body assertEquals(3, head.children().size()); assertEquals(1, body.children().size()); assertEquals("keywords", head.getElementsByTag("meta").get(0).attr("name")); assertEquals(0, body.getElementsByTag("meta").size()); assertEquals("jsoup", doc.title()); assertEquals("Hello world", body.text()); assertEquals("Hello world", body.children().get(0).text()); } @Test public void createsStructureFromBodySnippet() { // the bar baz stuff naturally goes into the body, but the 'foo' goes into root, and the normalisation routine // needs to move into the start of the body String html = "foo <b>bar</b> baz"; Document doc = Jsoup.parse(html); assertEquals("foo bar baz", doc.text()); } @Test public void handlesEscapedData() { String html = "<div title='Surf &amp; Turf'>Reef &amp; Beef</div>"; Document doc = Jsoup.parse(html); Element div = doc.getElementsByTag("div").get(0); assertEquals("Surf & Turf", div.attr("title")); assertEquals("Reef & Beef", div.text()); } @Test public void handlesDataOnlyTags() { String t = "<style>font-family: bold</style>"; List<Element> tels = Jsoup.parse(t).getElementsByTag("style"); assertEquals("font-family: bold", tels.get(0).data()); assertEquals("", tels.get(0).text()); String s = "<p>Hello</p><script>obj.insert('<a rel=\"none\" />');\ni++;</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("obj.insert('<a rel=\"none\" />');\ni++;", doc.data()); } @Test public void handlesTextAfterData() { String h = "<html><body>pre <script>inner</script> aft</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head></head><body>pre <script>inner</script> aft</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesTextArea() { Document doc = Jsoup.parse("<textarea>Hello</textarea>"); Elements els = doc.select("textarea"); assertEquals("Hello", els.text()); assertEquals("Hello", els.val()); } @Test public void preservesSpaceInTextArea() { // preserve because the tag is marked as preserve white space Document doc = Jsoup.parse("<textarea>\n\tOne\n\tTwo\n\tThree\n</textarea>"); String expect = "One\n\tTwo\n\tThree"; // the leading and trailing spaces are dropped as a convenience to authors Element el = doc.select("textarea").first(); assertEquals(expect, el.text()); assertEquals(expect, el.val()); assertEquals(expect, el.html()); assertEquals("<textarea>\n\t" + expect + "\n</textarea>", el.outerHtml()); // but preserved in round-trip html } @Test public void preservesSpaceInScript() { // preserve because it's content is a data node Document doc = Jsoup.parse("<script>\nOne\n\tTwo\n\tThree\n</script>"); String expect = "\nOne\n\tTwo\n\tThree\n"; Element el = doc.select("script").first(); assertEquals(expect, el.data()); assertEquals("One\n\tTwo\n\tThree", el.html()); assertEquals("<script>" + expect + "</script>", el.outerHtml()); } @Test public void doesNotCreateImplicitLists() { // old jsoup used to wrap this in <ul>, but that's not to spec String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should NOT have created a default ul. assertEquals(0, ol.size()); Elements lis = doc.select("li"); assertEquals(2, lis.size()); assertEquals("body", lis.first().parent().tagName()); // no fiddling with non-implicit lists String h2 = "<ol><li><p>Point the first<li><p>Point the second"; Document doc2 = Jsoup.parse(h2); assertEquals(0, doc2.select("ul").size()); assertEquals(1, doc2.select("ol").size()); assertEquals(2, doc2.select("ol li").size()); assertEquals(2, doc2.select("ol li p").size()); assertEquals(1, doc2.select("ol li").get(0).children().size()); // one p in first li } @Test public void discardsNakedTds() { // jsoup used to make this into an implicit table; but browsers make it into a text run String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("Hello<p>There</p><p>now</p>", TextUtil.stripNewlines(doc.body().html())); // <tbody> is introduced if no implicitly creating table, but allows tr to be directly under table } @Test public void handlesNestedImplicitTable() { Document doc = Jsoup.parse("<table><td>1</td></tr> <td>2</td></tr> <td> <table><td>3</td> <td>4</td></table> <tr><td>5</table>"); assertEquals("<table><tbody><tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td> <table><tbody><tr><td>3</td> <td>4</td></tr></tbody></table> </td></tr><tr><td>5</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesWhatWgExpensesTableExample() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/tabular-data.html#examples-0 Document doc = Jsoup.parse("<table> <colgroup> <col> <colgroup> <col> <col> <col> <thead> <tr> <th> <th>2008 <th>2007 <th>2006 <tbody> <tr> <th scope=rowgroup> Research and development <td> $ 1,109 <td> $ 782 <td> $ 712 <tr> <th scope=row> Percentage of net sales <td> 3.4% <td> 3.3% <td> 3.7% <tbody> <tr> <th scope=rowgroup> Selling, general, and administrative <td> $ 3,761 <td> $ 2,963 <td> $ 2,433 <tr> <th scope=row> Percentage of net sales <td> 11.6% <td> 12.3% <td> 12.6% </table>"); assertEquals("<table> <colgroup> <col> </colgroup><colgroup> <col> <col> <col> </colgroup><thead> <tr> <th> </th><th>2008 </th><th>2007 </th><th>2006 </th></tr></thead><tbody> <tr> <th scope=\"rowgroup\"> Research and development </th><td> $ 1,109 </td><td> $ 782 </td><td> $ 712 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 3.4% </td><td> 3.3% </td><td> 3.7% </td></tr></tbody><tbody> <tr> <th scope=\"rowgroup\"> Selling, general, and administrative </th><td> $ 3,761 </td><td> $ 2,963 </td><td> $ 2,433 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 11.6% </td><td> 12.3% </td><td> 12.6% </td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesTbodyTable() { Document doc = Jsoup.parse("<html><head></head><body><table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table></body></html>"); assertEquals("<table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesImplicitCaptionClose() { Document doc = Jsoup.parse("<table><caption>A caption<td>One<td>Two"); assertEquals("<table><caption>A caption</caption><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void noTableDirectInTable() { Document doc = Jsoup.parse("<table> <td>One <td><table><td>Two</table> <table><td>Three"); assertEquals("<table> <tbody><tr><td>One </td><td><table><tbody><tr><td>Two</td></tr></tbody></table> <table><tbody><tr><td>Three</td></tr></tbody></table></td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void ignoresDupeEndTrTag() { Document doc = Jsoup.parse("<table><tr><td>One</td><td><table><tr><td>Two</td></tr></tr></table></td><td>Three</td></tr></table>"); // two </tr></tr>, must ignore or will close table assertEquals("<table><tbody><tr><td>One</td><td><table><tbody><tr><td>Two</td></tr></tbody></table></td><td>Three</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { // only listen to the first base href String h = "<a href=1>#</a><base href='/2/'><a href='3'>#</a><base href='http://bar'><a href=/4>#</a>"; Document doc = Jsoup.parse(h, "http://foo/"); assertEquals("http://foo/2/", doc.baseUri()); // gets set once, so doc and descendants have first only Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/2/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://foo/2/", anchors.get(2).baseUri()); assertEquals("http://foo/2/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://foo/4", anchors.get(2).absUrl("href")); } @Test public void handlesProtocolRelativeUrl() { String base = "https://example.com/"; String html = "<img src='//example.net/img.jpg'>"; Document doc = Jsoup.parse(html, base); Element el = doc.select("img").first(); assertEquals("https://example.net/img.jpg", el.absUrl("src")); } @Test public void handlesCdata() { // todo: as this is html namespace, should actually treat as bogus comment, not cdata. keep as cdata for now String h = "<div id=1><![CDATA[<html>\n <foo><&amp;]]></div>"; // the &amp; in there should remain literal Document doc = Jsoup.parse(h); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node } @Test public void roundTripsCdata() { String h = "<div id=1><![CDATA[\n<html>\n <foo><&amp;]]></div>"; Document doc = Jsoup.parse(h); Element div = doc.getElementById("1"); assertEquals("<html>\n <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&amp;]]>\n</div>", div.outerHtml()); CDataNode cdata = (CDataNode) div.textNodes().get(0); assertEquals("\n<html>\n <foo><&amp;", cdata.text()); } @Test public void handlesCdataAcrossBuffer() { StringBuilder sb = new StringBuilder(); while (sb.length() <= CharacterReader.maxBufferLen) { sb.append("A suitable amount of CData.\n"); } String cdata = sb.toString(); String h = "<div><![CDATA[" + cdata + "]]></div>"; Document doc = Jsoup.parse(h); Element div = doc.selectFirst("div"); CDataNode node = (CDataNode) div.textNodes().get(0); assertEquals(cdata, node.text()); } @Test public void handlesCdataInScript() { String html = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>"; Document doc = Jsoup.parse(html); String data = "//<![CDATA[\n\n foo();\n//]]>"; Element script = doc.selectFirst("script"); assertEquals("", script.text()); // won't be parsed as cdata because in script data section assertEquals(data, script.data()); assertEquals(html, script.outerHtml()); DataNode dataNode = (DataNode) script.childNode(0); assertEquals(data, dataNode.getWholeData()); // see - not a cdata node, because in script. contrast with XmlTreeBuilder - will be cdata. } @Test public void handlesUnclosedCdataAtEOF() { // https://github.com/jhy/jsoup/issues/349 would crash, as character reader would try to seek past EOF String h = "<![CDATA[]]"; Document doc = Jsoup.parse(h); assertEquals(1, doc.body().childNodeSize()); } @Test public void handleCDataInText() { String h = "<p>One <![CDATA[Two <&]]> Three</p>"; Document doc = Jsoup.parse(h); Element p = doc.selectFirst("p"); List<Node> nodes = p.childNodes(); assertEquals("One ", ((TextNode) nodes.get(0)).getWholeText()); assertEquals("Two <&", ((TextNode) nodes.get(1)).getWholeText()); assertEquals("Two <&", ((CDataNode) nodes.get(1)).getWholeText()); assertEquals(" Three", ((TextNode) nodes.get(2)).getWholeText()); assertEquals(h, p.outerHtml()); } @Test public void cdataNodesAreTextNodes() { String h = "<p>One <![CDATA[ Two <& ]]> Three</p>"; Document doc = Jsoup.parse(h); Element p = doc.selectFirst("p"); List<TextNode> nodes = p.textNodes(); assertEquals("One ", nodes.get(0).text()); assertEquals(" Two <& ", nodes.get(1).text()); assertEquals(" Three", nodes.get(2).text()); } @Test public void handlesInvalidStartTags() { String h = "<div>Hello < There <&amp;></div>"; // parse to <div {#text=Hello < There <&>}> Document doc = Jsoup.parse(h); assertEquals("Hello < There <&>", doc.select("div").first().text()); } @Test public void handlesUnknownTags() { String h = "<div><foo title=bar>Hello<foo title=qux>there</foo></div>"; Document doc = Jsoup.parse(h); Elements foos = doc.select("foo"); assertEquals(2, foos.size()); assertEquals("bar", foos.first().attr("title")); assertEquals("qux", foos.last().attr("title")); assertEquals("there", foos.last().text()); } @Test public void handlesUnknownInlineTags() { String h = "<p><cust>Test</cust></p><p><cust><cust>Test</cust></cust></p>"; Document doc = Jsoup.parseBodyFragment(h); String out = doc.body().html(); assertEquals(h, TextUtil.stripNewlines(out)); } @Test public void parsesBodyFragment() { String h = "<!-- comment --><p><a href='foo'>One</a></p>"; Document doc = Jsoup.parseBodyFragment(h, "http://example.com"); assertEquals("<body><!-- comment --><p><a href=\"foo\">One</a></p></body>", TextUtil.stripNewlines(doc.body().outerHtml())); assertEquals("http://example.com/foo", doc.select("a").first().absUrl("href")); } @Test public void handlesUnknownNamespaceTags() { // note that the first foo:bar should not really be allowed to be self closing, if parsed in html mode. String h = "<foo:bar id='1' /><abc:def id=2>Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>"; Document doc = Jsoup.parse(h); assertEquals("<foo:bar id=\"1\" /><abc:def id=\"2\">Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesKnownEmptyBlocks() { // if a known tag, allow self closing outside of spec, but force an end tag. unknown tags can be self closing. String h = "<div id='1' /><script src='/foo' /><div id=2><img /><img></div><a id=3 /><i /><foo /><foo>One</foo> <hr /> hr text <hr> hr text two"; Document doc = Jsoup.parse(h); assertEquals("<div id=\"1\"></div><script src=\"/foo\"></script><div id=\"2\"><img><img></div><a id=\"3\"></a><i></i><foo /><foo>One</foo> <hr> hr text <hr> hr text two", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesKnownEmptyNoFrames() { String h = "<html><head><noframes /><meta name=foo></head><body>One</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><noframes></noframes><meta name=\"foo\"></head><body>One</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesKnownEmptyStyle() { String h = "<html><head><style /><meta name=foo></head><body>One</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><style></style><meta name=\"foo\"></head><body>One</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesKnownEmptyTitle() { String h = "<html><head><title /><meta name=foo></head><body>One</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><title></title><meta name=\"foo\"></head><body>One</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesKnownEmptyIframe() { String h = "<p>One</p><iframe id=1 /><p>Two"; Document doc = Jsoup.parse(h); assertEquals("<html><head></head><body><p>One</p><iframe id=\"1\"></iframe><p>Two</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesSolidusAtAttributeEnd() { // this test makes sure [<a href=/>link</a>] is parsed as [<a href="/">link</a>], not [<a href="" /><a>link</a>] String h = "<a href=/>link</a>"; Document doc = Jsoup.parse(h); assertEquals("<a href=\"/\">link</a>", doc.body().html()); } @Test public void handlesMultiClosingBody() { String h = "<body><p>Hello</body><p>there</p></body></body></html><p>now"; Document doc = Jsoup.parse(h); assertEquals(3, doc.select("p").size()); assertEquals(3, doc.body().children().size()); } @Test public void handlesUnclosedDefinitionLists() { // jsoup used to create a <dl>, but that's not to spec String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(0, doc.select("dl").size()); // no auto dl assertEquals(4, doc.select("dt, dd").size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @Test public void handlesBlocksInDefinitions() { // per the spec, dt and dd are inline, but in practise are block String h = "<dl><dt><div id=1>Term</div></dt><dd><div id=2>Def</div></dd></dl>"; Document doc = Jsoup.parse(h); assertEquals("dt", doc.select("#1").first().parent().tagName()); assertEquals("dd", doc.select("#2").first().parent().tagName()); assertEquals("<dl><dt><div id=\"1\">Term</div></dt><dd><div id=\"2\">Def</div></dd></dl>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesFrames() { String h = "<html><head><script></script><noscript></noscript></head><frameset><frame src=foo></frame><frame src=foo></frameset></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\"><frame src=\"foo\"></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body auto vivification } @Test public void ignoresContentAfterFrameset() { String h = "<html><head><title>One</title></head><frameset><frame /><frame /></frameset><table></table></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><title>One</title></head><frameset><frame><frame></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body, no table. No crash! } @Test public void handlesJavadocFont() { String h = "<TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A>&nbsp;</TD>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("Deprecated", a.text()); assertEquals("font", a.child(0).tagName()); assertEquals("b", a.child(0).child(0).tagName()); } @Test public void handlesBaseWithoutHref() { String h = "<head><base target='_blank'></head><body><a href=/foo>Test</a></body>"; Document doc = Jsoup.parse(h, "http://example.com/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://example.com/foo", a.attr("abs:href")); } @Test public void normalisesDocument() { String h = "<!doctype html>One<html>Two<head>Three<link></head>Four<body>Five </body>Six </html>Seven "; Document doc = Jsoup.parse(h); assertEquals("<!doctype html><html><head></head><body>OneTwoThree<link>FourFive Six Seven </body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesEmptyDocument() { Document doc = Jsoup.parse(""); assertEquals("<html><head></head><body></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesHeadlessBody() { Document doc = Jsoup.parse("<html><body><span class=\"foo\">bar</span>"); assertEquals("<html><head></head><body><span class=\"foo\">bar</span></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisedBodyAfterContent() { Document doc = Jsoup.parse("<font face=Arial><body class=name><div>One</div></body></font>"); assertEquals("<html><head></head><body class=\"name\"><font face=\"Arial\"><div>One</div></font></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void findsCharsetInMalformedMeta() { String h = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"; // example cited for reason of html5's <meta charset> element Document doc = Jsoup.parse(h); assertEquals("gb2312", doc.select("meta").attr("charset")); } @Test public void testHgroup() { // jsoup used to not allow hroup in h{n}, but that's not in spec, and browsers are OK Document doc = Jsoup.parse("<h1>Hello <h2>There <hgroup><h1>Another<h2>headline</hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup>"); assertEquals("<h1>Hello </h1><h2>There <hgroup><h1>Another</h1><h2>headline</h2></hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup></h2>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def>There</abc-def>"); assertEquals("<abc_def id=\"1\">Hello</abc_def> <abc-def>There</abc-def>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHeaderContents() { // h* tags (h1 .. h9) in browsers can handle any internal content other than other h*. which is not per any // spec, which defines them as containing phrasing content only. so, reality over theory. Document doc = Jsoup.parse("<h1>Hello <div>There</div> now</h1> <h2>More <h3>Content</h3></h2>"); assertEquals("<h1>Hello <div>There</div> now</h1> <h2>More </h2><h3>Content</h3>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testSpanContents() { // like h1 tags, the spec says SPAN is phrasing only, but browsers and publisher treat span as a block tag Document doc = Jsoup.parse("<span>Hello <div>there</div> <span>now</span></span>"); assertEquals("<span>Hello <div>there</div> <span>now</span></span>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testNoImagesInNoScriptInHead() { // jsoup used to allow, but against spec if parsing with noscript Document doc = Jsoup.parse("<html><head><noscript><img src='foo'></noscript></head><body><p>Hello</p></body></html>"); assertEquals("<html><head><noscript>&lt;img src=\"foo\"&gt;</noscript></head><body><p>Hello</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testAFlowContents() { // html5 has <a> as either phrasing or block Document doc = Jsoup.parse("<a>Hello <div>there</div> <span>now</span></a>"); assertEquals("<a>Hello <div>there</div> <span>now</span></a>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testFontFlowContents() { // html5 has no definition of <font>; often used as flow Document doc = Jsoup.parse("<font>Hello <div>there</div> <span>now</span></font>"); assertEquals("<font>Hello <div>there</div> <span>now</span></font>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesMisnestedTagsBI() { // whatwg: <b><i></b></i> String h = "<p>1<b>2<i>3</b>4</i>5</p>"; Document doc = Jsoup.parse(h); assertEquals("<p>1<b>2<i>3</i></b><i>4</i>5</p>", doc.body().html()); // adoption agency on </b>, reconstruction of formatters on 4. } @Test public void handlesMisnestedTagsBP() { // whatwg: <b><p></b></p> String h = "<b>1<p>2</b>3</p>"; Document doc = Jsoup.parse(h); assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html()); } @Ignore // todo: test case for https://github.com/jhy/jsoup/issues/845. Doesn't work yet. @Test public void handlesMisnestedAInDivs() { String h = "<a href='#1'><div><div><a href='#2'>child</a</div</div></a>"; String w = "<a href=\"#1\"></a><div><a href=\"#1\"></a><div><a href=\"#1\"></a><a href=\"#2\">child</a></div></div>"; Document doc = Jsoup.parse(h); assertEquals( StringUtil.normaliseWhitespace(w), StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void handlesUnexpectedMarkupInTables() { // whatwg - tests markers in active formatting (if they didn't work, would get in in table) // also tests foster parenting String h = "<table><b><tr><td>aaa</td></tr>bbb</table>ccc"; Document doc = Jsoup.parse(h); assertEquals("<b></b><b>bbb</b><table><tbody><tr><td>aaa</td></tr></tbody></table><b>ccc</b>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesUnclosedFormattingElements() { // whatwg: formatting elements get collected and applied, but excess elements are thrown away String h = "<!DOCTYPE html>\n" + "<p><b class=x><b class=x><b><b class=x><b class=x><b>X\n" + "<p>X\n" + "<p><b><b class=x><b>X\n" + "<p></b></b></b></b></b></b>X"; Document doc = Jsoup.parse(h); doc.outputSettings().indentAmount(0); String want = "<!doctype html>\n" + "<html>\n" + "<head></head>\n" + "<body>\n" + "<p><b class=\"x\"><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b><b><b class=\"x\"><b>X </b></b></b></b></b></b></b></b></p>\n" + "<p>X</p>\n" + "</body>\n" + "</html>"; assertEquals(want, doc.html()); } @Test public void handlesUnclosedAnchors() { String h = "<a href='http://example.com/'>Link<p>Error link</a>"; Document doc = Jsoup.parse(h); String want = "<a href=\"http://example.com/\">Link</a>\n<p><a href=\"http://example.com/\">Error link</a></p>"; assertEquals(want, doc.body().html()); } @Test public void reconstructFormattingElements() { // tests attributes and multi b String h = "<p><b class=one>One <i>Two <b>Three</p><p>Hello</p>"; Document doc = Jsoup.parse(h); assertEquals("<p><b class=\"one\">One <i>Two <b>Three</b></i></b></p>\n<p><b class=\"one\"><i><b>Hello</b></i></b></p>", doc.body().html()); } @Test public void reconstructFormattingElementsInTable() { // tests that tables get formatting markers -- the <b> applies outside the table and does not leak in, // and the <i> inside the table and does not leak out. String h = "<p><b>One</p> <table><tr><td><p><i>Three<p>Four</i></td></tr></table> <p>Five</p>"; Document doc = Jsoup.parse(h); String want = "<p><b>One</b></p>\n" + "<b> \n" + " <table>\n" + " <tbody>\n" + " <tr>\n" + " <td><p><i>Three</i></p><p><i>Four</i></p></td>\n" + " </tr>\n" + " </tbody>\n" + " </table> <p>Five</p></b>"; assertEquals(want, doc.body().html()); } @Test public void commentBeforeHtml() { String h = "<!-- comment --><!-- comment 2 --><p>One</p>"; Document doc = Jsoup.parse(h); assertEquals("<!-- comment --><!-- comment 2 --><html><head></head><body><p>One</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void emptyTdTag() { String h = "<table><tr><td>One</td><td id='2' /></tr></table>"; Document doc = Jsoup.parse(h); assertEquals("<td>One</td>\n<td id=\"2\"></td>", doc.select("tr").first().html()); } @Test public void handlesSolidusInA() { // test for bug #66 String h = "<a class=lp href=/lib/14160711/>link text</a>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("link text", a.text()); assertEquals("/lib/14160711/", a.attr("href")); } @Test public void handlesSpanInTbody() { // test for bug 64 String h = "<table><tbody><span class='1'><tr><td>One</td></tr><tr><td>Two</td></tr></span></tbody></table>"; Document doc = Jsoup.parse(h); assertEquals(doc.select("span").first().children().size(), 0); // the span gets closed assertEquals(doc.select("table").size(), 1); // only one table } @Test public void handlesUnclosedTitleAtEof() { assertEquals("Data", Jsoup.parse("<title>Data").title()); assertEquals("Data<", Jsoup.parse("<title>Data<").title()); assertEquals("Data</", Jsoup.parse("<title>Data</").title()); assertEquals("Data</t", Jsoup.parse("<title>Data</t").title()); assertEquals("Data</ti", Jsoup.parse("<title>Data</ti").title()); assertEquals("Data", Jsoup.parse("<title>Data</title>").title()); assertEquals("Data", Jsoup.parse("<title>Data</title >").title()); } @Test public void handlesUnclosedTitle() { Document one = Jsoup.parse("<title>One <b>Two <b>Three</TITLE><p>Test</p>"); // has title, so <b> is plain text assertEquals("One <b>Two <b>Three", one.title()); assertEquals("Test", one.select("p").first().text()); Document two = Jsoup.parse("<title>One<b>Two <p>Test</p>"); // no title, so <b> causes </title> breakout assertEquals("One", two.title()); assertEquals("<b>Two <p>Test</p></b>", two.body().html()); } @Test public void handlesUnclosedScriptAtEof() { assertEquals("Data", Jsoup.parse("<script>Data").select("script").first().data()); assertEquals("Data<", Jsoup.parse("<script>Data<").select("script").first().data()); assertEquals("Data</sc", Jsoup.parse("<script>Data</sc").select("script").first().data()); assertEquals("Data</-sc", Jsoup.parse("<script>Data</-sc").select("script").first().data()); assertEquals("Data</sc-", Jsoup.parse("<script>Data</sc-").select("script").first().data()); assertEquals("Data</sc--", Jsoup.parse("<script>Data</sc--").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script>").select("script").first().data()); assertEquals("Data</script", Jsoup.parse("<script>Data</script").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script ").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"p").select("script").first().data()); } @Test public void handlesUnclosedRawtextAtEof() { assertEquals("Data", Jsoup.parse("<style>Data").select("style").first().data()); assertEquals("Data</st", Jsoup.parse("<style>Data</st").select("style").first().data()); assertEquals("Data", Jsoup.parse("<style>Data</style>").select("style").first().data()); assertEquals("Data</style", Jsoup.parse("<style>Data</style").select("style").first().data()); assertEquals("Data</-style", Jsoup.parse("<style>Data</-style").select("style").first().data()); assertEquals("Data</style-", Jsoup.parse("<style>Data</style-").select("style").first().data()); assertEquals("Data</style--", Jsoup.parse("<style>Data</style--").select("style").first().data()); } @Test public void noImplicitFormForTextAreas() { // old jsoup parser would create implicit forms for form children like <textarea>, but no more Document doc = Jsoup.parse("<textarea>One</textarea>"); assertEquals("<textarea>One</textarea>", doc.body().html()); } @Test public void handlesEscapedScript() { Document doc = Jsoup.parse("<script><!-- one <script>Blah</script> --></script>"); assertEquals("<!-- one <script>Blah</script> -->", doc.select("script").first().data()); } @Test public void handles0CharacterAsText() { Document doc = Jsoup.parse("0<p>0</p>"); assertEquals("0\n<p>0</p>", doc.body().html()); } @Test public void handlesNullInData() { Document doc = Jsoup.parse("<p id=\u0000>Blah \u0000</p>"); assertEquals("<p id=\"\uFFFD\">Blah \u0000</p>", doc.body().html()); // replaced in attr, NOT replaced in data } @Test public void handlesNullInComments() { Document doc = Jsoup.parse("<body><!-- \u0000 \u0000 -->"); assertEquals("<!-- \uFFFD \uFFFD -->", doc.body().html()); } @Test public void handlesNewlinesAndWhitespaceInTag() { Document doc = Jsoup.parse("<a \n href=\"one\" \r\n id=\"two\" \f >"); assertEquals("<a href=\"one\" id=\"two\"></a>", doc.body().html()); } @Test public void handlesWhitespaceInoDocType() { String html = "<!DOCTYPE html\r\n" + " PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n" + " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; Document doc = Jsoup.parse(html); assertEquals("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">", doc.childNode(0).outerHtml()); } @Test public void tracksErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(500); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(5, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); assertEquals("50: Tag cannot be self closing; not a void tag", errors.get(3).toString()); assertEquals("61: Unexpectedly reached end of file (EOF) in input state [TagName]", errors.get(4).toString()); } @Test public void tracksLimitedErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(3); Document doc = parser.parseInput(html, "http://example.com"); List<ParseError> errors = parser.getErrors(); assertEquals(3, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); } @Test public void noErrorsByDefault() { String html = "<p>One</p href='no'>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser(); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(0, errors.size()); } @Test public void handlesCommentsInTable() { String html = "<table><tr><td>text</td><!-- Comment --></tr></table>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<html><head></head><body><table><tbody><tr><td>text</td><!-- Comment --></tr></tbody></table></body></html>", TextUtil.stripNewlines(node.outerHtml())); } @Test public void handlesQuotesInCommentsInScripts() { String html = "<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>", node.body().html()); } @Test public void handleNullContextInParseFragment() { String html = "<ol><li>One</li></ol><p>Two</p>"; List<Node> nodes = Parser.parseFragment(html, null, "http://example.com/"); assertEquals(1, nodes.size()); // returns <html> node (not document) -- no context means doc gets created assertEquals("html", nodes.get(0).nodeName()); assertEquals("<html> <head></head> <body> <ol> <li>One</li> </ol> <p>Two</p> </body> </html>", StringUtil.normaliseWhitespace(nodes.get(0).outerHtml())); } @Test public void doesNotFindShortestMatchingEntity() { // previous behaviour was to identify a possible entity, then chomp down the string until a match was found. // (as defined in html5.) However in practise that lead to spurious matches against the author's intent. String html = "One &clubsuite; &clubsuit;"; Document doc = Jsoup.parse(html); assertEquals(StringUtil.normaliseWhitespace("One &amp;clubsuite; ♣"), doc.body().html()); } @Test public void relaxedBaseEntityMatchAndStrictExtendedMatch() { // extended entities need a ; at the end to match, base does not String html = "&amp &quot &reg &icy &hopf &icy; &hopf;"; Document doc = Jsoup.parse(html); doc.outputSettings().escapeMode(Entities.EscapeMode.extended).charset("ascii"); // modifies output only to clarify test assertEquals("&amp; \" &reg; &amp;icy &amp;hopf &icy; &hopf;", doc.body().html()); } @Test public void handlesXmlDeclarationAsBogusComment() { String html = "<?xml encoding='UTF-8' ?><body>One</body>"; Document doc = Jsoup.parse(html); assertEquals("<!--?xml encoding='UTF-8' ?--> <html> <head></head> <body> One </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesTagsInTextarea() { String html = "<textarea><p>Jsoup</p></textarea>"; Document doc = Jsoup.parse(html); assertEquals("<textarea>&lt;p&gt;Jsoup&lt;/p&gt;</textarea>", doc.body().html()); } // form tests @Test public void createsFormElements() { String html = "<body><form><input id=1><input id=2></form></body>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); } @Test public void associatedFormControlsWithDisjointForms() { // form gets closed, isn't parent of controls String html = "<table><tr><form><input type=hidden id=1><td><input type=text id=2></td><tr></table>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); assertEquals("<table><tbody><tr><form></form><input type=\"hidden\" id=\"1\"><td><input type=\"text\" id=\"2\"></td></tr><tr></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesInputInTable() { String h = "<body>\n" + "<input type=\"hidden\" name=\"a\" value=\"\">\n" + "<table>\n" + "<input type=\"hidden\" name=\"b\" value=\"\" />\n" + "</table>\n" + "</body>"; Document doc = Jsoup.parse(h); assertEquals(1, doc.select("table input").size()); assertEquals(2, doc.select("input").size()); } @Test public void convertsImageToImg() { // image to img, unless in a svg. old html cruft. String h = "<body><image><svg><image /></svg></body>"; Document doc = Jsoup.parse(h); assertEquals("<img>\n<svg>\n <image />\n</svg>", doc.body().html()); } @Test public void handlesInvalidDoctypes() { // would previously throw invalid name exception on empty doctype Document doc = Jsoup.parse("<!DOCTYPE>"); assertEquals( "<!doctype> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE><html><p>Foo</p></html>"); assertEquals( "<!doctype> <html> <head></head> <body> <p>Foo</p> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE \u0000>"); assertEquals( "<!doctype �> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesManyChildren() { // Arrange StringBuilder longBody = new StringBuilder(500000); for (int i = 0; i < 25000; i++) { longBody.append(i).append("<br>"); } // Act long start = System.currentTimeMillis(); Document doc = Parser.parseBodyFragment(longBody.toString(), ""); // Assert assertEquals(50000, doc.body().childNodeSize()); assertTrue(System.currentTimeMillis() - start < 1000); } @Test public void handlesDeepStack() {} // Defects4J: flaky method // @Test public void handlesDeepStack() { // // inspired by http://sv.stargate.wikia.com/wiki/M2J and https://github.com/jhy/jsoup/issues/955 // // I didn't put it in the integration tests, because explorer and intellij kept dieing trying to preview/index it // // // Arrange // StringBuilder longBody = new StringBuilder(500000); // for (int i = 0; i < 25000; i++) { // longBody.append(i).append("<dl><dd>"); // } // for (int i = 0; i < 25000; i++) { // longBody.append(i).append("</dd></dl>"); // } // // // Act // long start = System.currentTimeMillis(); // Document doc = Parser.parseBodyFragment(longBody.toString(), ""); // // // Assert // assertEquals(2, doc.body().childNodeSize()); // assertEquals(25000, doc.select("dd").size()); // assertTrue(System.currentTimeMillis() - start < 2000); // } @Test public void testInvalidTableContents() throws IOException { File in = ParseTest.getFile("/htmltests/table-invalid-elements.html"); Document doc = Jsoup.parse(in, "UTF-8"); doc.outputSettings().prettyPrint(true); String rendered = doc.toString(); int endOfEmail = rendered.indexOf("Comment"); int guarantee = rendered.indexOf("Why am I here?"); assertTrue("Comment not found", endOfEmail > -1); assertTrue("Search text not found", guarantee > -1); assertTrue("Search text did not come after comment", guarantee > endOfEmail); } @Test public void testNormalisesIsIndex() { Document doc = Jsoup.parse("<body><isindex action='/submit'></body>"); String html = doc.outerHtml(); assertEquals("<form action=\"/submit\"> <hr> <label>This is a searchable index. Enter search keywords: <input name=\"isindex\"></label> <hr> </form>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void testReinsertionModeForThCelss() { String body = "<body> <table> <tr> <th> <table><tr><td></td></tr></table> <div> <table><tr><td></td></tr></table> </div> <div></div> <div></div> <div></div> </th> </tr> </table> </body>"; Document doc = Jsoup.parse(body); assertEquals(1, doc.body().children().size()); } @Test public void testUsingSingleQuotesInQueries() { String body = "<body> <div class='main'>hello</div></body>"; Document doc = Jsoup.parse(body); Elements main = doc.select("div[class='main']"); assertEquals("hello", main.text()); } @Test public void testSupportsNonAsciiTags() { String body = "<進捗推移グラフ>Yes</進捗推移グラフ><русский-тэг>Correct</<русский-тэг>"; Document doc = Jsoup.parse(body); Elements els = doc.select("進捗推移グラフ"); assertEquals("Yes", els.text()); els = doc.select("русский-тэг"); assertEquals("Correct", els.text()); } @Test public void testSupportsPartiallyNonAsciiTags() { String body = "<div>Check</divá>"; Document doc = Jsoup.parse(body); Elements els = doc.select("div"); assertEquals("Check", els.text()); } @Test public void testFragment() { // make sure when parsing a body fragment, a script tag at start goes into the body String html = "<script type=\"text/javascript\">console.log('foo');</script>\n" + "<div id=\"somecontent\">some content</div>\n" + "<script type=\"text/javascript\">console.log('bar');</script>"; Document body = Jsoup.parseBodyFragment(html); assertEquals("<script type=\"text/javascript\">console.log('foo');</script> \n" + "<div id=\"somecontent\">\n" + " some content\n" + "</div> \n" + "<script type=\"text/javascript\">console.log('bar');</script>", body.body().html()); } @Test public void testHtmlLowerCase() { String html = "<!doctype HTML><DIV ID=1>One</DIV>"; Document doc = Jsoup.parse(html); assertEquals("<!doctype html> <html> <head></head> <body> <div id=\"1\"> One </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG>One</TaG>"); assertEquals("<tag>One</tag>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void canPreserveTagCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, false)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN id=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG ID=one>One</TaG>"); assertEquals("<TaG id=\"one\">One</TaG>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void canPreserveAttributeCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(false, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <span ID=\"2\"></span> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG ID=one>One</TaG>"); assertEquals("<tag ID=\"one\">One</tag>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void canPreserveBothCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN ID=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); Element div = doc.selectFirst("#1"); div.after("<TaG ID=one>One</TaG>"); assertEquals("<TaG ID=\"one\">One</TaG>", TextUtil.stripNewlines(div.nextElementSibling().outerHtml())); } @Test public void handlesControlCodeInAttributeName() { Document doc = Jsoup.parse("<p><a \06=foo>One</a><a/\06=bar><a foo\06=bar>Two</a></p>"); assertEquals("<p><a>One</a><a></a><a foo=\"bar\">Two</a></p>", doc.body().html()); } @Test public void caseSensitiveParseTree() { String html = "<r><X>A</X><y>B</y></r>"; Parser parser = Parser.htmlParser(); parser.settings(ParseSettings.preserveCase); Document doc = parser.parseInput(html, ""); assertEquals("<r> <X> A </X> <y> B </y> </r>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void caseInsensitiveParseTree() { String html = "<r><X>A</X><y>B</y></r>"; Parser parser = Parser.htmlParser(); Document doc = parser.parseInput(html, ""); assertEquals("<r> <x> A </x> <y> B </y> </r>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void normalizesDiscordantTags() { Document document = Jsoup.parse("<div>test</DIV><p></p>"); assertEquals("<div>\n test\n</div>\n<p></p>", document.body().html()); } @Test public void selfClosingVoidIsNotAnError() { String html = "<p>test<br/>test<br/></p>"; Parser parser = Parser.htmlParser().setTrackErrors(5); parser.parseInput(html, ""); assertEquals(0, parser.getErrors().size()); assertTrue(Jsoup.isValid(html, Whitelist.basic())); String clean = Jsoup.clean(html, Whitelist.basic()); assertEquals("<p>test<br>test<br></p>", clean); } @Test public void selfClosingOnNonvoidIsError() { String html = "<p>test</p><div /><div>Two</div>"; Parser parser = Parser.htmlParser().setTrackErrors(5); parser.parseInput(html, ""); assertEquals(1, parser.getErrors().size()); assertEquals("18: Tag cannot be self closing; not a void tag", parser.getErrors().get(0).toString()); assertFalse(Jsoup.isValid(html, Whitelist.relaxed())); String clean = Jsoup.clean(html, Whitelist.relaxed()); assertEquals("<p>test</p> <div></div> <div> Two </div>", StringUtil.normaliseWhitespace(clean)); } @Test public void testTemplateInsideTable() throws IOException { File in = ParseTest.getFile("/htmltests/table-polymer-template.html"); Document doc = Jsoup.parse(in, "UTF-8"); doc.outputSettings().prettyPrint(true); Elements templates = doc.body().getElementsByTag("template"); for (Element template : templates) { assertTrue(template.childNodes().size() > 1); } } @Test public void testHandlesDeepSpans() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 200; i++) { sb.append("<span>"); } sb.append("<p>One</p>"); Document doc = Jsoup.parse(sb.toString()); assertEquals(200, doc.select("span").size()); assertEquals(1, doc.select("p").size()); } @Test public void commentAtEnd() throws Exception { Document doc = Jsoup.parse("<!"); assertTrue(doc.childNode(0) instanceof Comment); } @Test public void preSkipsFirstNewline() { Document doc = Jsoup.parse("<pre>\n\nOne\nTwo\n</pre>"); Element pre = doc.selectFirst("pre"); assertEquals("One\nTwo", pre.text()); assertEquals("\nOne\nTwo\n", pre.wholeText()); } @Test public void handlesXmlDeclAndCommentsBeforeDoctype() throws IOException { File in = ParseTest.getFile("/htmltests/comments.html"); Document doc = Jsoup.parse(in, "UTF-8"); assertEquals("<!--?xml version=\"1.0\" encoding=\"utf-8\"?--> <!-- so --><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <!-- what --> <html xml:lang=\"en\" lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"> <!-- now --> <head> <!-- then --> <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\"> <title>A Certain Kind of Test</title> </head> <body> <h1>Hello</h1>h1&gt; (There is a UTF8 hidden BOM at the top of this file.) </body> </html>", StringUtil.normaliseWhitespace(doc.html())); assertEquals("A Certain Kind of Test", doc.head().select("title").text()); } @Test public void fallbackToUtfIfCantEncode() throws IOException { // that charset can't be encoded, so make sure we flip to utf String in = "<html><meta charset=\"ISO-2022-CN\"/>One</html>"; Document doc = Jsoup.parse(new ByteArrayInputStream(in.getBytes()), null, ""); assertEquals("UTF-8", doc.charset().name()); assertEquals("One", doc.text()); String html = doc.outerHtml(); assertEquals("<html><head><meta charset=\"UTF-8\"></head><body>One</body></html>", TextUtil.stripNewlines(html)); } }
public void testZero() { assertPrint("var x ='\\0';", "var x=\"\\0\""); assertPrint("var x ='\\x00';", "var x=\"\\0\""); assertPrint("var x ='\\u0000';", "var x=\"\\0\""); }
com.google.javascript.jscomp.CodePrinterTest::testZero
test/com/google/javascript/jscomp/CodePrinterTest.java
1,181
test/com/google/javascript/jscomp/CodePrinterTest.java
testZero
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; public class CodePrinterTest extends TestCase { static Node parse(String js) { return parse(js, false); } static Node parse(String js, boolean checkTypes) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); // Allow getters and setters. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.initOptions(options); Node n = compiler.parseTestCode(js); if (checkTypes) { DefaultPassConfig passConfig = new DefaultPassConfig(null); CompilerPass typeResolver = passConfig.resolveTypes.create(compiler); Node externs = new Node(Token.SCRIPT); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); typeResolver.process(externs, n); CompilerPass inferTypes = passConfig.inferTypes.create(compiler); inferTypes.process(externs, n); } checkUnexpectedErrorsOrWarnings(compiler, 0); return n; } private static void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } String parsePrint(String js, boolean prettyprint, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes, boolean tagAsStrict) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .setTagAsStrict(tagAsStrict) .build(); } String printNode(Node n) { return new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build(); } void assertPrintNode(String expectedJs, Node ast) { assertEquals(expectedJs, printNode(ast)); } public void testPrint() { assertPrint("10 + a + b", "10+a+b"); assertPrint("10 + (30*50)", "10+30*50"); assertPrint("with(x) { x + 3; }", "with(x)x+3"); assertPrint("\"aa'a\"", "\"aa'a\""); assertPrint("\"aa\\\"a\"", "'aa\"a'"); assertPrint("function foo()\n{return 10;}", "function foo(){return 10}"); assertPrint("a instanceof b", "a instanceof b"); assertPrint("typeof(a)", "typeof a"); assertPrint( "var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}", "var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}"); // Safari: needs ';' at the end of a throw statement assertPrint("function foo(){throw 'error';}", "function foo(){throw\"error\";}"); // Safari 3 needs a "{" around a single function assertPrint("if (true) function foo(){return}", "if(true){function foo(){return}}"); assertPrint("var x = 10; { var y = 20; }", "var x=10;var y=20"); assertPrint("while (x-- > 0);", "while(x-- >0);"); assertPrint("x-- >> 1", "x-- >>1"); assertPrint("(function () {})(); ", "(function(){})()"); // Associativity assertPrint("var a,b,c,d;a || (b&& c) && (a || d)", "var a,b,c,d;a||b&&c&&(a||d)"); assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)", "var a,b,c;a||b||c;a*b*c;a|b|c"); assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);", "var a,b,c;a/b/c;a/(b/c);a-(b-c)"); assertPrint("var a,b; a = b = 3;", "var a,b;a=b=3"); assertPrint("var a,b,c,d; a = (b = c = (d = 3));", "var a,b,c,d;a=b=c=d=3"); assertPrint("var a,b,c; a += (b = c += 3);", "var a,b,c;a+=b=c+=3"); assertPrint("var a,b,c; a *= (b -= c);", "var a,b,c;a*=b-=c"); // Break scripts assertPrint("'<script>'", "\"<script>\""); assertPrint("'</script>'", "\"<\\/script>\""); assertPrint("\"</script> </SCRIPT>\"", "\"<\\/script> <\\/SCRIPT>\""); assertPrint("'-->'", "\"--\\>\""); assertPrint("']]>'", "\"]]\\>\""); assertPrint("' --></script>'", "\" --\\><\\/script>\""); assertPrint("/--> <\\/script>/g", "/--\\> <\\/script>/g"); // Break HTML start comments. Certain versions of Webkit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"<\\!-- I am a string --\\>\""); // Precedence assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3"); assertPrint("(delete a[0])/10", "delete a[0]/10"); // optional '()' for new // simple new assertPrint("new A", "new A"); assertPrint("new A()", "new A"); assertPrint("new A('x')", "new A(\"x\")"); // calling instance method directly after new assertPrint("new A().a()", "(new A).a()"); assertPrint("(new A).a()", "(new A).a()"); // this case should be fixed assertPrint("new A('y').a()", "(new A(\"y\")).a()"); // internal class assertPrint("new A.B", "new A.B"); assertPrint("new A.B()", "new A.B"); assertPrint("new A.B('z')", "new A.B(\"z\")"); // calling instance method directly after new internal class assertPrint("(new A.B).a()", "(new A.B).a()"); assertPrint("new A.B().a()", "(new A.B).a()"); // this case should be fixed assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()"); // Operators: make sure we don't convert binary + and unary + into ++ assertPrint("x + +y", "x+ +y"); assertPrint("x - (-y)", "x- -y"); assertPrint("x++ +y", "x++ +y"); assertPrint("x-- -y", "x-- -y"); assertPrint("x++ -y", "x++-y"); // Label assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo"); assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo"); // Object literals. assertPrint("({})", "({})"); assertPrint("var x = {};", "var x={}"); assertPrint("({}).x", "({}).x"); assertPrint("({})['x']", "({})[\"x\"]"); assertPrint("({}) instanceof Object", "({})instanceof Object"); assertPrint("({}) || 1", "({})||1"); assertPrint("1 || ({})", "1||{}"); assertPrint("({}) ? 1 : 2", "({})?1:2"); assertPrint("0 ? ({}) : 2", "0?{}:2"); assertPrint("0 ? 1 : ({})", "0?1:{}"); assertPrint("typeof ({})", "typeof{}"); assertPrint("f({})", "f({})"); // Anonymous function expressions. assertPrint("(function(){})", "(function(){})"); assertPrint("(function(){})()", "(function(){})()"); assertPrint("(function(){})instanceof Object", "(function(){})instanceof Object"); assertPrint("(function(){}).bind().call()", "(function(){}).bind().call()"); assertPrint("var x = function() { };", "var x=function(){}"); assertPrint("var x = function() { }();", "var x=function(){}()"); assertPrint("(function() {}), 2", "(function(){}),2"); // Name functions expression. assertPrint("(function f(){})", "(function f(){})"); // Function declaration. assertPrint("function f(){}", "function f(){}"); // Make sure we don't treat non-latin character escapes as raw strings. assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})"); assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})"); // Test if statement and for statements with single statements in body. assertPrint("if (true) { alert();}", "if(true)alert()"); assertPrint("if (false) {} else {alert(\"a\");}", "if(false);else alert(\"a\")"); assertPrint("for(;;) { alert();};", "for(;;)alert()"); assertPrint("do { alert(); } while(true);", "do alert();while(true)"); assertPrint("myLabel: { alert();}", "myLabel:alert()"); assertPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;)continue myLabel"); // Test nested var statement assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4"); // Non-latin identifier. Make sure we keep them escaped. assertPrint("\\u00fb", "\\u00fb"); assertPrint("\\u00fa=1", "\\u00fa=1"); assertPrint("function \\u00f9(){}", "function \\u00f9(){}"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl"); // Test the right-associative unary operators for spurious parens assertPrint("! ! true", "!!true"); assertPrint("!(!(true))", "!!true"); assertPrint("typeof(void(0))", "typeof void 0"); assertPrint("typeof(void(!0))", "typeof void!0"); assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus assertPrint("+(--x)", "+--x"); assertPrint("-(++x)", "-++x"); // needs a space to prevent an ambiguous parse assertPrint("-(--x)", "- --x"); assertPrint("!(~~5)", "!~~5"); assertPrint("~(a/b)", "~(a/b)"); // Preserve parens to overcome greedy binding of NEW assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)"); assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)"); assertPrint("new (new foobar(x)).factory(baz)", "new (new foobar(x)).factory(baz)"); // Make sure that HOOK is right associative assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e"); assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e"); assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e"); // Test nested ifs assertPrint("if (x) if (y); else;", "if(x)if(y);else;"); // Test comma. assertPrint("a,b,c", "a,b,c"); assertPrint("(a,b),c", "a,b,c"); assertPrint("a,(b,c)", "a,b,c"); assertPrint("x=a,b,c", "x=a,b,c"); assertPrint("x=(a,b),c", "x=(a,b),c"); assertPrint("x=a,(b,c)", "x=a,b,c"); assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c"); assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)"); assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]"); assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]"); assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]"); assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]"); assertPrint("var x=(a,b)", "var x=(a,b)"); assertPrint("var x=a,b,c", "var x=a,b,c"); assertPrint("var x=(a,b),c", "var x=(a,b),c"); assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)"); assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)"); assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)"); assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)"); assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))"); assertPrint("({}) , 1 , 2", "({}),1,2"); assertPrint("({}) , {} , {}", "({}),{},{}"); // EMPTY nodes assertPrint("if (x){}", "if(x);"); assertPrint("if(x);", "if(x);"); assertPrint("if(x)if(y);", "if(x)if(y);"); assertPrint("if(x){if(y);}", "if(x)if(y);"); assertPrint("if(x){if(y){};;;}", "if(x)if(y);"); assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}"); } public void testPrintArray() { assertPrint("[void 0, void 0]", "[void 0,void 0]"); assertPrint("[undefined, undefined]", "[undefined,undefined]"); assertPrint("[ , , , undefined]", "[,,,undefined]"); assertPrint("[ , , , 0]", "[,,,0]"); } public void testHook() { assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2"); assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2"); assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2"); assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2"); assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2"); assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2"); assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2"); assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)"); assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x"); assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x"); assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x"); assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3"); } public void testPrintInOperatorInForLoop() { // Check for in expression in for's init expression. // Check alone, with + (higher precedence), with ?: (lower precedence), // and with conditional. assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}", "var a={};for(var i=(\"length\"in a);i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}", "var a={};for(var i=(\"length\"in a)?0:1;i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}", "var a={};for(var i=(\"length\"in a)+1;i;);"); assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);", "var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);"); assertPrint("var a={};for (var i = a || a || (\"size\" in a);;);", "var a={};for(var i=a||a||(\"size\"in a);;);"); // Test works with unary operators and calls. assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}", "var a={};for(var i=-(\"length\"in a);i;);"); assertPrint("var a={};function b_(p){ return p;};" + "for(var i=1,j=b_(\"length\" in a);;) {}", "var a={};function b_(p){return p}" + "for(var i=1,j=b_(\"length\"in a);;);"); // Test we correctly handle an in operator in the test clause. assertPrint("var a={}; for (;(\"length\" in a);) {}", "var a={};for(;\"length\"in a;);"); } public void testLiteralProperty() { assertPrint("(64).toString()", "(64).toString()"); } private void assertPrint(String js, String expected) { parse(expected); // validate the expected string is valid js assertEquals(expected, parsePrint(js, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } // Make sure that the code generator doesn't associate an // else clause with the wrong if clause. public void testAmbiguousElseClauses() { assertPrintNode("if(x)if(y);else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), // ELSE clause for the inner if new Node(Token.BLOCK))))); assertPrintNode("if(x){if(y);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK))), // ELSE clause for the outer if new Node(Token.BLOCK))); assertPrintNode("if(x)if(y);else{if(z);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "z"), new Node(Token.BLOCK))))), // ELSE clause for the outermost if new Node(Token.BLOCK))); } public void testLineBreak() { // line break after function if in a statement context assertLineBreak("function a() {}\n" + "function b() {}", "function a(){}\n" + "function b(){}\n"); // line break after ; after a function assertLineBreak("var a = {};\n" + "a.foo = function () {}\n" + "function b() {}", "var a={};a.foo=function(){};\n" + "function b(){}\n"); // break after comma after a function assertLineBreak("var a = {\n" + " b: function() {},\n" + " c: function() {}\n" + "};\n" + "alert(a);", "var a={b:function(){},\n" + "c:function(){}};\n" + "alert(a)"); } private void assertLineBreak(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } public void testPrettyPrinter() { // Ensure that the pretty printer inserts line breaks at appropriate // places. assertPrettyPrint("(function(){})();","(function() {\n})();\n"); assertPrettyPrint("var a = (function() {});alert(a);", "var a = function() {\n};\nalert(a);\n"); // Check we correctly handle putting brackets around all if clauses so // we can put breakpoints inside statements. assertPrettyPrint("if (1) {}", "if(1) {\n" + "}\n"); assertPrettyPrint("if (1) {alert(\"\");}", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1)alert(\"\");", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1) {alert();alert();}", "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); // Don't add blocks if they weren't there already. assertPrettyPrint("label: alert();", "label:alert();\n"); // But if statements and loops get blocks automagically. assertPrettyPrint("if (1) alert();", "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for (;;) alert();", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("while (1) alert();", "while(1) {\n" + " alert()\n" + "}\n"); // Do we put else clauses in blocks? assertPrettyPrint("if (1) {} else {alert(a);}", "if(1) {\n" + "}else {\n alert(a)\n}\n"); // Do we add blocks to else clauses? assertPrettyPrint("if (1) alert(a); else alert(b);", "if(1) {\n" + " alert(a)\n" + "}else {\n" + " alert(b)\n" + "}\n"); // Do we put for bodies in blocks? assertPrettyPrint("for(;;) { alert();}", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for(;;) {}", "for(;;) {\n" + "}\n"); assertPrettyPrint("for(;;) { alert(); alert(); }", "for(;;) {\n" + " alert();\n" + " alert()\n" + "}\n"); // How about do loops? assertPrettyPrint("do { alert(); } while(true);", "do {\n" + " alert()\n" + "}while(true);\n"); // label? assertPrettyPrint("myLabel: { alert();}", "myLabel: {\n" + " alert()\n" + "}\n"); // Don't move the label on a loop, because then break {label} and // continue {label} won't work. assertPrettyPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;) {\n" + " continue myLabel\n" + "}\n"); assertPrettyPrint("var a;", "var a;\n"); } public void testPrettyPrinter2() { assertPrettyPrint( "if(true) f();", "if(true) {\n" + " f()\n" + "}\n"); assertPrettyPrint( "if (true) { f() } else { g() }", "if(true) {\n" + " f()\n" + "}else {\n" + " g()\n" + "}\n"); assertPrettyPrint( "if(true) f(); for(;;) g();", "if(true) {\n" + " f()\n" + "}\n" + "for(;;) {\n" + " g()\n" + "}\n"); } public void testPrettyPrinter3() { assertPrettyPrint( "try {} catch(e) {}if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} finally {}if (1) {alert();alert();}", "try {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} catch(e) {} finally {} if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); } public void testPrettyPrinter4() { assertPrettyPrint( "function f() {}if (1) {alert();}", "function f() {\n" + "}\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "var f = function() {};if (1) {alert();}", "var f = function() {\n" + "};\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {})();if (1) {alert();}", "(function() {\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {alert();alert();})();if (1) {alert();}", "(function() {\n" + " alert();\n" + " alert()\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); } public void testTypeAnnotations() { assertTypeAnnotations( "/** @constructor */ function Foo(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "function Foo() {\n}\n"); } public void testTypeAnnotationsTypeDef() { // TODO(johnlenz): It would be nice if there were some way to preserve // typedefs but currently they are resolved into the basic types in the // type registry. assertTypeAnnotations( "/** @typedef {Array.<number>} */ goog.java.Long;\n" + "/** @param {!goog.java.Long} a*/\n" + "function f(a){};\n", "goog.java.Long;\n" + "/**\n" + " * @param {(Array|null)} a\n" + " * @return {undefined}\n" + " */\n" + "function f(a) {\n}\n"); } public void testTypeAnnotationsAssign() { assertTypeAnnotations("/** @constructor */ var Foo = function(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "var Foo = function() {\n};\n"); } public void testTypeAnnotationsNamespace() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n"); } public void testTypeAnnotationsMemberSubclass() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};" + "/** @constructor \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo = function(){};" + "/** @interface \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @extends {a.Foo}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMember() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}" + "/** @param {string} foo\n" + " * @return {number} */\n" + "a.Foo.prototype.foo = function(foo) { return 3; };" + "/** @type {string|undefined} */" + "a.Foo.prototype.bar = '';", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n" + " * @param {string} foo\n" + " * @return {number}\n" + " */\n" + "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n" + "/** @type {string} */\n" + "a.Foo.prototype.bar = \"\";\n"); } public void testTypeAnnotationsImplements() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};\n" + "/** @interface */ a.I = function(){};\n" + "/** @interface */ a.I2 = function(){};\n" + "/** @constructor \n @extends {a.Foo}\n" + " * @implements {a.I} \n @implements {a.I2}\n" + "*/ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I2 = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @implements {a.I}\n" + " * @implements {a.I2}\n * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsDispatcher1() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " * @javadispatch \n" + " */\n" + "a.Foo = function(){}", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " * @javadispatch\n" + " */\n" + "a.Foo = function() {\n" + "};\n"); } public void testTypeAnnotationsDispatcher2() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " */\n" + "a.Foo = function(){}\n" + "/**\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {};", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " */\n" + "a.Foo = function() {\n" + "};\n" + "/**\n" + " * @return {undefined}\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {\n" + "};\n"); } public void testU2UFunctionTypeAnnotation() { assertTypeAnnotations( "/** @type {!Function} */ var x = function() {}", "/**\n * @constructor\n */\nvar x = function() {\n};\n"); } public void testEmitUnknownParamTypesAsAllType() { assertTypeAnnotations( "var a = function(x) {}", "/**\n" + " * @param {*} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testOptionalTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {string=} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {string=} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testVariableArgumentsTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {...string} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {...string} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testTempConstructor() { assertTypeAnnotations( "var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" + " /**\n * @constructor\n */\nfunction t2() {}\n" + " t1.prototype = t2.prototype}", "/**\n * @return {undefined}\n */\nvar x = function() {\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t1() {\n }\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t2() {\n }\n" + " t1.prototype = t2.prototype\n};\n" ); } private void assertPrettyPrint(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertTypeAnnotations(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true)); } public void testSubtraction() { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("x - -4"); assertEquals(0, compiler.getErrorCount()); assertEquals( "x- -4", new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build()); } public void testFunctionWithCall() { assertPrint( "var user = new function() {" + "alert(\"foo\")}", "var user=new function(){" + "alert(\"foo\")}"); assertPrint( "var user = new function() {" + "this.name = \"foo\";" + "this.local = function(){alert(this.name)};}", "var user=new function(){" + "this.name=\"foo\";" + "this.local=function(){alert(this.name)}}"); } public void testLineLength() { // list assertLineLength("var aba,bcb,cdc", "var aba,bcb," + "\ncdc"); // operators, and two breaks assertLineLength( "\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"", "\"foo\"+\"bar,baz,bomb\"+" + "\n\"whee\"+\";long-string\"+" + "\n\"aaa\""); // assignment assertLineLength("var abazaba=1234", "var abazaba=" + "\n1234"); // statements assertLineLength("var abab=1;var bab=2", "var abab=1;" + "\nvar bab=2"); // don't break regexes assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a", "var a=/some[reg](ex),with.*we?rd|chars/i;" + "\nvar b=a"); // don't break strings assertLineLength("var a=\"foo,{bar};baz\";var b=a", "var a=\"foo,{bar};baz\";" + "\nvar b=a"); // don't break before post inc/dec assertLineLength("var a=\"a\";a++;var b=\"bbb\";", "var a=\"a\";a++;\n" + "var b=\"bbb\""); } private void assertLineLength(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, 10)); } public void testParsePrintParse() { testReparse("3;"); testReparse("var a = b;"); testReparse("var x, y, z;"); testReparse("try { foo() } catch(e) { bar() }"); testReparse("try { foo() } catch(e) { bar() } finally { stuff() }"); testReparse("try { foo() } finally { stuff() }"); testReparse("throw 'me'"); testReparse("function foo(a) { return a + 4; }"); testReparse("function foo() { return; }"); testReparse("var a = function(a, b) { foo(); return a + b; }"); testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];"); testReparse("v = (5, 6, 7, 8)"); testReparse("d = 34.0; x = 0; y = .3; z = -22"); testReparse("d = -x; t = !x + ~y;"); testReparse("'hi'; /* just a test */ stuff(a,b) \n" + " foo(); // and another \n" + " bar();"); testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;"); testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5"); testReparse("a = (2 + 3) * 4;"); testReparse("a = 1 + (2 + 3) + 4;"); testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());"); testReparse("a = b | c || d ^ e " + "&& f & !g != h << i <= j < k >>> l > m * n % !o"); testReparse("a == b; a != b; a === b; a == b == a;" + " (a == b) == a; a == (b == a);"); testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;"); testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }"); testReparse("for (var i in a) b += i;"); testReparse("for (var i = 0; i < 10; i++){ b /= 2;" + " if (b == 2)break;else continue;}"); testReparse("for (x = 0; x < 10; x++) a /= 2;"); testReparse("for (;;) a++;"); testReparse("while(true) { blah(); }while(true) blah();"); testReparse("do stuff(); while(a>b);"); testReparse("[0, null, , true, false, this];"); testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');"); testReparse("new Foo; new Bar(a, b,c);"); testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;"); testReparse("delete foo['bar']; delete foo;"); testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };"); testReparse("switch(a) { case 2: case 3: stuff(); break;" + "case 4: morestuff(); break; default: done();}"); testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;"); testReparse("a.v = b.v; x['foo'] = y['zoo'];"); testReparse("'test' in x; 3 in x; a in x;"); testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'"); testReparse("x.__proto__;"); } private void testReparse(String code) { Compiler compiler = new Compiler(); Node parse1 = parse(code); Node parse2 = parse(new CodePrinter.Builder(parse1).build()); String explanation = parse1.checkTreeEquals(parse2); assertNull("\nExpected: " + compiler.toSource(parse1) + "\nResult: " + compiler.toSource(parse2) + "\n" + explanation, explanation); } public void testDoLoopIECompatiblity() { // Do loops within IFs cause syntax errors in IE6 and IE7. assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("function f(){if(e1)do foo();while(e2)else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x)do{foo()}while(y);else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x){do{foo()}while(y)}", "if(x){do foo();while(y)}"); assertPrint("if(x)do{foo()}while(y);", "if(x){do foo();while(y)}"); assertPrint("if(x)A:do{foo()}while(y);", "if(x){A:do foo();while(y)}"); assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);", "var i=0;a:do{b:do{i++;break b}while(0)}while(0)"); } public void testFunctionSafariCompatiblity() { // Functions within IFs cause syntax errors on Safari. assertPrint("function f(){if(e1){function goo(){return true}}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("function f(){if(e1)function goo(){return true}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("if(e1){function goo(){return true}}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)function goo(){return true}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)A:function goo(){return true}", "if(e1){A:function goo(){return true}}"); } public void testExponents() { assertPrintNumber("1", 1); assertPrintNumber("10", 10); assertPrintNumber("100", 100); assertPrintNumber("1E3", 1000); assertPrintNumber("1E4", 10000); assertPrintNumber("1E5", 100000); assertPrintNumber("-1", -1); assertPrintNumber("-10", -10); assertPrintNumber("-100", -100); assertPrintNumber("-1E3", -1000); assertPrintNumber("-12341234E4", -123412340000L); assertPrintNumber("1E18", 1000000000000000000L); assertPrintNumber("1E5", 100000.0); assertPrintNumber("100000.1", 100000.1); assertPrintNumber("1.0E-6", 0.000001); } // Make sure to test as both a String and a Node, because // negative numbers do not parse consistently from strings. private void assertPrintNumber(String expected, double number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } private void assertPrintNumber(String expected, int number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } public void testDirectEval() { assertPrint("eval('1');", "eval(\"1\")"); } public void testIndirectEval() { Node n = parse("eval('1');"); assertPrintNode("eval(\"1\")", n); n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp( Node.DIRECT_EVAL, false); assertPrintNode("(0,eval)(\"1\")", n); } public void testFreeCall1() { assertPrint("foo(a);", "foo(a)"); assertPrint("x.foo(a);", "x.foo(a)"); } public void testFreeCall2() { Node n = parse("foo(a);"); assertPrintNode("foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.getType() == Token.CALL); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("foo(a)", n); } public void testFreeCall3() { Node n = parse("x.foo(a);"); assertPrintNode("x.foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.getType() == Token.CALL); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("(0,x.foo)(a)", n); } public void testPrintScript() { // Verify that SCRIPT nodes not marked as synthetic are printed as // blocks. Node ast = new Node(Token.SCRIPT, new Node(Token.EXPR_RESULT, Node.newString("f")), new Node(Token.EXPR_RESULT, Node.newString("g"))); String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build(); assertEquals("\"f\";\n\"g\";\n", result); } public void testObjectLit() { assertPrint("({x:1})", "({x:1})"); assertPrint("var x=({x:1})", "var x={x:1}"); assertPrint("var x={'x':1}", "var x={\"x\":1}"); assertPrint("var x={1:1}", "var x={1:1}"); } public void testGetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {get a() {return 1}}", "var x={get a(){return 1}}"); assertPrint( "var x = {get a() {}, get b(){}}", "var x={get a(){},get b(){}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {get 1() {return 1}}", // "var x={get \"1\"(){return 1}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {get \"()\"() {return 1}}", // "var x={get \"()\"(){return 1}}"); } public void testSetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {set a(x) {return 1}}", "var x={set a(x){return 1}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {set 1(x) {return 1}}", // "var x={set \"1\"(x){return 1}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {set \"(x)\"() {return 1}}", // "var x={set \"(x)\"(){return 1}}"); } public void testNegCollapse() { // Collapse the negative symbol on numbers at generation time, // to match the Rhino behavior. assertPrint("var x = - - 2;", "var x=2"); assertPrint("var x = - (2);", "var x=-2"); } public void testStrict() { String result = parsePrint("var x", false, false, 0, false, true); assertEquals("'use strict';var x", result); } public void testArrayLiteral() { assertPrint("var x = [,];","var x=[,]"); assertPrint("var x = [,,];","var x=[,,]"); assertPrint("var x = [,s,,];","var x=[,s,,]"); assertPrint("var x = [,s];","var x=[,s]"); assertPrint("var x = [s,];","var x=[s]"); } public void testZero() { assertPrint("var x ='\\0';", "var x=\"\\0\""); assertPrint("var x ='\\x00';", "var x=\"\\0\""); assertPrint("var x ='\\u0000';", "var x=\"\\0\""); } }
// You are a professional Java test case writer, please create a test case named `testZero` for the issue `Closure-383`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-383 // // ## Issue-Title: // \0 \x00 and \u0000 are translated to null character // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. write script with string constant "\0" or "\x00" or "\u0000" // // **What is the expected output? What do you see instead?** // I expected a string literal with "\0" (or something like that) // and instead get a string literal with three null character values. // // **What version of the product are you using? On what operating system?** // compiler-20110119.zip on windows 7 x64 // // **Please provide any additional information below.** // // This is causing an issue with IE9 and jQuery.getScript. It causes IE9 to interpret the null character as the end of the file instead of a null character. // // public void testZero() {
1,181
77
1,177
test/com/google/javascript/jscomp/CodePrinterTest.java
test
```markdown ## Issue-ID: Closure-383 ## Issue-Title: \0 \x00 and \u0000 are translated to null character ## Issue-Description: **What steps will reproduce the problem?** 1. write script with string constant "\0" or "\x00" or "\u0000" **What is the expected output? What do you see instead?** I expected a string literal with "\0" (or something like that) and instead get a string literal with three null character values. **What version of the product are you using? On what operating system?** compiler-20110119.zip on windows 7 x64 **Please provide any additional information below.** This is causing an issue with IE9 and jQuery.getScript. It causes IE9 to interpret the null character as the end of the file instead of a null character. ``` You are a professional Java test case writer, please create a test case named `testZero` for the issue `Closure-383`, utilizing the provided issue report information and the following function signature. ```java public void testZero() { ```
1,177
[ "com.google.javascript.jscomp.CodeGenerator" ]
f9199e80c0f7c7eb1afb10cd607a4eba106017f72b23ce24a858b10f7ca1ba53
public void testZero()
// You are a professional Java test case writer, please create a test case named `testZero` for the issue `Closure-383`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-383 // // ## Issue-Title: // \0 \x00 and \u0000 are translated to null character // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. write script with string constant "\0" or "\x00" or "\u0000" // // **What is the expected output? What do you see instead?** // I expected a string literal with "\0" (or something like that) // and instead get a string literal with three null character values. // // **What version of the product are you using? On what operating system?** // compiler-20110119.zip on windows 7 x64 // // **Please provide any additional information below.** // // This is causing an issue with IE9 and jQuery.getScript. It causes IE9 to interpret the null character as the end of the file instead of a null character. // //
Closure
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; public class CodePrinterTest extends TestCase { static Node parse(String js) { return parse(js, false); } static Node parse(String js, boolean checkTypes) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); // Allow getters and setters. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.initOptions(options); Node n = compiler.parseTestCode(js); if (checkTypes) { DefaultPassConfig passConfig = new DefaultPassConfig(null); CompilerPass typeResolver = passConfig.resolveTypes.create(compiler); Node externs = new Node(Token.SCRIPT); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); typeResolver.process(externs, n); CompilerPass inferTypes = passConfig.inferTypes.create(compiler); inferTypes.process(externs, n); } checkUnexpectedErrorsOrWarnings(compiler, 0); return n; } private static void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } String parsePrint(String js, boolean prettyprint, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes, boolean tagAsStrict) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .setTagAsStrict(tagAsStrict) .build(); } String printNode(Node n) { return new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build(); } void assertPrintNode(String expectedJs, Node ast) { assertEquals(expectedJs, printNode(ast)); } public void testPrint() { assertPrint("10 + a + b", "10+a+b"); assertPrint("10 + (30*50)", "10+30*50"); assertPrint("with(x) { x + 3; }", "with(x)x+3"); assertPrint("\"aa'a\"", "\"aa'a\""); assertPrint("\"aa\\\"a\"", "'aa\"a'"); assertPrint("function foo()\n{return 10;}", "function foo(){return 10}"); assertPrint("a instanceof b", "a instanceof b"); assertPrint("typeof(a)", "typeof a"); assertPrint( "var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}", "var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}"); // Safari: needs ';' at the end of a throw statement assertPrint("function foo(){throw 'error';}", "function foo(){throw\"error\";}"); // Safari 3 needs a "{" around a single function assertPrint("if (true) function foo(){return}", "if(true){function foo(){return}}"); assertPrint("var x = 10; { var y = 20; }", "var x=10;var y=20"); assertPrint("while (x-- > 0);", "while(x-- >0);"); assertPrint("x-- >> 1", "x-- >>1"); assertPrint("(function () {})(); ", "(function(){})()"); // Associativity assertPrint("var a,b,c,d;a || (b&& c) && (a || d)", "var a,b,c,d;a||b&&c&&(a||d)"); assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)", "var a,b,c;a||b||c;a*b*c;a|b|c"); assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);", "var a,b,c;a/b/c;a/(b/c);a-(b-c)"); assertPrint("var a,b; a = b = 3;", "var a,b;a=b=3"); assertPrint("var a,b,c,d; a = (b = c = (d = 3));", "var a,b,c,d;a=b=c=d=3"); assertPrint("var a,b,c; a += (b = c += 3);", "var a,b,c;a+=b=c+=3"); assertPrint("var a,b,c; a *= (b -= c);", "var a,b,c;a*=b-=c"); // Break scripts assertPrint("'<script>'", "\"<script>\""); assertPrint("'</script>'", "\"<\\/script>\""); assertPrint("\"</script> </SCRIPT>\"", "\"<\\/script> <\\/SCRIPT>\""); assertPrint("'-->'", "\"--\\>\""); assertPrint("']]>'", "\"]]\\>\""); assertPrint("' --></script>'", "\" --\\><\\/script>\""); assertPrint("/--> <\\/script>/g", "/--\\> <\\/script>/g"); // Break HTML start comments. Certain versions of Webkit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"<\\!-- I am a string --\\>\""); // Precedence assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3"); assertPrint("(delete a[0])/10", "delete a[0]/10"); // optional '()' for new // simple new assertPrint("new A", "new A"); assertPrint("new A()", "new A"); assertPrint("new A('x')", "new A(\"x\")"); // calling instance method directly after new assertPrint("new A().a()", "(new A).a()"); assertPrint("(new A).a()", "(new A).a()"); // this case should be fixed assertPrint("new A('y').a()", "(new A(\"y\")).a()"); // internal class assertPrint("new A.B", "new A.B"); assertPrint("new A.B()", "new A.B"); assertPrint("new A.B('z')", "new A.B(\"z\")"); // calling instance method directly after new internal class assertPrint("(new A.B).a()", "(new A.B).a()"); assertPrint("new A.B().a()", "(new A.B).a()"); // this case should be fixed assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()"); // Operators: make sure we don't convert binary + and unary + into ++ assertPrint("x + +y", "x+ +y"); assertPrint("x - (-y)", "x- -y"); assertPrint("x++ +y", "x++ +y"); assertPrint("x-- -y", "x-- -y"); assertPrint("x++ -y", "x++-y"); // Label assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo"); assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo"); // Object literals. assertPrint("({})", "({})"); assertPrint("var x = {};", "var x={}"); assertPrint("({}).x", "({}).x"); assertPrint("({})['x']", "({})[\"x\"]"); assertPrint("({}) instanceof Object", "({})instanceof Object"); assertPrint("({}) || 1", "({})||1"); assertPrint("1 || ({})", "1||{}"); assertPrint("({}) ? 1 : 2", "({})?1:2"); assertPrint("0 ? ({}) : 2", "0?{}:2"); assertPrint("0 ? 1 : ({})", "0?1:{}"); assertPrint("typeof ({})", "typeof{}"); assertPrint("f({})", "f({})"); // Anonymous function expressions. assertPrint("(function(){})", "(function(){})"); assertPrint("(function(){})()", "(function(){})()"); assertPrint("(function(){})instanceof Object", "(function(){})instanceof Object"); assertPrint("(function(){}).bind().call()", "(function(){}).bind().call()"); assertPrint("var x = function() { };", "var x=function(){}"); assertPrint("var x = function() { }();", "var x=function(){}()"); assertPrint("(function() {}), 2", "(function(){}),2"); // Name functions expression. assertPrint("(function f(){})", "(function f(){})"); // Function declaration. assertPrint("function f(){}", "function f(){}"); // Make sure we don't treat non-latin character escapes as raw strings. assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})"); assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})"); // Test if statement and for statements with single statements in body. assertPrint("if (true) { alert();}", "if(true)alert()"); assertPrint("if (false) {} else {alert(\"a\");}", "if(false);else alert(\"a\")"); assertPrint("for(;;) { alert();};", "for(;;)alert()"); assertPrint("do { alert(); } while(true);", "do alert();while(true)"); assertPrint("myLabel: { alert();}", "myLabel:alert()"); assertPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;)continue myLabel"); // Test nested var statement assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4"); // Non-latin identifier. Make sure we keep them escaped. assertPrint("\\u00fb", "\\u00fb"); assertPrint("\\u00fa=1", "\\u00fa=1"); assertPrint("function \\u00f9(){}", "function \\u00f9(){}"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl"); // Test the right-associative unary operators for spurious parens assertPrint("! ! true", "!!true"); assertPrint("!(!(true))", "!!true"); assertPrint("typeof(void(0))", "typeof void 0"); assertPrint("typeof(void(!0))", "typeof void!0"); assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus assertPrint("+(--x)", "+--x"); assertPrint("-(++x)", "-++x"); // needs a space to prevent an ambiguous parse assertPrint("-(--x)", "- --x"); assertPrint("!(~~5)", "!~~5"); assertPrint("~(a/b)", "~(a/b)"); // Preserve parens to overcome greedy binding of NEW assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)"); assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)"); assertPrint("new (new foobar(x)).factory(baz)", "new (new foobar(x)).factory(baz)"); // Make sure that HOOK is right associative assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e"); assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e"); assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e"); // Test nested ifs assertPrint("if (x) if (y); else;", "if(x)if(y);else;"); // Test comma. assertPrint("a,b,c", "a,b,c"); assertPrint("(a,b),c", "a,b,c"); assertPrint("a,(b,c)", "a,b,c"); assertPrint("x=a,b,c", "x=a,b,c"); assertPrint("x=(a,b),c", "x=(a,b),c"); assertPrint("x=a,(b,c)", "x=a,b,c"); assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c"); assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)"); assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]"); assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]"); assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]"); assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]"); assertPrint("var x=(a,b)", "var x=(a,b)"); assertPrint("var x=a,b,c", "var x=a,b,c"); assertPrint("var x=(a,b),c", "var x=(a,b),c"); assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)"); assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)"); assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)"); assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)"); assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))"); assertPrint("({}) , 1 , 2", "({}),1,2"); assertPrint("({}) , {} , {}", "({}),{},{}"); // EMPTY nodes assertPrint("if (x){}", "if(x);"); assertPrint("if(x);", "if(x);"); assertPrint("if(x)if(y);", "if(x)if(y);"); assertPrint("if(x){if(y);}", "if(x)if(y);"); assertPrint("if(x){if(y){};;;}", "if(x)if(y);"); assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}"); } public void testPrintArray() { assertPrint("[void 0, void 0]", "[void 0,void 0]"); assertPrint("[undefined, undefined]", "[undefined,undefined]"); assertPrint("[ , , , undefined]", "[,,,undefined]"); assertPrint("[ , , , 0]", "[,,,0]"); } public void testHook() { assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2"); assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2"); assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2"); assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2"); assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2"); assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2"); assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2"); assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)"); assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x"); assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x"); assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x"); assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3"); } public void testPrintInOperatorInForLoop() { // Check for in expression in for's init expression. // Check alone, with + (higher precedence), with ?: (lower precedence), // and with conditional. assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}", "var a={};for(var i=(\"length\"in a);i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}", "var a={};for(var i=(\"length\"in a)?0:1;i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}", "var a={};for(var i=(\"length\"in a)+1;i;);"); assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);", "var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);"); assertPrint("var a={};for (var i = a || a || (\"size\" in a);;);", "var a={};for(var i=a||a||(\"size\"in a);;);"); // Test works with unary operators and calls. assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}", "var a={};for(var i=-(\"length\"in a);i;);"); assertPrint("var a={};function b_(p){ return p;};" + "for(var i=1,j=b_(\"length\" in a);;) {}", "var a={};function b_(p){return p}" + "for(var i=1,j=b_(\"length\"in a);;);"); // Test we correctly handle an in operator in the test clause. assertPrint("var a={}; for (;(\"length\" in a);) {}", "var a={};for(;\"length\"in a;);"); } public void testLiteralProperty() { assertPrint("(64).toString()", "(64).toString()"); } private void assertPrint(String js, String expected) { parse(expected); // validate the expected string is valid js assertEquals(expected, parsePrint(js, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } // Make sure that the code generator doesn't associate an // else clause with the wrong if clause. public void testAmbiguousElseClauses() { assertPrintNode("if(x)if(y);else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), // ELSE clause for the inner if new Node(Token.BLOCK))))); assertPrintNode("if(x){if(y);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK))), // ELSE clause for the outer if new Node(Token.BLOCK))); assertPrintNode("if(x)if(y);else{if(z);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "z"), new Node(Token.BLOCK))))), // ELSE clause for the outermost if new Node(Token.BLOCK))); } public void testLineBreak() { // line break after function if in a statement context assertLineBreak("function a() {}\n" + "function b() {}", "function a(){}\n" + "function b(){}\n"); // line break after ; after a function assertLineBreak("var a = {};\n" + "a.foo = function () {}\n" + "function b() {}", "var a={};a.foo=function(){};\n" + "function b(){}\n"); // break after comma after a function assertLineBreak("var a = {\n" + " b: function() {},\n" + " c: function() {}\n" + "};\n" + "alert(a);", "var a={b:function(){},\n" + "c:function(){}};\n" + "alert(a)"); } private void assertLineBreak(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } public void testPrettyPrinter() { // Ensure that the pretty printer inserts line breaks at appropriate // places. assertPrettyPrint("(function(){})();","(function() {\n})();\n"); assertPrettyPrint("var a = (function() {});alert(a);", "var a = function() {\n};\nalert(a);\n"); // Check we correctly handle putting brackets around all if clauses so // we can put breakpoints inside statements. assertPrettyPrint("if (1) {}", "if(1) {\n" + "}\n"); assertPrettyPrint("if (1) {alert(\"\");}", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1)alert(\"\");", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1) {alert();alert();}", "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); // Don't add blocks if they weren't there already. assertPrettyPrint("label: alert();", "label:alert();\n"); // But if statements and loops get blocks automagically. assertPrettyPrint("if (1) alert();", "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for (;;) alert();", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("while (1) alert();", "while(1) {\n" + " alert()\n" + "}\n"); // Do we put else clauses in blocks? assertPrettyPrint("if (1) {} else {alert(a);}", "if(1) {\n" + "}else {\n alert(a)\n}\n"); // Do we add blocks to else clauses? assertPrettyPrint("if (1) alert(a); else alert(b);", "if(1) {\n" + " alert(a)\n" + "}else {\n" + " alert(b)\n" + "}\n"); // Do we put for bodies in blocks? assertPrettyPrint("for(;;) { alert();}", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for(;;) {}", "for(;;) {\n" + "}\n"); assertPrettyPrint("for(;;) { alert(); alert(); }", "for(;;) {\n" + " alert();\n" + " alert()\n" + "}\n"); // How about do loops? assertPrettyPrint("do { alert(); } while(true);", "do {\n" + " alert()\n" + "}while(true);\n"); // label? assertPrettyPrint("myLabel: { alert();}", "myLabel: {\n" + " alert()\n" + "}\n"); // Don't move the label on a loop, because then break {label} and // continue {label} won't work. assertPrettyPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;) {\n" + " continue myLabel\n" + "}\n"); assertPrettyPrint("var a;", "var a;\n"); } public void testPrettyPrinter2() { assertPrettyPrint( "if(true) f();", "if(true) {\n" + " f()\n" + "}\n"); assertPrettyPrint( "if (true) { f() } else { g() }", "if(true) {\n" + " f()\n" + "}else {\n" + " g()\n" + "}\n"); assertPrettyPrint( "if(true) f(); for(;;) g();", "if(true) {\n" + " f()\n" + "}\n" + "for(;;) {\n" + " g()\n" + "}\n"); } public void testPrettyPrinter3() { assertPrettyPrint( "try {} catch(e) {}if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} finally {}if (1) {alert();alert();}", "try {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} catch(e) {} finally {} if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); } public void testPrettyPrinter4() { assertPrettyPrint( "function f() {}if (1) {alert();}", "function f() {\n" + "}\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "var f = function() {};if (1) {alert();}", "var f = function() {\n" + "};\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {})();if (1) {alert();}", "(function() {\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {alert();alert();})();if (1) {alert();}", "(function() {\n" + " alert();\n" + " alert()\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); } public void testTypeAnnotations() { assertTypeAnnotations( "/** @constructor */ function Foo(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "function Foo() {\n}\n"); } public void testTypeAnnotationsTypeDef() { // TODO(johnlenz): It would be nice if there were some way to preserve // typedefs but currently they are resolved into the basic types in the // type registry. assertTypeAnnotations( "/** @typedef {Array.<number>} */ goog.java.Long;\n" + "/** @param {!goog.java.Long} a*/\n" + "function f(a){};\n", "goog.java.Long;\n" + "/**\n" + " * @param {(Array|null)} a\n" + " * @return {undefined}\n" + " */\n" + "function f(a) {\n}\n"); } public void testTypeAnnotationsAssign() { assertTypeAnnotations("/** @constructor */ var Foo = function(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "var Foo = function() {\n};\n"); } public void testTypeAnnotationsNamespace() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n"); } public void testTypeAnnotationsMemberSubclass() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};" + "/** @constructor \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo = function(){};" + "/** @interface \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @extends {a.Foo}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMember() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}" + "/** @param {string} foo\n" + " * @return {number} */\n" + "a.Foo.prototype.foo = function(foo) { return 3; };" + "/** @type {string|undefined} */" + "a.Foo.prototype.bar = '';", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n" + " * @param {string} foo\n" + " * @return {number}\n" + " */\n" + "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n" + "/** @type {string} */\n" + "a.Foo.prototype.bar = \"\";\n"); } public void testTypeAnnotationsImplements() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};\n" + "/** @interface */ a.I = function(){};\n" + "/** @interface */ a.I2 = function(){};\n" + "/** @constructor \n @extends {a.Foo}\n" + " * @implements {a.I} \n @implements {a.I2}\n" + "*/ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I2 = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @implements {a.I}\n" + " * @implements {a.I2}\n * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsDispatcher1() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " * @javadispatch \n" + " */\n" + "a.Foo = function(){}", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " * @javadispatch\n" + " */\n" + "a.Foo = function() {\n" + "};\n"); } public void testTypeAnnotationsDispatcher2() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " */\n" + "a.Foo = function(){}\n" + "/**\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {};", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " */\n" + "a.Foo = function() {\n" + "};\n" + "/**\n" + " * @return {undefined}\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {\n" + "};\n"); } public void testU2UFunctionTypeAnnotation() { assertTypeAnnotations( "/** @type {!Function} */ var x = function() {}", "/**\n * @constructor\n */\nvar x = function() {\n};\n"); } public void testEmitUnknownParamTypesAsAllType() { assertTypeAnnotations( "var a = function(x) {}", "/**\n" + " * @param {*} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testOptionalTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {string=} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {string=} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testVariableArgumentsTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {...string} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {...string} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testTempConstructor() { assertTypeAnnotations( "var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" + " /**\n * @constructor\n */\nfunction t2() {}\n" + " t1.prototype = t2.prototype}", "/**\n * @return {undefined}\n */\nvar x = function() {\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t1() {\n }\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t2() {\n }\n" + " t1.prototype = t2.prototype\n};\n" ); } private void assertPrettyPrint(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertTypeAnnotations(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true)); } public void testSubtraction() { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("x - -4"); assertEquals(0, compiler.getErrorCount()); assertEquals( "x- -4", new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build()); } public void testFunctionWithCall() { assertPrint( "var user = new function() {" + "alert(\"foo\")}", "var user=new function(){" + "alert(\"foo\")}"); assertPrint( "var user = new function() {" + "this.name = \"foo\";" + "this.local = function(){alert(this.name)};}", "var user=new function(){" + "this.name=\"foo\";" + "this.local=function(){alert(this.name)}}"); } public void testLineLength() { // list assertLineLength("var aba,bcb,cdc", "var aba,bcb," + "\ncdc"); // operators, and two breaks assertLineLength( "\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"", "\"foo\"+\"bar,baz,bomb\"+" + "\n\"whee\"+\";long-string\"+" + "\n\"aaa\""); // assignment assertLineLength("var abazaba=1234", "var abazaba=" + "\n1234"); // statements assertLineLength("var abab=1;var bab=2", "var abab=1;" + "\nvar bab=2"); // don't break regexes assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a", "var a=/some[reg](ex),with.*we?rd|chars/i;" + "\nvar b=a"); // don't break strings assertLineLength("var a=\"foo,{bar};baz\";var b=a", "var a=\"foo,{bar};baz\";" + "\nvar b=a"); // don't break before post inc/dec assertLineLength("var a=\"a\";a++;var b=\"bbb\";", "var a=\"a\";a++;\n" + "var b=\"bbb\""); } private void assertLineLength(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, 10)); } public void testParsePrintParse() { testReparse("3;"); testReparse("var a = b;"); testReparse("var x, y, z;"); testReparse("try { foo() } catch(e) { bar() }"); testReparse("try { foo() } catch(e) { bar() } finally { stuff() }"); testReparse("try { foo() } finally { stuff() }"); testReparse("throw 'me'"); testReparse("function foo(a) { return a + 4; }"); testReparse("function foo() { return; }"); testReparse("var a = function(a, b) { foo(); return a + b; }"); testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];"); testReparse("v = (5, 6, 7, 8)"); testReparse("d = 34.0; x = 0; y = .3; z = -22"); testReparse("d = -x; t = !x + ~y;"); testReparse("'hi'; /* just a test */ stuff(a,b) \n" + " foo(); // and another \n" + " bar();"); testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;"); testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5"); testReparse("a = (2 + 3) * 4;"); testReparse("a = 1 + (2 + 3) + 4;"); testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());"); testReparse("a = b | c || d ^ e " + "&& f & !g != h << i <= j < k >>> l > m * n % !o"); testReparse("a == b; a != b; a === b; a == b == a;" + " (a == b) == a; a == (b == a);"); testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;"); testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }"); testReparse("for (var i in a) b += i;"); testReparse("for (var i = 0; i < 10; i++){ b /= 2;" + " if (b == 2)break;else continue;}"); testReparse("for (x = 0; x < 10; x++) a /= 2;"); testReparse("for (;;) a++;"); testReparse("while(true) { blah(); }while(true) blah();"); testReparse("do stuff(); while(a>b);"); testReparse("[0, null, , true, false, this];"); testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');"); testReparse("new Foo; new Bar(a, b,c);"); testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;"); testReparse("delete foo['bar']; delete foo;"); testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };"); testReparse("switch(a) { case 2: case 3: stuff(); break;" + "case 4: morestuff(); break; default: done();}"); testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;"); testReparse("a.v = b.v; x['foo'] = y['zoo'];"); testReparse("'test' in x; 3 in x; a in x;"); testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'"); testReparse("x.__proto__;"); } private void testReparse(String code) { Compiler compiler = new Compiler(); Node parse1 = parse(code); Node parse2 = parse(new CodePrinter.Builder(parse1).build()); String explanation = parse1.checkTreeEquals(parse2); assertNull("\nExpected: " + compiler.toSource(parse1) + "\nResult: " + compiler.toSource(parse2) + "\n" + explanation, explanation); } public void testDoLoopIECompatiblity() { // Do loops within IFs cause syntax errors in IE6 and IE7. assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("function f(){if(e1)do foo();while(e2)else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x)do{foo()}while(y);else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x){do{foo()}while(y)}", "if(x){do foo();while(y)}"); assertPrint("if(x)do{foo()}while(y);", "if(x){do foo();while(y)}"); assertPrint("if(x)A:do{foo()}while(y);", "if(x){A:do foo();while(y)}"); assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);", "var i=0;a:do{b:do{i++;break b}while(0)}while(0)"); } public void testFunctionSafariCompatiblity() { // Functions within IFs cause syntax errors on Safari. assertPrint("function f(){if(e1){function goo(){return true}}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("function f(){if(e1)function goo(){return true}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("if(e1){function goo(){return true}}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)function goo(){return true}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)A:function goo(){return true}", "if(e1){A:function goo(){return true}}"); } public void testExponents() { assertPrintNumber("1", 1); assertPrintNumber("10", 10); assertPrintNumber("100", 100); assertPrintNumber("1E3", 1000); assertPrintNumber("1E4", 10000); assertPrintNumber("1E5", 100000); assertPrintNumber("-1", -1); assertPrintNumber("-10", -10); assertPrintNumber("-100", -100); assertPrintNumber("-1E3", -1000); assertPrintNumber("-12341234E4", -123412340000L); assertPrintNumber("1E18", 1000000000000000000L); assertPrintNumber("1E5", 100000.0); assertPrintNumber("100000.1", 100000.1); assertPrintNumber("1.0E-6", 0.000001); } // Make sure to test as both a String and a Node, because // negative numbers do not parse consistently from strings. private void assertPrintNumber(String expected, double number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } private void assertPrintNumber(String expected, int number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } public void testDirectEval() { assertPrint("eval('1');", "eval(\"1\")"); } public void testIndirectEval() { Node n = parse("eval('1');"); assertPrintNode("eval(\"1\")", n); n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp( Node.DIRECT_EVAL, false); assertPrintNode("(0,eval)(\"1\")", n); } public void testFreeCall1() { assertPrint("foo(a);", "foo(a)"); assertPrint("x.foo(a);", "x.foo(a)"); } public void testFreeCall2() { Node n = parse("foo(a);"); assertPrintNode("foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.getType() == Token.CALL); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("foo(a)", n); } public void testFreeCall3() { Node n = parse("x.foo(a);"); assertPrintNode("x.foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.getType() == Token.CALL); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("(0,x.foo)(a)", n); } public void testPrintScript() { // Verify that SCRIPT nodes not marked as synthetic are printed as // blocks. Node ast = new Node(Token.SCRIPT, new Node(Token.EXPR_RESULT, Node.newString("f")), new Node(Token.EXPR_RESULT, Node.newString("g"))); String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build(); assertEquals("\"f\";\n\"g\";\n", result); } public void testObjectLit() { assertPrint("({x:1})", "({x:1})"); assertPrint("var x=({x:1})", "var x={x:1}"); assertPrint("var x={'x':1}", "var x={\"x\":1}"); assertPrint("var x={1:1}", "var x={1:1}"); } public void testGetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {get a() {return 1}}", "var x={get a(){return 1}}"); assertPrint( "var x = {get a() {}, get b(){}}", "var x={get a(){},get b(){}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {get 1() {return 1}}", // "var x={get \"1\"(){return 1}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {get \"()\"() {return 1}}", // "var x={get \"()\"(){return 1}}"); } public void testSetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {set a(x) {return 1}}", "var x={set a(x){return 1}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {set 1(x) {return 1}}", // "var x={set \"1\"(x){return 1}}"); // Valid ES5 but Rhino doesn't accept this yet. // assertPrint( // "var x = {set \"(x)\"() {return 1}}", // "var x={set \"(x)\"(){return 1}}"); } public void testNegCollapse() { // Collapse the negative symbol on numbers at generation time, // to match the Rhino behavior. assertPrint("var x = - - 2;", "var x=2"); assertPrint("var x = - (2);", "var x=-2"); } public void testStrict() { String result = parsePrint("var x", false, false, 0, false, true); assertEquals("'use strict';var x", result); } public void testArrayLiteral() { assertPrint("var x = [,];","var x=[,]"); assertPrint("var x = [,,];","var x=[,,]"); assertPrint("var x = [,s,,];","var x=[,s,,]"); assertPrint("var x = [,s];","var x=[,s]"); assertPrint("var x = [s,];","var x=[s]"); } public void testZero() { assertPrint("var x ='\\0';", "var x=\"\\0\""); assertPrint("var x ='\\x00';", "var x=\"\\0\""); assertPrint("var x ='\\u0000';", "var x=\"\\0\""); } }
@Test public void handlesControlCodeInAttributeName() { Document doc = Jsoup.parse("<p><a \06=foo>One</a><a/\06=bar><a foo\06=bar>Two</a></p>"); assertEquals("<p><a>One</a><a></a><a foo=\"bar\">Two</a></p>", doc.body().html()); }
org.jsoup.parser.HtmlParserTest::handlesControlCodeInAttributeName
src/test/java/org/jsoup/parser/HtmlParserTest.java
947
src/test/java/org/jsoup/parser/HtmlParserTest.java
handlesControlCodeInAttributeName
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.*; import org.jsoup.select.Elements; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** Tests for the Parser @author Jonathan Hedley, jonathan@hedley.net */ public class HtmlParserTest { @Test public void parsesSimpleDocument() { String html = "<html><head><title>First!</title></head><body><p>First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); Element img = p.child(0); assertEquals("foo.png", img.attr("src")); assertEquals("img", img.tagName()); } @Test public void parsesRoughAttributes() { String html = "<html><head><title>First!</title></head><body><p class=\"foo > bar\">First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); assertEquals("foo > bar", p.attr("class")); } @Test public void parsesQuiteRoughAttributes() { String html = "<p =a>One<a <p>Something</p>Else"; // this gets a <p> with attr '=a' and an <a tag with an attribue named '<p'; and then auto-recreated Document doc = Jsoup.parse(html); assertEquals("<p =a>One<a <p>Something</a></p>\n" + "<a <p>Else</a>", doc.body().html()); doc = Jsoup.parse("<p .....>"); assertEquals("<p .....></p>", doc.body().html()); } @Test public void parsesComments() { String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --><p>Hello</p></body></html>"; Document doc = Jsoup.parse(html); Element body = doc.body(); Comment comment = (Comment) body.childNode(1); // comment should not be sub of img, as it's an empty tag assertEquals(" <table><tr><td></table> ", comment.getData()); Element p = body.child(1); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); } @Test public void parsesUnterminatedComments() { String html = "<p>Hello<!-- <tr><td>"; Document doc = Jsoup.parse(html); Element p = doc.getElementsByTag("p").get(0); assertEquals("Hello", p.text()); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); Comment comment = (Comment) p.childNode(1); assertEquals(" <tr><td>", comment.getData()); } @Test public void dropsUnterminatedTag() { // jsoup used to parse this to <p>, but whatwg, webkit will drop. String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(0, doc.getElementsByTag("p").size()); assertEquals("", doc.text()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); assertEquals("", doc.text()); } @Test public void dropsUnterminatedAttribute() { // jsoup used to parse this to <p id="foo">, but whatwg, webkit will drop. String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); assertEquals("", doc.text()); } @Test public void parsesUnterminatedTextarea() { // don't parse right to end, but break on <p> Document doc = Jsoup.parse("<body><p><textarea>one<p>two"); Element t = doc.select("textarea").first(); assertEquals("one", t.text()); assertEquals("two", doc.select("p").get(1).text()); } @Test public void parsesUnterminatedOption() { // bit weird this -- browsers and spec get stuck in select until there's a </select> Document doc = Jsoup.parse("<body><p><select><option>One<option>Two</p><p>Three</p>"); Elements options = doc.select("option"); assertEquals(2, options.size()); assertEquals("One", options.first().text()); assertEquals("TwoThree", options.last().text()); } @Test public void testSpaceAfterTag() { Document doc = Jsoup.parse("<div > <a name=\"top\"></a ><p id=1 >Hello</p></div>"); assertEquals("<div> <a name=\"top\"></a><p id=\"1\">Hello</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void createsDocumentStructure() { String html = "<meta name=keywords /><link rel=stylesheet /><title>jsoup</title><p>Hello world</p>"; Document doc = Jsoup.parse(html); Element head = doc.head(); Element body = doc.body(); assertEquals(1, doc.children().size()); // root node: contains html node assertEquals(2, doc.child(0).children().size()); // html node: head and body assertEquals(3, head.children().size()); assertEquals(1, body.children().size()); assertEquals("keywords", head.getElementsByTag("meta").get(0).attr("name")); assertEquals(0, body.getElementsByTag("meta").size()); assertEquals("jsoup", doc.title()); assertEquals("Hello world", body.text()); assertEquals("Hello world", body.children().get(0).text()); } @Test public void createsStructureFromBodySnippet() { // the bar baz stuff naturally goes into the body, but the 'foo' goes into root, and the normalisation routine // needs to move into the start of the body String html = "foo <b>bar</b> baz"; Document doc = Jsoup.parse(html); assertEquals("foo bar baz", doc.text()); } @Test public void handlesEscapedData() { String html = "<div title='Surf &amp; Turf'>Reef &amp; Beef</div>"; Document doc = Jsoup.parse(html); Element div = doc.getElementsByTag("div").get(0); assertEquals("Surf & Turf", div.attr("title")); assertEquals("Reef & Beef", div.text()); } @Test public void handlesDataOnlyTags() { String t = "<style>font-family: bold</style>"; List<Element> tels = Jsoup.parse(t).getElementsByTag("style"); assertEquals("font-family: bold", tels.get(0).data()); assertEquals("", tels.get(0).text()); String s = "<p>Hello</p><script>obj.insert('<a rel=\"none\" />');\ni++;</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("obj.insert('<a rel=\"none\" />');\ni++;", doc.data()); } @Test public void handlesTextAfterData() { String h = "<html><body>pre <script>inner</script> aft</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head></head><body>pre <script>inner</script> aft</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesTextArea() { Document doc = Jsoup.parse("<textarea>Hello</textarea>"); Elements els = doc.select("textarea"); assertEquals("Hello", els.text()); assertEquals("Hello", els.val()); } @Test public void preservesSpaceInTextArea() { // preserve because the tag is marked as preserve white space Document doc = Jsoup.parse("<textarea>\n\tOne\n\tTwo\n\tThree\n</textarea>"); String expect = "One\n\tTwo\n\tThree"; // the leading and trailing spaces are dropped as a convenience to authors Element el = doc.select("textarea").first(); assertEquals(expect, el.text()); assertEquals(expect, el.val()); assertEquals(expect, el.html()); assertEquals("<textarea>\n\t" + expect + "\n</textarea>", el.outerHtml()); // but preserved in round-trip html } @Test public void preservesSpaceInScript() { // preserve because it's content is a data node Document doc = Jsoup.parse("<script>\nOne\n\tTwo\n\tThree\n</script>"); String expect = "\nOne\n\tTwo\n\tThree\n"; Element el = doc.select("script").first(); assertEquals(expect, el.data()); assertEquals("One\n\tTwo\n\tThree", el.html()); assertEquals("<script>" + expect + "</script>", el.outerHtml()); } @Test public void doesNotCreateImplicitLists() { // old jsoup used to wrap this in <ul>, but that's not to spec String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should NOT have created a default ul. assertEquals(0, ol.size()); Elements lis = doc.select("li"); assertEquals(2, lis.size()); assertEquals("body", lis.first().parent().tagName()); // no fiddling with non-implicit lists String h2 = "<ol><li><p>Point the first<li><p>Point the second"; Document doc2 = Jsoup.parse(h2); assertEquals(0, doc2.select("ul").size()); assertEquals(1, doc2.select("ol").size()); assertEquals(2, doc2.select("ol li").size()); assertEquals(2, doc2.select("ol li p").size()); assertEquals(1, doc2.select("ol li").get(0).children().size()); // one p in first li } @Test public void discardsNakedTds() { // jsoup used to make this into an implicit table; but browsers make it into a text run String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("Hello<p>There</p><p>now</p>", TextUtil.stripNewlines(doc.body().html())); // <tbody> is introduced if no implicitly creating table, but allows tr to be directly under table } @Test public void handlesNestedImplicitTable() { Document doc = Jsoup.parse("<table><td>1</td></tr> <td>2</td></tr> <td> <table><td>3</td> <td>4</td></table> <tr><td>5</table>"); assertEquals("<table><tbody><tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td> <table><tbody><tr><td>3</td> <td>4</td></tr></tbody></table> </td></tr><tr><td>5</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesWhatWgExpensesTableExample() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/tabular-data.html#examples-0 Document doc = Jsoup.parse("<table> <colgroup> <col> <colgroup> <col> <col> <col> <thead> <tr> <th> <th>2008 <th>2007 <th>2006 <tbody> <tr> <th scope=rowgroup> Research and development <td> $ 1,109 <td> $ 782 <td> $ 712 <tr> <th scope=row> Percentage of net sales <td> 3.4% <td> 3.3% <td> 3.7% <tbody> <tr> <th scope=rowgroup> Selling, general, and administrative <td> $ 3,761 <td> $ 2,963 <td> $ 2,433 <tr> <th scope=row> Percentage of net sales <td> 11.6% <td> 12.3% <td> 12.6% </table>"); assertEquals("<table> <colgroup> <col> </colgroup><colgroup> <col> <col> <col> </colgroup><thead> <tr> <th> </th><th>2008 </th><th>2007 </th><th>2006 </th></tr></thead><tbody> <tr> <th scope=\"rowgroup\"> Research and development </th><td> $ 1,109 </td><td> $ 782 </td><td> $ 712 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 3.4% </td><td> 3.3% </td><td> 3.7% </td></tr></tbody><tbody> <tr> <th scope=\"rowgroup\"> Selling, general, and administrative </th><td> $ 3,761 </td><td> $ 2,963 </td><td> $ 2,433 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 11.6% </td><td> 12.3% </td><td> 12.6% </td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesTbodyTable() { Document doc = Jsoup.parse("<html><head></head><body><table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table></body></html>"); assertEquals("<table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesImplicitCaptionClose() { Document doc = Jsoup.parse("<table><caption>A caption<td>One<td>Two"); assertEquals("<table><caption>A caption</caption><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void noTableDirectInTable() { Document doc = Jsoup.parse("<table> <td>One <td><table><td>Two</table> <table><td>Three"); assertEquals("<table> <tbody><tr><td>One </td><td><table><tbody><tr><td>Two</td></tr></tbody></table> <table><tbody><tr><td>Three</td></tr></tbody></table></td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void ignoresDupeEndTrTag() { Document doc = Jsoup.parse("<table><tr><td>One</td><td><table><tr><td>Two</td></tr></tr></table></td><td>Three</td></tr></table>"); // two </tr></tr>, must ignore or will close table assertEquals("<table><tbody><tr><td>One</td><td><table><tbody><tr><td>Two</td></tr></tbody></table></td><td>Three</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { // only listen to the first base href String h = "<a href=1>#</a><base href='/2/'><a href='3'>#</a><base href='http://bar'><a href=/4>#</a>"; Document doc = Jsoup.parse(h, "http://foo/"); assertEquals("http://foo/2/", doc.baseUri()); // gets set once, so doc and descendants have first only Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/2/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://foo/2/", anchors.get(2).baseUri()); assertEquals("http://foo/2/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://foo/4", anchors.get(2).absUrl("href")); } @Test public void handlesProtocolRelativeUrl() { String base = "https://example.com/"; String html = "<img src='//example.net/img.jpg'>"; Document doc = Jsoup.parse(html, base); Element el = doc.select("img").first(); assertEquals("https://example.net/img.jpg", el.absUrl("src")); } @Test public void handlesCdata() { // todo: as this is html namespace, should actually treat as bogus comment, not cdata. keep as cdata for now String h = "<div id=1><![CDATA[<html>\n<foo><&amp;]]></div>"; // the &amp; in there should remain literal Document doc = Jsoup.parse(h); Element div = doc.getElementById("1"); assertEquals("<html> <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node } @Test public void handlesUnclosedCdataAtEOF() { // https://github.com/jhy/jsoup/issues/349 would crash, as character reader would try to seek past EOF String h = "<![CDATA[]]"; Document doc = Jsoup.parse(h); assertEquals(1, doc.body().childNodeSize()); } @Test public void handlesInvalidStartTags() { String h = "<div>Hello < There <&amp;></div>"; // parse to <div {#text=Hello < There <&>}> Document doc = Jsoup.parse(h); assertEquals("Hello < There <&>", doc.select("div").first().text()); } @Test public void handlesUnknownTags() { String h = "<div><foo title=bar>Hello<foo title=qux>there</foo></div>"; Document doc = Jsoup.parse(h); Elements foos = doc.select("foo"); assertEquals(2, foos.size()); assertEquals("bar", foos.first().attr("title")); assertEquals("qux", foos.last().attr("title")); assertEquals("there", foos.last().text()); } @Test public void handlesUnknownInlineTags() { String h = "<p><cust>Test</cust></p><p><cust><cust>Test</cust></cust></p>"; Document doc = Jsoup.parseBodyFragment(h); String out = doc.body().html(); assertEquals(h, TextUtil.stripNewlines(out)); } @Test public void parsesBodyFragment() { String h = "<!-- comment --><p><a href='foo'>One</a></p>"; Document doc = Jsoup.parseBodyFragment(h, "http://example.com"); assertEquals("<body><!-- comment --><p><a href=\"foo\">One</a></p></body>", TextUtil.stripNewlines(doc.body().outerHtml())); assertEquals("http://example.com/foo", doc.select("a").first().absUrl("href")); } @Test public void handlesUnknownNamespaceTags() { // note that the first foo:bar should not really be allowed to be self closing, if parsed in html mode. String h = "<foo:bar id='1' /><abc:def id=2>Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>"; Document doc = Jsoup.parse(h); assertEquals("<foo:bar id=\"1\" /><abc:def id=\"2\">Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesKnownEmptyBlocks() { // if a known tag, allow self closing outside of spec, but force an end tag. unknown tags can be self closing. String h = "<div id='1' /><script src='/foo' /><div id=2><img /><img></div><a id=3 /><i /><foo /><foo>One</foo> <hr /> hr text <hr> hr text two"; Document doc = Jsoup.parse(h); assertEquals("<div id=\"1\"></div><script src=\"/foo\"></script><div id=\"2\"><img><img></div><a id=\"3\"></a><i></i><foo /><foo>One</foo> <hr> hr text <hr> hr text two", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesSolidusAtAttributeEnd() { // this test makes sure [<a href=/>link</a>] is parsed as [<a href="/">link</a>], not [<a href="" /><a>link</a>] String h = "<a href=/>link</a>"; Document doc = Jsoup.parse(h); assertEquals("<a href=\"/\">link</a>", doc.body().html()); } @Test public void handlesMultiClosingBody() { String h = "<body><p>Hello</body><p>there</p></body></body></html><p>now"; Document doc = Jsoup.parse(h); assertEquals(3, doc.select("p").size()); assertEquals(3, doc.body().children().size()); } @Test public void handlesUnclosedDefinitionLists() { // jsoup used to create a <dl>, but that's not to spec String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(0, doc.select("dl").size()); // no auto dl assertEquals(4, doc.select("dt, dd").size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @Test public void handlesBlocksInDefinitions() { // per the spec, dt and dd are inline, but in practise are block String h = "<dl><dt><div id=1>Term</div></dt><dd><div id=2>Def</div></dd></dl>"; Document doc = Jsoup.parse(h); assertEquals("dt", doc.select("#1").first().parent().tagName()); assertEquals("dd", doc.select("#2").first().parent().tagName()); assertEquals("<dl><dt><div id=\"1\">Term</div></dt><dd><div id=\"2\">Def</div></dd></dl>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesFrames() { String h = "<html><head><script></script><noscript></noscript></head><frameset><frame src=foo></frame><frame src=foo></frameset></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\"><frame src=\"foo\"></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body auto vivification } @Test public void ignoresContentAfterFrameset() { String h = "<html><head><title>One</title></head><frameset><frame /><frame /></frameset><table></table></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><title>One</title></head><frameset><frame><frame></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body, no table. No crash! } @Test public void handlesJavadocFont() { String h = "<TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A>&nbsp;</TD>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("Deprecated", a.text()); assertEquals("font", a.child(0).tagName()); assertEquals("b", a.child(0).child(0).tagName()); } @Test public void handlesBaseWithoutHref() { String h = "<head><base target='_blank'></head><body><a href=/foo>Test</a></body>"; Document doc = Jsoup.parse(h, "http://example.com/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://example.com/foo", a.attr("abs:href")); } @Test public void normalisesDocument() { String h = "<!doctype html>One<html>Two<head>Three<link></head>Four<body>Five </body>Six </html>Seven "; Document doc = Jsoup.parse(h); assertEquals("<!doctype html><html><head></head><body>OneTwoThree<link>FourFive Six Seven </body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesEmptyDocument() { Document doc = Jsoup.parse(""); assertEquals("<html><head></head><body></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesHeadlessBody() { Document doc = Jsoup.parse("<html><body><span class=\"foo\">bar</span>"); assertEquals("<html><head></head><body><span class=\"foo\">bar</span></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisedBodyAfterContent() { Document doc = Jsoup.parse("<font face=Arial><body class=name><div>One</div></body></font>"); assertEquals("<html><head></head><body class=\"name\"><font face=\"Arial\"><div>One</div></font></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void findsCharsetInMalformedMeta() { String h = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"; // example cited for reason of html5's <meta charset> element Document doc = Jsoup.parse(h); assertEquals("gb2312", doc.select("meta").attr("charset")); } @Test public void testHgroup() { // jsoup used to not allow hroup in h{n}, but that's not in spec, and browsers are OK Document doc = Jsoup.parse("<h1>Hello <h2>There <hgroup><h1>Another<h2>headline</hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup>"); assertEquals("<h1>Hello </h1><h2>There <hgroup><h1>Another</h1><h2>headline</h2></hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup></h2>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def>There</abc-def>"); assertEquals("<abc_def id=\"1\">Hello</abc_def> <abc-def>There</abc-def>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHeaderContents() { // h* tags (h1 .. h9) in browsers can handle any internal content other than other h*. which is not per any // spec, which defines them as containing phrasing content only. so, reality over theory. Document doc = Jsoup.parse("<h1>Hello <div>There</div> now</h1> <h2>More <h3>Content</h3></h2>"); assertEquals("<h1>Hello <div>There</div> now</h1> <h2>More </h2><h3>Content</h3>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testSpanContents() { // like h1 tags, the spec says SPAN is phrasing only, but browsers and publisher treat span as a block tag Document doc = Jsoup.parse("<span>Hello <div>there</div> <span>now</span></span>"); assertEquals("<span>Hello <div>there</div> <span>now</span></span>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testNoImagesInNoScriptInHead() { // jsoup used to allow, but against spec if parsing with noscript Document doc = Jsoup.parse("<html><head><noscript><img src='foo'></noscript></head><body><p>Hello</p></body></html>"); assertEquals("<html><head><noscript>&lt;img src=\"foo\"&gt;</noscript></head><body><p>Hello</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testAFlowContents() { // html5 has <a> as either phrasing or block Document doc = Jsoup.parse("<a>Hello <div>there</div> <span>now</span></a>"); assertEquals("<a>Hello <div>there</div> <span>now</span></a>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testFontFlowContents() { // html5 has no definition of <font>; often used as flow Document doc = Jsoup.parse("<font>Hello <div>there</div> <span>now</span></font>"); assertEquals("<font>Hello <div>there</div> <span>now</span></font>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesMisnestedTagsBI() { // whatwg: <b><i></b></i> String h = "<p>1<b>2<i>3</b>4</i>5</p>"; Document doc = Jsoup.parse(h); assertEquals("<p>1<b>2<i>3</i></b><i>4</i>5</p>", doc.body().html()); // adoption agency on </b>, reconstruction of formatters on 4. } @Test public void handlesMisnestedTagsBP() { // whatwg: <b><p></b></p> String h = "<b>1<p>2</b>3</p>"; Document doc = Jsoup.parse(h); assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html()); } @Test public void handlesUnexpectedMarkupInTables() { // whatwg - tests markers in active formatting (if they didn't work, would get in in table) // also tests foster parenting String h = "<table><b><tr><td>aaa</td></tr>bbb</table>ccc"; Document doc = Jsoup.parse(h); assertEquals("<b></b><b>bbb</b><table><tbody><tr><td>aaa</td></tr></tbody></table><b>ccc</b>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesUnclosedFormattingElements() { // whatwg: formatting elements get collected and applied, but excess elements are thrown away String h = "<!DOCTYPE html>\n" + "<p><b class=x><b class=x><b><b class=x><b class=x><b>X\n" + "<p>X\n" + "<p><b><b class=x><b>X\n" + "<p></b></b></b></b></b></b>X"; Document doc = Jsoup.parse(h); doc.outputSettings().indentAmount(0); String want = "<!doctype html>\n" + "<html>\n" + "<head></head>\n" + "<body>\n" + "<p><b class=\"x\"><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b><b><b class=\"x\"><b>X </b></b></b></b></b></b></b></b></p>\n" + "<p>X</p>\n" + "</body>\n" + "</html>"; assertEquals(want, doc.html()); } @Test public void handlesUnclosedAnchors() { String h = "<a href='http://example.com/'>Link<p>Error link</a>"; Document doc = Jsoup.parse(h); String want = "<a href=\"http://example.com/\">Link</a>\n<p><a href=\"http://example.com/\">Error link</a></p>"; assertEquals(want, doc.body().html()); } @Test public void reconstructFormattingElements() { // tests attributes and multi b String h = "<p><b class=one>One <i>Two <b>Three</p><p>Hello</p>"; Document doc = Jsoup.parse(h); assertEquals("<p><b class=\"one\">One <i>Two <b>Three</b></i></b></p>\n<p><b class=\"one\"><i><b>Hello</b></i></b></p>", doc.body().html()); } @Test public void reconstructFormattingElementsInTable() { // tests that tables get formatting markers -- the <b> applies outside the table and does not leak in, // and the <i> inside the table and does not leak out. String h = "<p><b>One</p> <table><tr><td><p><i>Three<p>Four</i></td></tr></table> <p>Five</p>"; Document doc = Jsoup.parse(h); String want = "<p><b>One</b></p>\n" + "<b> \n" + " <table>\n" + " <tbody>\n" + " <tr>\n" + " <td><p><i>Three</i></p><p><i>Four</i></p></td>\n" + " </tr>\n" + " </tbody>\n" + " </table> <p>Five</p></b>"; assertEquals(want, doc.body().html()); } @Test public void commentBeforeHtml() { String h = "<!-- comment --><!-- comment 2 --><p>One</p>"; Document doc = Jsoup.parse(h); assertEquals("<!-- comment --><!-- comment 2 --><html><head></head><body><p>One</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void emptyTdTag() { String h = "<table><tr><td>One</td><td id='2' /></tr></table>"; Document doc = Jsoup.parse(h); assertEquals("<td>One</td>\n<td id=\"2\"></td>", doc.select("tr").first().html()); } @Test public void handlesSolidusInA() { // test for bug #66 String h = "<a class=lp href=/lib/14160711/>link text</a>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("link text", a.text()); assertEquals("/lib/14160711/", a.attr("href")); } @Test public void handlesSpanInTbody() { // test for bug 64 String h = "<table><tbody><span class='1'><tr><td>One</td></tr><tr><td>Two</td></tr></span></tbody></table>"; Document doc = Jsoup.parse(h); assertEquals(doc.select("span").first().children().size(), 0); // the span gets closed assertEquals(doc.select("table").size(), 1); // only one table } @Test public void handlesUnclosedTitleAtEof() { assertEquals("Data", Jsoup.parse("<title>Data").title()); assertEquals("Data<", Jsoup.parse("<title>Data<").title()); assertEquals("Data</", Jsoup.parse("<title>Data</").title()); assertEquals("Data</t", Jsoup.parse("<title>Data</t").title()); assertEquals("Data</ti", Jsoup.parse("<title>Data</ti").title()); assertEquals("Data", Jsoup.parse("<title>Data</title>").title()); assertEquals("Data", Jsoup.parse("<title>Data</title >").title()); } @Test public void handlesUnclosedTitle() { Document one = Jsoup.parse("<title>One <b>Two <b>Three</TITLE><p>Test</p>"); // has title, so <b> is plain text assertEquals("One <b>Two <b>Three", one.title()); assertEquals("Test", one.select("p").first().text()); Document two = Jsoup.parse("<title>One<b>Two <p>Test</p>"); // no title, so <b> causes </title> breakout assertEquals("One", two.title()); assertEquals("<b>Two <p>Test</p></b>", two.body().html()); } @Test public void handlesUnclosedScriptAtEof() { assertEquals("Data", Jsoup.parse("<script>Data").select("script").first().data()); assertEquals("Data<", Jsoup.parse("<script>Data<").select("script").first().data()); assertEquals("Data</sc", Jsoup.parse("<script>Data</sc").select("script").first().data()); assertEquals("Data</-sc", Jsoup.parse("<script>Data</-sc").select("script").first().data()); assertEquals("Data</sc-", Jsoup.parse("<script>Data</sc-").select("script").first().data()); assertEquals("Data</sc--", Jsoup.parse("<script>Data</sc--").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script>").select("script").first().data()); assertEquals("Data</script", Jsoup.parse("<script>Data</script").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script ").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"p").select("script").first().data()); } @Test public void handlesUnclosedRawtextAtEof() { assertEquals("Data", Jsoup.parse("<style>Data").select("style").first().data()); assertEquals("Data</st", Jsoup.parse("<style>Data</st").select("style").first().data()); assertEquals("Data", Jsoup.parse("<style>Data</style>").select("style").first().data()); assertEquals("Data</style", Jsoup.parse("<style>Data</style").select("style").first().data()); assertEquals("Data</-style", Jsoup.parse("<style>Data</-style").select("style").first().data()); assertEquals("Data</style-", Jsoup.parse("<style>Data</style-").select("style").first().data()); assertEquals("Data</style--", Jsoup.parse("<style>Data</style--").select("style").first().data()); } @Test public void noImplicitFormForTextAreas() { // old jsoup parser would create implicit forms for form children like <textarea>, but no more Document doc = Jsoup.parse("<textarea>One</textarea>"); assertEquals("<textarea>One</textarea>", doc.body().html()); } @Test public void handlesEscapedScript() { Document doc = Jsoup.parse("<script><!-- one <script>Blah</script> --></script>"); assertEquals("<!-- one <script>Blah</script> -->", doc.select("script").first().data()); } @Test public void handles0CharacterAsText() { Document doc = Jsoup.parse("0<p>0</p>"); assertEquals("0\n<p>0</p>", doc.body().html()); } @Test public void handlesNullInData() { Document doc = Jsoup.parse("<p id=\u0000>Blah \u0000</p>"); assertEquals("<p id=\"\uFFFD\">Blah \u0000</p>", doc.body().html()); // replaced in attr, NOT replaced in data } @Test public void handlesNullInComments() { Document doc = Jsoup.parse("<body><!-- \u0000 \u0000 -->"); assertEquals("<!-- \uFFFD \uFFFD -->", doc.body().html()); } @Test public void handlesNewlinesAndWhitespaceInTag() { Document doc = Jsoup.parse("<a \n href=\"one\" \r\n id=\"two\" \f >"); assertEquals("<a href=\"one\" id=\"two\"></a>", doc.body().html()); } @Test public void handlesWhitespaceInoDocType() { String html = "<!DOCTYPE html\r\n" + " PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n" + " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; Document doc = Jsoup.parse(html); assertEquals("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">", doc.childNode(0).outerHtml()); } @Test public void tracksErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(500); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(5, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); assertEquals("50: Self closing flag not acknowledged", errors.get(3).toString()); assertEquals("61: Unexpectedly reached end of file (EOF) in input state [TagName]", errors.get(4).toString()); } @Test public void tracksLimitedErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(3); Document doc = parser.parseInput(html, "http://example.com"); List<ParseError> errors = parser.getErrors(); assertEquals(3, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); } @Test public void noErrorsByDefault() { String html = "<p>One</p href='no'>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser(); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(0, errors.size()); } @Test public void handlesCommentsInTable() { String html = "<table><tr><td>text</td><!-- Comment --></tr></table>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<html><head></head><body><table><tbody><tr><td>text</td><!-- Comment --></tr></tbody></table></body></html>", TextUtil.stripNewlines(node.outerHtml())); } @Test public void handlesQuotesInCommentsInScripts() { String html = "<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>", node.body().html()); } @Test public void handleNullContextInParseFragment() { String html = "<ol><li>One</li></ol><p>Two</p>"; List<Node> nodes = Parser.parseFragment(html, null, "http://example.com/"); assertEquals(1, nodes.size()); // returns <html> node (not document) -- no context means doc gets created assertEquals("html", nodes.get(0).nodeName()); assertEquals("<html> <head></head> <body> <ol> <li>One</li> </ol> <p>Two</p> </body> </html>", StringUtil.normaliseWhitespace(nodes.get(0).outerHtml())); } @Test public void doesNotFindShortestMatchingEntity() { // previous behaviour was to identify a possible entity, then chomp down the string until a match was found. // (as defined in html5.) However in practise that lead to spurious matches against the author's intent. String html = "One &clubsuite; &clubsuit;"; Document doc = Jsoup.parse(html); assertEquals(StringUtil.normaliseWhitespace("One &amp;clubsuite; ♣"), doc.body().html()); } @Test public void relaxedBaseEntityMatchAndStrictExtendedMatch() { // extended entities need a ; at the end to match, base does not String html = "&amp &quot &reg &icy &hopf &icy; &hopf;"; Document doc = Jsoup.parse(html); doc.outputSettings().escapeMode(Entities.EscapeMode.extended).charset("ascii"); // modifies output only to clarify test assertEquals("&amp; \" &reg; &amp;icy &amp;hopf &icy; &hopf;", doc.body().html()); } @Test public void handlesXmlDeclarationAsBogusComment() { String html = "<?xml encoding='UTF-8' ?><body>One</body>"; Document doc = Jsoup.parse(html); assertEquals("<!--?xml encoding='UTF-8' ?--> <html> <head></head> <body> One </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesTagsInTextarea() { String html = "<textarea><p>Jsoup</p></textarea>"; Document doc = Jsoup.parse(html); assertEquals("<textarea>&lt;p&gt;Jsoup&lt;/p&gt;</textarea>", doc.body().html()); } // form tests @Test public void createsFormElements() { String html = "<body><form><input id=1><input id=2></form></body>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); } @Test public void associatedFormControlsWithDisjointForms() { // form gets closed, isn't parent of controls String html = "<table><tr><form><input type=hidden id=1><td><input type=text id=2></td><tr></table>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); assertEquals("<table><tbody><tr><form></form><input type=\"hidden\" id=\"1\"><td><input type=\"text\" id=\"2\"></td></tr><tr></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesInputInTable() { String h = "<body>\n" + "<input type=\"hidden\" name=\"a\" value=\"\">\n" + "<table>\n" + "<input type=\"hidden\" name=\"b\" value=\"\" />\n" + "</table>\n" + "</body>"; Document doc = Jsoup.parse(h); assertEquals(1, doc.select("table input").size()); assertEquals(2, doc.select("input").size()); } @Test public void convertsImageToImg() { // image to img, unless in a svg. old html cruft. String h = "<body><image><svg><image /></svg></body>"; Document doc = Jsoup.parse(h); assertEquals("<img>\n<svg>\n <image />\n</svg>", doc.body().html()); } @Test public void handlesInvalidDoctypes() { // would previously throw invalid name exception on empty doctype Document doc = Jsoup.parse("<!DOCTYPE>"); assertEquals( "<!doctype> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE><html><p>Foo</p></html>"); assertEquals( "<!doctype> <html> <head></head> <body> <p>Foo</p> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE \u0000>"); assertEquals( "<!doctype �> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesManyChildren() { // Arrange StringBuilder longBody = new StringBuilder(500000); for (int i = 0; i < 25000; i++) { longBody.append(i).append("<br>"); } // Act long start = System.currentTimeMillis(); Document doc = Parser.parseBodyFragment(longBody.toString(), ""); // Assert assertEquals(50000, doc.body().childNodeSize()); assertTrue(System.currentTimeMillis() - start < 1000); } @Test public void testInvalidTableContents() throws IOException { File in = ParseTest.getFile("/htmltests/table-invalid-elements.html"); Document doc = Jsoup.parse(in, "UTF-8"); doc.outputSettings().prettyPrint(true); String rendered = doc.toString(); int endOfEmail = rendered.indexOf("Comment"); int guarantee = rendered.indexOf("Why am I here?"); assertTrue("Comment not found", endOfEmail > -1); assertTrue("Search text not found", guarantee > -1); assertTrue("Search text did not come after comment", guarantee > endOfEmail); } @Test public void testNormalisesIsIndex() { Document doc = Jsoup.parse("<body><isindex action='/submit'></body>"); String html = doc.outerHtml(); assertEquals("<form action=\"/submit\"> <hr> <label>This is a searchable index. Enter search keywords: <input name=\"isindex\"></label> <hr> </form>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void testReinsertionModeForThCelss() { String body = "<body> <table> <tr> <th> <table><tr><td></td></tr></table> <div> <table><tr><td></td></tr></table> </div> <div></div> <div></div> <div></div> </th> </tr> </table> </body>"; Document doc = Jsoup.parse(body); assertEquals(1, doc.body().children().size()); } @Test public void testUsingSingleQuotesInQueries() { String body = "<body> <div class='main'>hello</div></body>"; Document doc = Jsoup.parse(body); Elements main = doc.select("div[class='main']"); assertEquals("hello", main.text()); } @Test public void testSupportsNonAsciiTags() { String body = "<進捗推移グラフ>Yes</進捗推移グラフ><русский-тэг>Correct</<русский-тэг>"; Document doc = Jsoup.parse(body); Elements els = doc.select("進捗推移グラフ"); assertEquals("Yes", els.text()); els = doc.select("русский-тэг"); assertEquals("Correct", els.text()); } @Test public void testSupportsPartiallyNonAsciiTags() { String body = "<div>Check</divá>"; Document doc = Jsoup.parse(body); Elements els = doc.select("div"); assertEquals("Check", els.text()); } @Test public void testFragment() { // make sure when parsing a body fragment, a script tag at start goes into the body String html = "<script type=\"text/javascript\">console.log('foo');</script>\n" + "<div id=\"somecontent\">some content</div>\n" + "<script type=\"text/javascript\">console.log('bar');</script>"; Document body = Jsoup.parseBodyFragment(html); assertEquals("<script type=\"text/javascript\">console.log('foo');</script> \n" + "<div id=\"somecontent\">\n" + " some content\n" + "</div> \n" + "<script type=\"text/javascript\">console.log('bar');</script>", body.body().html()); } @Test public void testHtmlLowerCase() { String html = "<!doctype HTML><DIV ID=1>One</DIV>"; Document doc = Jsoup.parse(html); assertEquals("<!doctype html> <html> <head></head> <body> <div id=\"1\"> One </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void canPreserveTagCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, false)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN id=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void canPreserveAttributeCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(false, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <span ID=\"2\"></span> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void canPreserveBothCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN ID=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesControlCodeInAttributeName() { Document doc = Jsoup.parse("<p><a \06=foo>One</a><a/\06=bar><a foo\06=bar>Two</a></p>"); assertEquals("<p><a>One</a><a></a><a foo=\"bar\">Two</a></p>", doc.body().html()); } }
// You are a professional Java test case writer, please create a test case named `handlesControlCodeInAttributeName` for the issue `Jsoup-793`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-793 // // ## Issue-Title: // Jsoup.clean control characters throws: IllegalArgumentException: String must not be empty // // ## Issue-Description: // I found that when running Jsoup.clean() on a string that contains the format below, Jsoup throws: `IllegalArgumentException: String must not be empty`. // // The problematic string format: // // `'<a/*>'`, (where \* is a control char). // // i.e. `<` char followed by a letter (a-z), then any chars, `/` and any control char (ASCII 0-31) except 0, 9-10, 12-13, any chars, and a `>` char. // // // // @Test public void handlesControlCodeInAttributeName() {
947
59
944
src/test/java/org/jsoup/parser/HtmlParserTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-793 ## Issue-Title: Jsoup.clean control characters throws: IllegalArgumentException: String must not be empty ## Issue-Description: I found that when running Jsoup.clean() on a string that contains the format below, Jsoup throws: `IllegalArgumentException: String must not be empty`. The problematic string format: `'<a/*>'`, (where \* is a control char). i.e. `<` char followed by a letter (a-z), then any chars, `/` and any control char (ASCII 0-31) except 0, 9-10, 12-13, any chars, and a `>` char. ``` You are a professional Java test case writer, please create a test case named `handlesControlCodeInAttributeName` for the issue `Jsoup-793`, utilizing the provided issue report information and the following function signature. ```java @Test public void handlesControlCodeInAttributeName() { ```
944
[ "org.jsoup.parser.Token" ]
fa63e413cd9f40ec8ce9e9f410d82bc7ea2685ef26363118ac6291df597c3f32
@Test public void handlesControlCodeInAttributeName()
// You are a professional Java test case writer, please create a test case named `handlesControlCodeInAttributeName` for the issue `Jsoup-793`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-793 // // ## Issue-Title: // Jsoup.clean control characters throws: IllegalArgumentException: String must not be empty // // ## Issue-Description: // I found that when running Jsoup.clean() on a string that contains the format below, Jsoup throws: `IllegalArgumentException: String must not be empty`. // // The problematic string format: // // `'<a/*>'`, (where \* is a control char). // // i.e. `<` char followed by a letter (a-z), then any chars, `/` and any control char (ASCII 0-31) except 0, 9-10, 12-13, any chars, and a `>` char. // // // //
Jsoup
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.*; import org.jsoup.select.Elements; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** Tests for the Parser @author Jonathan Hedley, jonathan@hedley.net */ public class HtmlParserTest { @Test public void parsesSimpleDocument() { String html = "<html><head><title>First!</title></head><body><p>First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); Element img = p.child(0); assertEquals("foo.png", img.attr("src")); assertEquals("img", img.tagName()); } @Test public void parsesRoughAttributes() { String html = "<html><head><title>First!</title></head><body><p class=\"foo > bar\">First post! <img src=\"foo.png\" /></p></body></html>"; Document doc = Jsoup.parse(html); // need a better way to verify these: Element p = doc.body().child(0); assertEquals("p", p.tagName()); assertEquals("foo > bar", p.attr("class")); } @Test public void parsesQuiteRoughAttributes() { String html = "<p =a>One<a <p>Something</p>Else"; // this gets a <p> with attr '=a' and an <a tag with an attribue named '<p'; and then auto-recreated Document doc = Jsoup.parse(html); assertEquals("<p =a>One<a <p>Something</a></p>\n" + "<a <p>Else</a>", doc.body().html()); doc = Jsoup.parse("<p .....>"); assertEquals("<p .....></p>", doc.body().html()); } @Test public void parsesComments() { String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --><p>Hello</p></body></html>"; Document doc = Jsoup.parse(html); Element body = doc.body(); Comment comment = (Comment) body.childNode(1); // comment should not be sub of img, as it's an empty tag assertEquals(" <table><tr><td></table> ", comment.getData()); Element p = body.child(1); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); } @Test public void parsesUnterminatedComments() { String html = "<p>Hello<!-- <tr><td>"; Document doc = Jsoup.parse(html); Element p = doc.getElementsByTag("p").get(0); assertEquals("Hello", p.text()); TextNode text = (TextNode) p.childNode(0); assertEquals("Hello", text.getWholeText()); Comment comment = (Comment) p.childNode(1); assertEquals(" <tr><td>", comment.getData()); } @Test public void dropsUnterminatedTag() { // jsoup used to parse this to <p>, but whatwg, webkit will drop. String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(0, doc.getElementsByTag("p").size()); assertEquals("", doc.text()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); assertEquals("", doc.text()); } @Test public void dropsUnterminatedAttribute() { // jsoup used to parse this to <p id="foo">, but whatwg, webkit will drop. String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); assertEquals("", doc.text()); } @Test public void parsesUnterminatedTextarea() { // don't parse right to end, but break on <p> Document doc = Jsoup.parse("<body><p><textarea>one<p>two"); Element t = doc.select("textarea").first(); assertEquals("one", t.text()); assertEquals("two", doc.select("p").get(1).text()); } @Test public void parsesUnterminatedOption() { // bit weird this -- browsers and spec get stuck in select until there's a </select> Document doc = Jsoup.parse("<body><p><select><option>One<option>Two</p><p>Three</p>"); Elements options = doc.select("option"); assertEquals(2, options.size()); assertEquals("One", options.first().text()); assertEquals("TwoThree", options.last().text()); } @Test public void testSpaceAfterTag() { Document doc = Jsoup.parse("<div > <a name=\"top\"></a ><p id=1 >Hello</p></div>"); assertEquals("<div> <a name=\"top\"></a><p id=\"1\">Hello</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void createsDocumentStructure() { String html = "<meta name=keywords /><link rel=stylesheet /><title>jsoup</title><p>Hello world</p>"; Document doc = Jsoup.parse(html); Element head = doc.head(); Element body = doc.body(); assertEquals(1, doc.children().size()); // root node: contains html node assertEquals(2, doc.child(0).children().size()); // html node: head and body assertEquals(3, head.children().size()); assertEquals(1, body.children().size()); assertEquals("keywords", head.getElementsByTag("meta").get(0).attr("name")); assertEquals(0, body.getElementsByTag("meta").size()); assertEquals("jsoup", doc.title()); assertEquals("Hello world", body.text()); assertEquals("Hello world", body.children().get(0).text()); } @Test public void createsStructureFromBodySnippet() { // the bar baz stuff naturally goes into the body, but the 'foo' goes into root, and the normalisation routine // needs to move into the start of the body String html = "foo <b>bar</b> baz"; Document doc = Jsoup.parse(html); assertEquals("foo bar baz", doc.text()); } @Test public void handlesEscapedData() { String html = "<div title='Surf &amp; Turf'>Reef &amp; Beef</div>"; Document doc = Jsoup.parse(html); Element div = doc.getElementsByTag("div").get(0); assertEquals("Surf & Turf", div.attr("title")); assertEquals("Reef & Beef", div.text()); } @Test public void handlesDataOnlyTags() { String t = "<style>font-family: bold</style>"; List<Element> tels = Jsoup.parse(t).getElementsByTag("style"); assertEquals("font-family: bold", tels.get(0).data()); assertEquals("", tels.get(0).text()); String s = "<p>Hello</p><script>obj.insert('<a rel=\"none\" />');\ni++;</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("obj.insert('<a rel=\"none\" />');\ni++;", doc.data()); } @Test public void handlesTextAfterData() { String h = "<html><body>pre <script>inner</script> aft</body></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head></head><body>pre <script>inner</script> aft</body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void handlesTextArea() { Document doc = Jsoup.parse("<textarea>Hello</textarea>"); Elements els = doc.select("textarea"); assertEquals("Hello", els.text()); assertEquals("Hello", els.val()); } @Test public void preservesSpaceInTextArea() { // preserve because the tag is marked as preserve white space Document doc = Jsoup.parse("<textarea>\n\tOne\n\tTwo\n\tThree\n</textarea>"); String expect = "One\n\tTwo\n\tThree"; // the leading and trailing spaces are dropped as a convenience to authors Element el = doc.select("textarea").first(); assertEquals(expect, el.text()); assertEquals(expect, el.val()); assertEquals(expect, el.html()); assertEquals("<textarea>\n\t" + expect + "\n</textarea>", el.outerHtml()); // but preserved in round-trip html } @Test public void preservesSpaceInScript() { // preserve because it's content is a data node Document doc = Jsoup.parse("<script>\nOne\n\tTwo\n\tThree\n</script>"); String expect = "\nOne\n\tTwo\n\tThree\n"; Element el = doc.select("script").first(); assertEquals(expect, el.data()); assertEquals("One\n\tTwo\n\tThree", el.html()); assertEquals("<script>" + expect + "</script>", el.outerHtml()); } @Test public void doesNotCreateImplicitLists() { // old jsoup used to wrap this in <ul>, but that's not to spec String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should NOT have created a default ul. assertEquals(0, ol.size()); Elements lis = doc.select("li"); assertEquals(2, lis.size()); assertEquals("body", lis.first().parent().tagName()); // no fiddling with non-implicit lists String h2 = "<ol><li><p>Point the first<li><p>Point the second"; Document doc2 = Jsoup.parse(h2); assertEquals(0, doc2.select("ul").size()); assertEquals(1, doc2.select("ol").size()); assertEquals(2, doc2.select("ol li").size()); assertEquals(2, doc2.select("ol li p").size()); assertEquals(1, doc2.select("ol li").get(0).children().size()); // one p in first li } @Test public void discardsNakedTds() { // jsoup used to make this into an implicit table; but browsers make it into a text run String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("Hello<p>There</p><p>now</p>", TextUtil.stripNewlines(doc.body().html())); // <tbody> is introduced if no implicitly creating table, but allows tr to be directly under table } @Test public void handlesNestedImplicitTable() { Document doc = Jsoup.parse("<table><td>1</td></tr> <td>2</td></tr> <td> <table><td>3</td> <td>4</td></table> <tr><td>5</table>"); assertEquals("<table><tbody><tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td> <table><tbody><tr><td>3</td> <td>4</td></tr></tbody></table> </td></tr><tr><td>5</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesWhatWgExpensesTableExample() { // http://www.whatwg.org/specs/web-apps/current-work/multipage/tabular-data.html#examples-0 Document doc = Jsoup.parse("<table> <colgroup> <col> <colgroup> <col> <col> <col> <thead> <tr> <th> <th>2008 <th>2007 <th>2006 <tbody> <tr> <th scope=rowgroup> Research and development <td> $ 1,109 <td> $ 782 <td> $ 712 <tr> <th scope=row> Percentage of net sales <td> 3.4% <td> 3.3% <td> 3.7% <tbody> <tr> <th scope=rowgroup> Selling, general, and administrative <td> $ 3,761 <td> $ 2,963 <td> $ 2,433 <tr> <th scope=row> Percentage of net sales <td> 11.6% <td> 12.3% <td> 12.6% </table>"); assertEquals("<table> <colgroup> <col> </colgroup><colgroup> <col> <col> <col> </colgroup><thead> <tr> <th> </th><th>2008 </th><th>2007 </th><th>2006 </th></tr></thead><tbody> <tr> <th scope=\"rowgroup\"> Research and development </th><td> $ 1,109 </td><td> $ 782 </td><td> $ 712 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 3.4% </td><td> 3.3% </td><td> 3.7% </td></tr></tbody><tbody> <tr> <th scope=\"rowgroup\"> Selling, general, and administrative </th><td> $ 3,761 </td><td> $ 2,963 </td><td> $ 2,433 </td></tr><tr> <th scope=\"row\"> Percentage of net sales </th><td> 11.6% </td><td> 12.3% </td><td> 12.6% </td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesTbodyTable() { Document doc = Jsoup.parse("<html><head></head><body><table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table></body></html>"); assertEquals("<table><tbody><tr><td>aaa</td><td>bbb</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesImplicitCaptionClose() { Document doc = Jsoup.parse("<table><caption>A caption<td>One<td>Two"); assertEquals("<table><caption>A caption</caption><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void noTableDirectInTable() { Document doc = Jsoup.parse("<table> <td>One <td><table><td>Two</table> <table><td>Three"); assertEquals("<table> <tbody><tr><td>One </td><td><table><tbody><tr><td>Two</td></tr></tbody></table> <table><tbody><tr><td>Three</td></tr></tbody></table></td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void ignoresDupeEndTrTag() { Document doc = Jsoup.parse("<table><tr><td>One</td><td><table><tr><td>Two</td></tr></tr></table></td><td>Three</td></tr></table>"); // two </tr></tr>, must ignore or will close table assertEquals("<table><tbody><tr><td>One</td><td><table><tbody><tr><td>Two</td></tr></tbody></table></td><td>Three</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { // only listen to the first base href String h = "<a href=1>#</a><base href='/2/'><a href='3'>#</a><base href='http://bar'><a href=/4>#</a>"; Document doc = Jsoup.parse(h, "http://foo/"); assertEquals("http://foo/2/", doc.baseUri()); // gets set once, so doc and descendants have first only Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/2/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://foo/2/", anchors.get(2).baseUri()); assertEquals("http://foo/2/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://foo/4", anchors.get(2).absUrl("href")); } @Test public void handlesProtocolRelativeUrl() { String base = "https://example.com/"; String html = "<img src='//example.net/img.jpg'>"; Document doc = Jsoup.parse(html, base); Element el = doc.select("img").first(); assertEquals("https://example.net/img.jpg", el.absUrl("src")); } @Test public void handlesCdata() { // todo: as this is html namespace, should actually treat as bogus comment, not cdata. keep as cdata for now String h = "<div id=1><![CDATA[<html>\n<foo><&amp;]]></div>"; // the &amp; in there should remain literal Document doc = Jsoup.parse(h); Element div = doc.getElementById("1"); assertEquals("<html> <foo><&amp;", div.text()); assertEquals(0, div.children().size()); assertEquals(1, div.childNodeSize()); // no elements, one text node } @Test public void handlesUnclosedCdataAtEOF() { // https://github.com/jhy/jsoup/issues/349 would crash, as character reader would try to seek past EOF String h = "<![CDATA[]]"; Document doc = Jsoup.parse(h); assertEquals(1, doc.body().childNodeSize()); } @Test public void handlesInvalidStartTags() { String h = "<div>Hello < There <&amp;></div>"; // parse to <div {#text=Hello < There <&>}> Document doc = Jsoup.parse(h); assertEquals("Hello < There <&>", doc.select("div").first().text()); } @Test public void handlesUnknownTags() { String h = "<div><foo title=bar>Hello<foo title=qux>there</foo></div>"; Document doc = Jsoup.parse(h); Elements foos = doc.select("foo"); assertEquals(2, foos.size()); assertEquals("bar", foos.first().attr("title")); assertEquals("qux", foos.last().attr("title")); assertEquals("there", foos.last().text()); } @Test public void handlesUnknownInlineTags() { String h = "<p><cust>Test</cust></p><p><cust><cust>Test</cust></cust></p>"; Document doc = Jsoup.parseBodyFragment(h); String out = doc.body().html(); assertEquals(h, TextUtil.stripNewlines(out)); } @Test public void parsesBodyFragment() { String h = "<!-- comment --><p><a href='foo'>One</a></p>"; Document doc = Jsoup.parseBodyFragment(h, "http://example.com"); assertEquals("<body><!-- comment --><p><a href=\"foo\">One</a></p></body>", TextUtil.stripNewlines(doc.body().outerHtml())); assertEquals("http://example.com/foo", doc.select("a").first().absUrl("href")); } @Test public void handlesUnknownNamespaceTags() { // note that the first foo:bar should not really be allowed to be self closing, if parsed in html mode. String h = "<foo:bar id='1' /><abc:def id=2>Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>"; Document doc = Jsoup.parse(h); assertEquals("<foo:bar id=\"1\" /><abc:def id=\"2\">Foo<p>Hello</p></abc:def><foo:bar>There</foo:bar>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesKnownEmptyBlocks() { // if a known tag, allow self closing outside of spec, but force an end tag. unknown tags can be self closing. String h = "<div id='1' /><script src='/foo' /><div id=2><img /><img></div><a id=3 /><i /><foo /><foo>One</foo> <hr /> hr text <hr> hr text two"; Document doc = Jsoup.parse(h); assertEquals("<div id=\"1\"></div><script src=\"/foo\"></script><div id=\"2\"><img><img></div><a id=\"3\"></a><i></i><foo /><foo>One</foo> <hr> hr text <hr> hr text two", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesSolidusAtAttributeEnd() { // this test makes sure [<a href=/>link</a>] is parsed as [<a href="/">link</a>], not [<a href="" /><a>link</a>] String h = "<a href=/>link</a>"; Document doc = Jsoup.parse(h); assertEquals("<a href=\"/\">link</a>", doc.body().html()); } @Test public void handlesMultiClosingBody() { String h = "<body><p>Hello</body><p>there</p></body></body></html><p>now"; Document doc = Jsoup.parse(h); assertEquals(3, doc.select("p").size()); assertEquals(3, doc.body().children().size()); } @Test public void handlesUnclosedDefinitionLists() { // jsoup used to create a <dl>, but that's not to spec String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(0, doc.select("dl").size()); // no auto dl assertEquals(4, doc.select("dt, dd").size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @Test public void handlesBlocksInDefinitions() { // per the spec, dt and dd are inline, but in practise are block String h = "<dl><dt><div id=1>Term</div></dt><dd><div id=2>Def</div></dd></dl>"; Document doc = Jsoup.parse(h); assertEquals("dt", doc.select("#1").first().parent().tagName()); assertEquals("dd", doc.select("#2").first().parent().tagName()); assertEquals("<dl><dt><div id=\"1\">Term</div></dt><dd><div id=\"2\">Def</div></dd></dl>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesFrames() { String h = "<html><head><script></script><noscript></noscript></head><frameset><frame src=foo></frame><frame src=foo></frameset></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\"><frame src=\"foo\"></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body auto vivification } @Test public void ignoresContentAfterFrameset() { String h = "<html><head><title>One</title></head><frameset><frame /><frame /></frameset><table></table></html>"; Document doc = Jsoup.parse(h); assertEquals("<html><head><title>One</title></head><frameset><frame><frame></frameset></html>", TextUtil.stripNewlines(doc.html())); // no body, no table. No crash! } @Test public void handlesJavadocFont() { String h = "<TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A>&nbsp;</TD>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("Deprecated", a.text()); assertEquals("font", a.child(0).tagName()); assertEquals("b", a.child(0).child(0).tagName()); } @Test public void handlesBaseWithoutHref() { String h = "<head><base target='_blank'></head><body><a href=/foo>Test</a></body>"; Document doc = Jsoup.parse(h, "http://example.com/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://example.com/foo", a.attr("abs:href")); } @Test public void normalisesDocument() { String h = "<!doctype html>One<html>Two<head>Three<link></head>Four<body>Five </body>Six </html>Seven "; Document doc = Jsoup.parse(h); assertEquals("<!doctype html><html><head></head><body>OneTwoThree<link>FourFive Six Seven </body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesEmptyDocument() { Document doc = Jsoup.parse(""); assertEquals("<html><head></head><body></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesHeadlessBody() { Document doc = Jsoup.parse("<html><body><span class=\"foo\">bar</span>"); assertEquals("<html><head></head><body><span class=\"foo\">bar</span></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisedBodyAfterContent() { Document doc = Jsoup.parse("<font face=Arial><body class=name><div>One</div></body></font>"); assertEquals("<html><head></head><body class=\"name\"><font face=\"Arial\"><div>One</div></font></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void findsCharsetInMalformedMeta() { String h = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"; // example cited for reason of html5's <meta charset> element Document doc = Jsoup.parse(h); assertEquals("gb2312", doc.select("meta").attr("charset")); } @Test public void testHgroup() { // jsoup used to not allow hroup in h{n}, but that's not in spec, and browsers are OK Document doc = Jsoup.parse("<h1>Hello <h2>There <hgroup><h1>Another<h2>headline</hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup>"); assertEquals("<h1>Hello </h1><h2>There <hgroup><h1>Another</h1><h2>headline</h2></hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup></h2>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def>There</abc-def>"); assertEquals("<abc_def id=\"1\">Hello</abc_def> <abc-def>There</abc-def>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHeaderContents() { // h* tags (h1 .. h9) in browsers can handle any internal content other than other h*. which is not per any // spec, which defines them as containing phrasing content only. so, reality over theory. Document doc = Jsoup.parse("<h1>Hello <div>There</div> now</h1> <h2>More <h3>Content</h3></h2>"); assertEquals("<h1>Hello <div>There</div> now</h1> <h2>More </h2><h3>Content</h3>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testSpanContents() { // like h1 tags, the spec says SPAN is phrasing only, but browsers and publisher treat span as a block tag Document doc = Jsoup.parse("<span>Hello <div>there</div> <span>now</span></span>"); assertEquals("<span>Hello <div>there</div> <span>now</span></span>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testNoImagesInNoScriptInHead() { // jsoup used to allow, but against spec if parsing with noscript Document doc = Jsoup.parse("<html><head><noscript><img src='foo'></noscript></head><body><p>Hello</p></body></html>"); assertEquals("<html><head><noscript>&lt;img src=\"foo\"&gt;</noscript></head><body><p>Hello</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testAFlowContents() { // html5 has <a> as either phrasing or block Document doc = Jsoup.parse("<a>Hello <div>there</div> <span>now</span></a>"); assertEquals("<a>Hello <div>there</div> <span>now</span></a>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testFontFlowContents() { // html5 has no definition of <font>; often used as flow Document doc = Jsoup.parse("<font>Hello <div>there</div> <span>now</span></font>"); assertEquals("<font>Hello <div>there</div> <span>now</span></font>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesMisnestedTagsBI() { // whatwg: <b><i></b></i> String h = "<p>1<b>2<i>3</b>4</i>5</p>"; Document doc = Jsoup.parse(h); assertEquals("<p>1<b>2<i>3</i></b><i>4</i>5</p>", doc.body().html()); // adoption agency on </b>, reconstruction of formatters on 4. } @Test public void handlesMisnestedTagsBP() { // whatwg: <b><p></b></p> String h = "<b>1<p>2</b>3</p>"; Document doc = Jsoup.parse(h); assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html()); } @Test public void handlesUnexpectedMarkupInTables() { // whatwg - tests markers in active formatting (if they didn't work, would get in in table) // also tests foster parenting String h = "<table><b><tr><td>aaa</td></tr>bbb</table>ccc"; Document doc = Jsoup.parse(h); assertEquals("<b></b><b>bbb</b><table><tbody><tr><td>aaa</td></tr></tbody></table><b>ccc</b>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesUnclosedFormattingElements() { // whatwg: formatting elements get collected and applied, but excess elements are thrown away String h = "<!DOCTYPE html>\n" + "<p><b class=x><b class=x><b><b class=x><b class=x><b>X\n" + "<p>X\n" + "<p><b><b class=x><b>X\n" + "<p></b></b></b></b></b></b>X"; Document doc = Jsoup.parse(h); doc.outputSettings().indentAmount(0); String want = "<!doctype html>\n" + "<html>\n" + "<head></head>\n" + "<body>\n" + "<p><b class=\"x\"><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b>X </b></b></b></b></b></p>\n" + "<p><b class=\"x\"><b><b class=\"x\"><b class=\"x\"><b><b><b class=\"x\"><b>X </b></b></b></b></b></b></b></b></p>\n" + "<p>X</p>\n" + "</body>\n" + "</html>"; assertEquals(want, doc.html()); } @Test public void handlesUnclosedAnchors() { String h = "<a href='http://example.com/'>Link<p>Error link</a>"; Document doc = Jsoup.parse(h); String want = "<a href=\"http://example.com/\">Link</a>\n<p><a href=\"http://example.com/\">Error link</a></p>"; assertEquals(want, doc.body().html()); } @Test public void reconstructFormattingElements() { // tests attributes and multi b String h = "<p><b class=one>One <i>Two <b>Three</p><p>Hello</p>"; Document doc = Jsoup.parse(h); assertEquals("<p><b class=\"one\">One <i>Two <b>Three</b></i></b></p>\n<p><b class=\"one\"><i><b>Hello</b></i></b></p>", doc.body().html()); } @Test public void reconstructFormattingElementsInTable() { // tests that tables get formatting markers -- the <b> applies outside the table and does not leak in, // and the <i> inside the table and does not leak out. String h = "<p><b>One</p> <table><tr><td><p><i>Three<p>Four</i></td></tr></table> <p>Five</p>"; Document doc = Jsoup.parse(h); String want = "<p><b>One</b></p>\n" + "<b> \n" + " <table>\n" + " <tbody>\n" + " <tr>\n" + " <td><p><i>Three</i></p><p><i>Four</i></p></td>\n" + " </tr>\n" + " </tbody>\n" + " </table> <p>Five</p></b>"; assertEquals(want, doc.body().html()); } @Test public void commentBeforeHtml() { String h = "<!-- comment --><!-- comment 2 --><p>One</p>"; Document doc = Jsoup.parse(h); assertEquals("<!-- comment --><!-- comment 2 --><html><head></head><body><p>One</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void emptyTdTag() { String h = "<table><tr><td>One</td><td id='2' /></tr></table>"; Document doc = Jsoup.parse(h); assertEquals("<td>One</td>\n<td id=\"2\"></td>", doc.select("tr").first().html()); } @Test public void handlesSolidusInA() { // test for bug #66 String h = "<a class=lp href=/lib/14160711/>link text</a>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("link text", a.text()); assertEquals("/lib/14160711/", a.attr("href")); } @Test public void handlesSpanInTbody() { // test for bug 64 String h = "<table><tbody><span class='1'><tr><td>One</td></tr><tr><td>Two</td></tr></span></tbody></table>"; Document doc = Jsoup.parse(h); assertEquals(doc.select("span").first().children().size(), 0); // the span gets closed assertEquals(doc.select("table").size(), 1); // only one table } @Test public void handlesUnclosedTitleAtEof() { assertEquals("Data", Jsoup.parse("<title>Data").title()); assertEquals("Data<", Jsoup.parse("<title>Data<").title()); assertEquals("Data</", Jsoup.parse("<title>Data</").title()); assertEquals("Data</t", Jsoup.parse("<title>Data</t").title()); assertEquals("Data</ti", Jsoup.parse("<title>Data</ti").title()); assertEquals("Data", Jsoup.parse("<title>Data</title>").title()); assertEquals("Data", Jsoup.parse("<title>Data</title >").title()); } @Test public void handlesUnclosedTitle() { Document one = Jsoup.parse("<title>One <b>Two <b>Three</TITLE><p>Test</p>"); // has title, so <b> is plain text assertEquals("One <b>Two <b>Three", one.title()); assertEquals("Test", one.select("p").first().text()); Document two = Jsoup.parse("<title>One<b>Two <p>Test</p>"); // no title, so <b> causes </title> breakout assertEquals("One", two.title()); assertEquals("<b>Two <p>Test</p></b>", two.body().html()); } @Test public void handlesUnclosedScriptAtEof() { assertEquals("Data", Jsoup.parse("<script>Data").select("script").first().data()); assertEquals("Data<", Jsoup.parse("<script>Data<").select("script").first().data()); assertEquals("Data</sc", Jsoup.parse("<script>Data</sc").select("script").first().data()); assertEquals("Data</-sc", Jsoup.parse("<script>Data</-sc").select("script").first().data()); assertEquals("Data</sc-", Jsoup.parse("<script>Data</sc-").select("script").first().data()); assertEquals("Data</sc--", Jsoup.parse("<script>Data</sc--").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script>").select("script").first().data()); assertEquals("Data</script", Jsoup.parse("<script>Data</script").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script ").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"").select("script").first().data()); assertEquals("Data", Jsoup.parse("<script>Data</script n=\"p").select("script").first().data()); } @Test public void handlesUnclosedRawtextAtEof() { assertEquals("Data", Jsoup.parse("<style>Data").select("style").first().data()); assertEquals("Data</st", Jsoup.parse("<style>Data</st").select("style").first().data()); assertEquals("Data", Jsoup.parse("<style>Data</style>").select("style").first().data()); assertEquals("Data</style", Jsoup.parse("<style>Data</style").select("style").first().data()); assertEquals("Data</-style", Jsoup.parse("<style>Data</-style").select("style").first().data()); assertEquals("Data</style-", Jsoup.parse("<style>Data</style-").select("style").first().data()); assertEquals("Data</style--", Jsoup.parse("<style>Data</style--").select("style").first().data()); } @Test public void noImplicitFormForTextAreas() { // old jsoup parser would create implicit forms for form children like <textarea>, but no more Document doc = Jsoup.parse("<textarea>One</textarea>"); assertEquals("<textarea>One</textarea>", doc.body().html()); } @Test public void handlesEscapedScript() { Document doc = Jsoup.parse("<script><!-- one <script>Blah</script> --></script>"); assertEquals("<!-- one <script>Blah</script> -->", doc.select("script").first().data()); } @Test public void handles0CharacterAsText() { Document doc = Jsoup.parse("0<p>0</p>"); assertEquals("0\n<p>0</p>", doc.body().html()); } @Test public void handlesNullInData() { Document doc = Jsoup.parse("<p id=\u0000>Blah \u0000</p>"); assertEquals("<p id=\"\uFFFD\">Blah \u0000</p>", doc.body().html()); // replaced in attr, NOT replaced in data } @Test public void handlesNullInComments() { Document doc = Jsoup.parse("<body><!-- \u0000 \u0000 -->"); assertEquals("<!-- \uFFFD \uFFFD -->", doc.body().html()); } @Test public void handlesNewlinesAndWhitespaceInTag() { Document doc = Jsoup.parse("<a \n href=\"one\" \r\n id=\"two\" \f >"); assertEquals("<a href=\"one\" id=\"two\"></a>", doc.body().html()); } @Test public void handlesWhitespaceInoDocType() { String html = "<!DOCTYPE html\r\n" + " PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n" + " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; Document doc = Jsoup.parse(html); assertEquals("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">", doc.childNode(0).outerHtml()); } @Test public void tracksErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(500); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(5, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); assertEquals("50: Self closing flag not acknowledged", errors.get(3).toString()); assertEquals("61: Unexpectedly reached end of file (EOF) in input state [TagName]", errors.get(4).toString()); } @Test public void tracksLimitedErrorsWhenRequested() { String html = "<p>One</p href='no'><!DOCTYPE html>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser().setTrackErrors(3); Document doc = parser.parseInput(html, "http://example.com"); List<ParseError> errors = parser.getErrors(); assertEquals(3, errors.size()); assertEquals("20: Attributes incorrectly present on end tag", errors.get(0).toString()); assertEquals("35: Unexpected token [Doctype] when in state [InBody]", errors.get(1).toString()); assertEquals("36: Invalid character reference: invalid named referenece 'arrgh'", errors.get(2).toString()); } @Test public void noErrorsByDefault() { String html = "<p>One</p href='no'>&arrgh;<font /><br /><foo"; Parser parser = Parser.htmlParser(); Document doc = Jsoup.parse(html, "http://example.com", parser); List<ParseError> errors = parser.getErrors(); assertEquals(0, errors.size()); } @Test public void handlesCommentsInTable() { String html = "<table><tr><td>text</td><!-- Comment --></tr></table>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<html><head></head><body><table><tbody><tr><td>text</td><!-- Comment --></tr></tbody></table></body></html>", TextUtil.stripNewlines(node.outerHtml())); } @Test public void handlesQuotesInCommentsInScripts() { String html = "<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>"; Document node = Jsoup.parseBodyFragment(html); assertEquals("<script>\n" + " <!--\n" + " document.write('</scr' + 'ipt>');\n" + " // -->\n" + "</script>", node.body().html()); } @Test public void handleNullContextInParseFragment() { String html = "<ol><li>One</li></ol><p>Two</p>"; List<Node> nodes = Parser.parseFragment(html, null, "http://example.com/"); assertEquals(1, nodes.size()); // returns <html> node (not document) -- no context means doc gets created assertEquals("html", nodes.get(0).nodeName()); assertEquals("<html> <head></head> <body> <ol> <li>One</li> </ol> <p>Two</p> </body> </html>", StringUtil.normaliseWhitespace(nodes.get(0).outerHtml())); } @Test public void doesNotFindShortestMatchingEntity() { // previous behaviour was to identify a possible entity, then chomp down the string until a match was found. // (as defined in html5.) However in practise that lead to spurious matches against the author's intent. String html = "One &clubsuite; &clubsuit;"; Document doc = Jsoup.parse(html); assertEquals(StringUtil.normaliseWhitespace("One &amp;clubsuite; ♣"), doc.body().html()); } @Test public void relaxedBaseEntityMatchAndStrictExtendedMatch() { // extended entities need a ; at the end to match, base does not String html = "&amp &quot &reg &icy &hopf &icy; &hopf;"; Document doc = Jsoup.parse(html); doc.outputSettings().escapeMode(Entities.EscapeMode.extended).charset("ascii"); // modifies output only to clarify test assertEquals("&amp; \" &reg; &amp;icy &amp;hopf &icy; &hopf;", doc.body().html()); } @Test public void handlesXmlDeclarationAsBogusComment() { String html = "<?xml encoding='UTF-8' ?><body>One</body>"; Document doc = Jsoup.parse(html); assertEquals("<!--?xml encoding='UTF-8' ?--> <html> <head></head> <body> One </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesTagsInTextarea() { String html = "<textarea><p>Jsoup</p></textarea>"; Document doc = Jsoup.parse(html); assertEquals("<textarea>&lt;p&gt;Jsoup&lt;/p&gt;</textarea>", doc.body().html()); } // form tests @Test public void createsFormElements() { String html = "<body><form><input id=1><input id=2></form></body>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); } @Test public void associatedFormControlsWithDisjointForms() { // form gets closed, isn't parent of controls String html = "<table><tr><form><input type=hidden id=1><td><input type=text id=2></td><tr></table>"; Document doc = Jsoup.parse(html); Element el = doc.select("form").first(); assertTrue("Is form element", el instanceof FormElement); FormElement form = (FormElement) el; Elements controls = form.elements(); assertEquals(2, controls.size()); assertEquals("1", controls.get(0).id()); assertEquals("2", controls.get(1).id()); assertEquals("<table><tbody><tr><form></form><input type=\"hidden\" id=\"1\"><td><input type=\"text\" id=\"2\"></td></tr><tr></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesInputInTable() { String h = "<body>\n" + "<input type=\"hidden\" name=\"a\" value=\"\">\n" + "<table>\n" + "<input type=\"hidden\" name=\"b\" value=\"\" />\n" + "</table>\n" + "</body>"; Document doc = Jsoup.parse(h); assertEquals(1, doc.select("table input").size()); assertEquals(2, doc.select("input").size()); } @Test public void convertsImageToImg() { // image to img, unless in a svg. old html cruft. String h = "<body><image><svg><image /></svg></body>"; Document doc = Jsoup.parse(h); assertEquals("<img>\n<svg>\n <image />\n</svg>", doc.body().html()); } @Test public void handlesInvalidDoctypes() { // would previously throw invalid name exception on empty doctype Document doc = Jsoup.parse("<!DOCTYPE>"); assertEquals( "<!doctype> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE><html><p>Foo</p></html>"); assertEquals( "<!doctype> <html> <head></head> <body> <p>Foo</p> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); doc = Jsoup.parse("<!DOCTYPE \u0000>"); assertEquals( "<!doctype �> <html> <head></head> <body></body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesManyChildren() { // Arrange StringBuilder longBody = new StringBuilder(500000); for (int i = 0; i < 25000; i++) { longBody.append(i).append("<br>"); } // Act long start = System.currentTimeMillis(); Document doc = Parser.parseBodyFragment(longBody.toString(), ""); // Assert assertEquals(50000, doc.body().childNodeSize()); assertTrue(System.currentTimeMillis() - start < 1000); } @Test public void testInvalidTableContents() throws IOException { File in = ParseTest.getFile("/htmltests/table-invalid-elements.html"); Document doc = Jsoup.parse(in, "UTF-8"); doc.outputSettings().prettyPrint(true); String rendered = doc.toString(); int endOfEmail = rendered.indexOf("Comment"); int guarantee = rendered.indexOf("Why am I here?"); assertTrue("Comment not found", endOfEmail > -1); assertTrue("Search text not found", guarantee > -1); assertTrue("Search text did not come after comment", guarantee > endOfEmail); } @Test public void testNormalisesIsIndex() { Document doc = Jsoup.parse("<body><isindex action='/submit'></body>"); String html = doc.outerHtml(); assertEquals("<form action=\"/submit\"> <hr> <label>This is a searchable index. Enter search keywords: <input name=\"isindex\"></label> <hr> </form>", StringUtil.normaliseWhitespace(doc.body().html())); } @Test public void testReinsertionModeForThCelss() { String body = "<body> <table> <tr> <th> <table><tr><td></td></tr></table> <div> <table><tr><td></td></tr></table> </div> <div></div> <div></div> <div></div> </th> </tr> </table> </body>"; Document doc = Jsoup.parse(body); assertEquals(1, doc.body().children().size()); } @Test public void testUsingSingleQuotesInQueries() { String body = "<body> <div class='main'>hello</div></body>"; Document doc = Jsoup.parse(body); Elements main = doc.select("div[class='main']"); assertEquals("hello", main.text()); } @Test public void testSupportsNonAsciiTags() { String body = "<進捗推移グラフ>Yes</進捗推移グラフ><русский-тэг>Correct</<русский-тэг>"; Document doc = Jsoup.parse(body); Elements els = doc.select("進捗推移グラフ"); assertEquals("Yes", els.text()); els = doc.select("русский-тэг"); assertEquals("Correct", els.text()); } @Test public void testSupportsPartiallyNonAsciiTags() { String body = "<div>Check</divá>"; Document doc = Jsoup.parse(body); Elements els = doc.select("div"); assertEquals("Check", els.text()); } @Test public void testFragment() { // make sure when parsing a body fragment, a script tag at start goes into the body String html = "<script type=\"text/javascript\">console.log('foo');</script>\n" + "<div id=\"somecontent\">some content</div>\n" + "<script type=\"text/javascript\">console.log('bar');</script>"; Document body = Jsoup.parseBodyFragment(html); assertEquals("<script type=\"text/javascript\">console.log('foo');</script> \n" + "<div id=\"somecontent\">\n" + " some content\n" + "</div> \n" + "<script type=\"text/javascript\">console.log('bar');</script>", body.body().html()); } @Test public void testHtmlLowerCase() { String html = "<!doctype HTML><DIV ID=1>One</DIV>"; Document doc = Jsoup.parse(html); assertEquals("<!doctype html> <html> <head></head> <body> <div id=\"1\"> One </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void canPreserveTagCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, false)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN id=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void canPreserveAttributeCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(false, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <span ID=\"2\"></span> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void canPreserveBothCase() { Parser parser = Parser.htmlParser(); parser.settings(new ParseSettings(true, true)); Document doc = parser.parseInput("<div id=1><SPAN ID=2>", ""); assertEquals("<html> <head></head> <body> <div id=\"1\"> <SPAN ID=\"2\"></SPAN> </div> </body> </html>", StringUtil.normaliseWhitespace(doc.outerHtml())); } @Test public void handlesControlCodeInAttributeName() { Document doc = Jsoup.parse("<p><a \06=foo>One</a><a/\06=bar><a foo\06=bar>Two</a></p>"); assertEquals("<p><a>One</a><a></a><a foo=\"bar\">Two</a></p>", doc.body().html()); } }
@Test public void readEntriesOfSize0() throws IOException { final SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-348.7z")); try { int entries = 0; SevenZArchiveEntry entry = sevenZFile.getNextEntry(); while (entry != null) { entries++; int b = sevenZFile.read(); if ("2.txt".equals(entry.getName()) || "5.txt".equals(entry.getName())) { assertEquals(-1, b); } else { assertNotEquals(-1, b); } entry = sevenZFile.getNextEntry(); } assertEquals(5, entries); } finally { sevenZFile.close(); } }
org.apache.commons.compress.archivers.sevenz.SevenZFileTest::readEntriesOfSize0
src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZFileTest.java
285
src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZFileTest.java
readEntriesOfSize0
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.sevenz; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import javax.crypto.Cipher; import org.apache.commons.compress.AbstractTestCase; import org.apache.commons.compress.PasswordRequiredException; import org.junit.Test; public class SevenZFileTest extends AbstractTestCase { private static final String TEST2_CONTENT = "<?xml version = '1.0'?>\r\n<!DOCTYPE" + " connections>\r\n<meinxml>\r\n\t<leer />\r\n</meinxml>\n"; // https://issues.apache.org/jira/browse/COMPRESS-320 @Test public void testRandomlySkippingEntries() throws Exception { // Read sequential reference. final Map<String, byte[]> entriesByName = new HashMap<String, byte[]>(); SevenZFile archive = new SevenZFile(getFile("COMPRESS-320/Copy.7z")); SevenZArchiveEntry entry; while ((entry = archive.getNextEntry()) != null) { if (entry.hasStream()) { entriesByName.put(entry.getName(), readFully(archive)); } } archive.close(); final String[] variants = { "BZip2-solid.7z", "BZip2.7z", "Copy-solid.7z", "Copy.7z", "Deflate-solid.7z", "Deflate.7z", "LZMA-solid.7z", "LZMA.7z", "LZMA2-solid.7z", "LZMA2.7z", // TODO: unsupported compression method. // "PPMd-solid.7z", // "PPMd.7z", }; // TODO: use randomizedtesting for predictable, but different, randomness. final Random rnd = new Random(0xdeadbeef); for (final String fileName : variants) { archive = new SevenZFile(getFile("COMPRESS-320/" + fileName)); while ((entry = archive.getNextEntry()) != null) { // Sometimes skip reading entries. if (rnd.nextBoolean()) { continue; } if (entry.hasStream()) { assertTrue(entriesByName.containsKey(entry.getName())); final byte [] content = readFully(archive); assertTrue("Content mismatch on: " + fileName + "!" + entry.getName(), Arrays.equals(content, entriesByName.get(entry.getName()))); } } archive.close(); } } private byte[] readFully(final SevenZFile archive) throws IOException { final byte [] buf = new byte [1024]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int len = 0; (len = archive.read(buf)) > 0;) { baos.write(buf, 0, len); } return baos.toByteArray(); } @Test public void testAllEmptyFilesArchive() throws Exception { final SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z")); try { assertNotNull(archive.getNextEntry()); } finally { archive.close(); } } @Test public void testHelloWorldHeaderCompressionOffCopy() throws Exception { checkHelloWorld("7z-hello-mhc-off-copy.7z"); } @Test public void testHelloWorldHeaderCompressionOffLZMA2() throws Exception { checkHelloWorld("7z-hello-mhc-off-lzma2.7z"); } @Test public void test7zUnarchive() throws Exception { test7zUnarchive(getFile("bla.7z"), SevenZMethod.LZMA); } @Test public void test7zDeflateUnarchive() throws Exception { test7zUnarchive(getFile("bla.deflate.7z"), SevenZMethod.DEFLATE); } @Test public void test7zDecryptUnarchive() throws Exception { if (isStrongCryptoAvailable()) { test7zUnarchive(getFile("bla.encrypted.7z"), SevenZMethod.LZMA, // stack LZMA + AES "foo".getBytes("UTF-16LE")); } } private void test7zUnarchive(final File f, final SevenZMethod m) throws Exception { test7zUnarchive(f, m, null); } @Test public void testEncryptedArchiveRequiresPassword() throws Exception { try { new SevenZFile(getFile("bla.encrypted.7z")); fail("shouldn't decrypt without a password"); } catch (final PasswordRequiredException ex) { final String msg = ex.getMessage(); assertTrue("Should start with whining about being unable to decrypt", msg.startsWith("Cannot read encrypted content from ")); assertTrue("Should finish the sentence properly", msg.endsWith(" without a password.")); assertTrue("Should contain archive's name", msg.contains("bla.encrypted.7z")); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-256" */ @Test public void testCompressedHeaderWithNonDefaultDictionarySize() throws Exception { final SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z")); try { int count = 0; while (sevenZFile.getNextEntry() != null) { count++; } assertEquals(446, count); } finally { sevenZFile.close(); } } @Test public void testSignatureCheck() { assertTrue(SevenZFile.matches(SevenZFile.sevenZSignature, SevenZFile.sevenZSignature.length)); assertTrue(SevenZFile.matches(SevenZFile.sevenZSignature, SevenZFile.sevenZSignature.length + 1)); assertFalse(SevenZFile.matches(SevenZFile.sevenZSignature, SevenZFile.sevenZSignature.length - 1)); assertFalse(SevenZFile.matches(new byte[] { 1, 2, 3, 4, 5, 6 }, 6)); assertTrue(SevenZFile.matches(new byte[] { '7', 'z', (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C}, 6)); assertFalse(SevenZFile.matches(new byte[] { '7', 'z', (byte) 0xBC, (byte) 0xAF, 0x27, 0x1D}, 6)); } @Test public void testReadingBackLZMA2DictSize() throws Exception { final File output = new File(dir, "lzma2-dictsize.7z"); final SevenZOutputFile outArchive = new SevenZOutputFile(output); try { outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20))); final SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo.txt"); outArchive.putArchiveEntry(entry); outArchive.write(new byte[] { 'A' }); outArchive.closeArchiveEntry(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { final SevenZArchiveEntry entry = archive.getNextEntry(); final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next(); assertEquals(SevenZMethod.LZMA2, m.getMethod()); assertEquals(1 << 20, m.getOptions()); } finally { archive.close(); } } @Test public void testReadingBackDeltaDistance() throws Exception { final File output = new File(dir, "delta-distance.7z"); final SevenZOutputFile outArchive = new SevenZOutputFile(output); try { outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.DELTA_FILTER, 32), new SevenZMethodConfiguration(SevenZMethod.LZMA2))); final SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo.txt"); outArchive.putArchiveEntry(entry); outArchive.write(new byte[] { 'A' }); outArchive.closeArchiveEntry(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { final SevenZArchiveEntry entry = archive.getNextEntry(); final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next(); assertEquals(SevenZMethod.DELTA_FILTER, m.getMethod()); assertEquals(32, m.getOptions()); } finally { archive.close(); } } @Test public void getEntriesOfUnarchiveTest() throws IOException { final SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z")); try { final Iterable<SevenZArchiveEntry> entries = sevenZFile.getEntries(); final Iterator<SevenZArchiveEntry> iter = entries.iterator(); SevenZArchiveEntry entry = iter.next(); assertEquals("test1.xml", entry.getName()); entry = iter.next(); assertEquals("test2.xml", entry.getName()); assertFalse(iter.hasNext()); } finally { sevenZFile.close(); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-348" */ @Test public void readEntriesOfSize0() throws IOException { final SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-348.7z")); try { int entries = 0; SevenZArchiveEntry entry = sevenZFile.getNextEntry(); while (entry != null) { entries++; int b = sevenZFile.read(); if ("2.txt".equals(entry.getName()) || "5.txt".equals(entry.getName())) { assertEquals(-1, b); } else { assertNotEquals(-1, b); } entry = sevenZFile.getNextEntry(); } assertEquals(5, entries); } finally { sevenZFile.close(); } } private void test7zUnarchive(final File f, final SevenZMethod m, final byte[] password) throws Exception { final SevenZFile sevenZFile = new SevenZFile(f, password); try { SevenZArchiveEntry entry = sevenZFile.getNextEntry(); assertEquals("test1.xml", entry.getName()); assertEquals(m, entry.getContentMethods().iterator().next().getMethod()); entry = sevenZFile.getNextEntry(); assertEquals("test2.xml", entry.getName()); assertEquals(m, entry.getContentMethods().iterator().next().getMethod()); final byte[] contents = new byte[(int)entry.getSize()]; int off = 0; while ((off < contents.length)) { final int bytesRead = sevenZFile.read(contents, off, contents.length - off); assert(bytesRead >= 0); off += bytesRead; } assertEquals(TEST2_CONTENT, new String(contents, "UTF-8")); assertNull(sevenZFile.getNextEntry()); } finally { sevenZFile.close(); } } private void checkHelloWorld(final String filename) throws Exception { final SevenZFile sevenZFile = new SevenZFile(getFile(filename)); try { final SevenZArchiveEntry entry = sevenZFile.getNextEntry(); assertEquals("Hello world.txt", entry.getName()); final byte[] contents = new byte[(int)entry.getSize()]; int off = 0; while ((off < contents.length)) { final int bytesRead = sevenZFile.read(contents, off, contents.length - off); assert(bytesRead >= 0); off += bytesRead; } assertEquals("Hello, world!\n", new String(contents, "UTF-8")); assertNull(sevenZFile.getNextEntry()); } finally { sevenZFile.close(); } } private static boolean isStrongCryptoAvailable() throws NoSuchAlgorithmException { return Cipher.getMaxAllowedKeyLength("AES/ECB/PKCS5Padding") >= 256; } }
// You are a professional Java test case writer, please create a test case named `readEntriesOfSize0` for the issue `Compress-COMPRESS-348`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-348 // // ## Issue-Title: // Calling SevenZFile.read() on empty SevenZArchiveEntry throws IllegalStateException // // ## Issue-Description: // // I'm pretty sure [~~COMPRESS-340~~](https://issues.apache.org/jira/browse/COMPRESS-340 "Provide an efficient way to skip over 7zip entries without decompressing them") breaks reading empty archive entries. When calling getNextEntry() and that entry has no content, the code jumps into the first block at line 830 (SevenZFile.class), clearing the deferredBlockStreams. When calling entry.read(...) afterwards an IllegalStateException ("No current 7z entry (call getNextEntry() first).") is thrown. IMHO, there should be another check for entry.getSize() == 0. // // // This worked correctly up until 1.10. // // // // // @Test public void readEntriesOfSize0() throws IOException {
285
/** * @see "https://issues.apache.org/jira/browse/COMPRESS-348" */
36
265
src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZFileTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-348 ## Issue-Title: Calling SevenZFile.read() on empty SevenZArchiveEntry throws IllegalStateException ## Issue-Description: I'm pretty sure [~~COMPRESS-340~~](https://issues.apache.org/jira/browse/COMPRESS-340 "Provide an efficient way to skip over 7zip entries without decompressing them") breaks reading empty archive entries. When calling getNextEntry() and that entry has no content, the code jumps into the first block at line 830 (SevenZFile.class), clearing the deferredBlockStreams. When calling entry.read(...) afterwards an IllegalStateException ("No current 7z entry (call getNextEntry() first).") is thrown. IMHO, there should be another check for entry.getSize() == 0. This worked correctly up until 1.10. ``` You are a professional Java test case writer, please create a test case named `readEntriesOfSize0` for the issue `Compress-COMPRESS-348`, utilizing the provided issue report information and the following function signature. ```java @Test public void readEntriesOfSize0() throws IOException { ```
265
[ "org.apache.commons.compress.archivers.sevenz.SevenZFile" ]
fb5e83c2952d71efa56dfd762c1053589fc2199486cf683b77c79573e1f88fe3
@Test public void readEntriesOfSize0() throws IOException
// You are a professional Java test case writer, please create a test case named `readEntriesOfSize0` for the issue `Compress-COMPRESS-348`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-348 // // ## Issue-Title: // Calling SevenZFile.read() on empty SevenZArchiveEntry throws IllegalStateException // // ## Issue-Description: // // I'm pretty sure [~~COMPRESS-340~~](https://issues.apache.org/jira/browse/COMPRESS-340 "Provide an efficient way to skip over 7zip entries without decompressing them") breaks reading empty archive entries. When calling getNextEntry() and that entry has no content, the code jumps into the first block at line 830 (SevenZFile.class), clearing the deferredBlockStreams. When calling entry.read(...) afterwards an IllegalStateException ("No current 7z entry (call getNextEntry() first).") is thrown. IMHO, there should be another check for entry.getSize() == 0. // // // This worked correctly up until 1.10. // // // // //
Compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.sevenz; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import javax.crypto.Cipher; import org.apache.commons.compress.AbstractTestCase; import org.apache.commons.compress.PasswordRequiredException; import org.junit.Test; public class SevenZFileTest extends AbstractTestCase { private static final String TEST2_CONTENT = "<?xml version = '1.0'?>\r\n<!DOCTYPE" + " connections>\r\n<meinxml>\r\n\t<leer />\r\n</meinxml>\n"; // https://issues.apache.org/jira/browse/COMPRESS-320 @Test public void testRandomlySkippingEntries() throws Exception { // Read sequential reference. final Map<String, byte[]> entriesByName = new HashMap<String, byte[]>(); SevenZFile archive = new SevenZFile(getFile("COMPRESS-320/Copy.7z")); SevenZArchiveEntry entry; while ((entry = archive.getNextEntry()) != null) { if (entry.hasStream()) { entriesByName.put(entry.getName(), readFully(archive)); } } archive.close(); final String[] variants = { "BZip2-solid.7z", "BZip2.7z", "Copy-solid.7z", "Copy.7z", "Deflate-solid.7z", "Deflate.7z", "LZMA-solid.7z", "LZMA.7z", "LZMA2-solid.7z", "LZMA2.7z", // TODO: unsupported compression method. // "PPMd-solid.7z", // "PPMd.7z", }; // TODO: use randomizedtesting for predictable, but different, randomness. final Random rnd = new Random(0xdeadbeef); for (final String fileName : variants) { archive = new SevenZFile(getFile("COMPRESS-320/" + fileName)); while ((entry = archive.getNextEntry()) != null) { // Sometimes skip reading entries. if (rnd.nextBoolean()) { continue; } if (entry.hasStream()) { assertTrue(entriesByName.containsKey(entry.getName())); final byte [] content = readFully(archive); assertTrue("Content mismatch on: " + fileName + "!" + entry.getName(), Arrays.equals(content, entriesByName.get(entry.getName()))); } } archive.close(); } } private byte[] readFully(final SevenZFile archive) throws IOException { final byte [] buf = new byte [1024]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int len = 0; (len = archive.read(buf)) > 0;) { baos.write(buf, 0, len); } return baos.toByteArray(); } @Test public void testAllEmptyFilesArchive() throws Exception { final SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z")); try { assertNotNull(archive.getNextEntry()); } finally { archive.close(); } } @Test public void testHelloWorldHeaderCompressionOffCopy() throws Exception { checkHelloWorld("7z-hello-mhc-off-copy.7z"); } @Test public void testHelloWorldHeaderCompressionOffLZMA2() throws Exception { checkHelloWorld("7z-hello-mhc-off-lzma2.7z"); } @Test public void test7zUnarchive() throws Exception { test7zUnarchive(getFile("bla.7z"), SevenZMethod.LZMA); } @Test public void test7zDeflateUnarchive() throws Exception { test7zUnarchive(getFile("bla.deflate.7z"), SevenZMethod.DEFLATE); } @Test public void test7zDecryptUnarchive() throws Exception { if (isStrongCryptoAvailable()) { test7zUnarchive(getFile("bla.encrypted.7z"), SevenZMethod.LZMA, // stack LZMA + AES "foo".getBytes("UTF-16LE")); } } private void test7zUnarchive(final File f, final SevenZMethod m) throws Exception { test7zUnarchive(f, m, null); } @Test public void testEncryptedArchiveRequiresPassword() throws Exception { try { new SevenZFile(getFile("bla.encrypted.7z")); fail("shouldn't decrypt without a password"); } catch (final PasswordRequiredException ex) { final String msg = ex.getMessage(); assertTrue("Should start with whining about being unable to decrypt", msg.startsWith("Cannot read encrypted content from ")); assertTrue("Should finish the sentence properly", msg.endsWith(" without a password.")); assertTrue("Should contain archive's name", msg.contains("bla.encrypted.7z")); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-256" */ @Test public void testCompressedHeaderWithNonDefaultDictionarySize() throws Exception { final SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z")); try { int count = 0; while (sevenZFile.getNextEntry() != null) { count++; } assertEquals(446, count); } finally { sevenZFile.close(); } } @Test public void testSignatureCheck() { assertTrue(SevenZFile.matches(SevenZFile.sevenZSignature, SevenZFile.sevenZSignature.length)); assertTrue(SevenZFile.matches(SevenZFile.sevenZSignature, SevenZFile.sevenZSignature.length + 1)); assertFalse(SevenZFile.matches(SevenZFile.sevenZSignature, SevenZFile.sevenZSignature.length - 1)); assertFalse(SevenZFile.matches(new byte[] { 1, 2, 3, 4, 5, 6 }, 6)); assertTrue(SevenZFile.matches(new byte[] { '7', 'z', (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C}, 6)); assertFalse(SevenZFile.matches(new byte[] { '7', 'z', (byte) 0xBC, (byte) 0xAF, 0x27, 0x1D}, 6)); } @Test public void testReadingBackLZMA2DictSize() throws Exception { final File output = new File(dir, "lzma2-dictsize.7z"); final SevenZOutputFile outArchive = new SevenZOutputFile(output); try { outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20))); final SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo.txt"); outArchive.putArchiveEntry(entry); outArchive.write(new byte[] { 'A' }); outArchive.closeArchiveEntry(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { final SevenZArchiveEntry entry = archive.getNextEntry(); final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next(); assertEquals(SevenZMethod.LZMA2, m.getMethod()); assertEquals(1 << 20, m.getOptions()); } finally { archive.close(); } } @Test public void testReadingBackDeltaDistance() throws Exception { final File output = new File(dir, "delta-distance.7z"); final SevenZOutputFile outArchive = new SevenZOutputFile(output); try { outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.DELTA_FILTER, 32), new SevenZMethodConfiguration(SevenZMethod.LZMA2))); final SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setName("foo.txt"); outArchive.putArchiveEntry(entry); outArchive.write(new byte[] { 'A' }); outArchive.closeArchiveEntry(); } finally { outArchive.close(); } final SevenZFile archive = new SevenZFile(output); try { final SevenZArchiveEntry entry = archive.getNextEntry(); final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next(); assertEquals(SevenZMethod.DELTA_FILTER, m.getMethod()); assertEquals(32, m.getOptions()); } finally { archive.close(); } } @Test public void getEntriesOfUnarchiveTest() throws IOException { final SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z")); try { final Iterable<SevenZArchiveEntry> entries = sevenZFile.getEntries(); final Iterator<SevenZArchiveEntry> iter = entries.iterator(); SevenZArchiveEntry entry = iter.next(); assertEquals("test1.xml", entry.getName()); entry = iter.next(); assertEquals("test2.xml", entry.getName()); assertFalse(iter.hasNext()); } finally { sevenZFile.close(); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-348" */ @Test public void readEntriesOfSize0() throws IOException { final SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-348.7z")); try { int entries = 0; SevenZArchiveEntry entry = sevenZFile.getNextEntry(); while (entry != null) { entries++; int b = sevenZFile.read(); if ("2.txt".equals(entry.getName()) || "5.txt".equals(entry.getName())) { assertEquals(-1, b); } else { assertNotEquals(-1, b); } entry = sevenZFile.getNextEntry(); } assertEquals(5, entries); } finally { sevenZFile.close(); } } private void test7zUnarchive(final File f, final SevenZMethod m, final byte[] password) throws Exception { final SevenZFile sevenZFile = new SevenZFile(f, password); try { SevenZArchiveEntry entry = sevenZFile.getNextEntry(); assertEquals("test1.xml", entry.getName()); assertEquals(m, entry.getContentMethods().iterator().next().getMethod()); entry = sevenZFile.getNextEntry(); assertEquals("test2.xml", entry.getName()); assertEquals(m, entry.getContentMethods().iterator().next().getMethod()); final byte[] contents = new byte[(int)entry.getSize()]; int off = 0; while ((off < contents.length)) { final int bytesRead = sevenZFile.read(contents, off, contents.length - off); assert(bytesRead >= 0); off += bytesRead; } assertEquals(TEST2_CONTENT, new String(contents, "UTF-8")); assertNull(sevenZFile.getNextEntry()); } finally { sevenZFile.close(); } } private void checkHelloWorld(final String filename) throws Exception { final SevenZFile sevenZFile = new SevenZFile(getFile(filename)); try { final SevenZArchiveEntry entry = sevenZFile.getNextEntry(); assertEquals("Hello world.txt", entry.getName()); final byte[] contents = new byte[(int)entry.getSize()]; int off = 0; while ((off < contents.length)) { final int bytesRead = sevenZFile.read(contents, off, contents.length - off); assert(bytesRead >= 0); off += bytesRead; } assertEquals("Hello, world!\n", new String(contents, "UTF-8")); assertNull(sevenZFile.getNextEntry()); } finally { sevenZFile.close(); } } private static boolean isStrongCryptoAvailable() throws NoSuchAlgorithmException { return Cipher.getMaxAllowedKeyLength("AES/ECB/PKCS5Padding") >= 256; } }
public void testIssue941() throws Exception { ObjectNode object = MAPPER.createObjectNode(); String json = MAPPER.writeValueAsString(object); System.out.println("json: "+json); ObjectNode de1 = MAPPER.readValue(json, ObjectNode.class); // this works System.out.println("Deserialized to ObjectNode: "+de1); MyValue de2 = MAPPER.readValue(json, MyValue.class); // but this throws exception System.out.println("Deserialized to MyValue: "+de2); }
com.fasterxml.jackson.databind.node.TestObjectNode::testIssue941
src/test/java/com/fasterxml/jackson/databind/node/TestObjectNode.java
412
src/test/java/com/fasterxml/jackson/databind/node/TestObjectNode.java
testIssue941
package com.fasterxml.jackson.databind.node; import java.math.BigDecimal; import java.util.*; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * Additional tests for {@link ObjectNode} container class. */ public class TestObjectNode extends BaseMapTest { @JsonDeserialize(as = DataImpl.class) public interface Data { } public static class DataImpl implements Data { protected JsonNode root; @JsonCreator public DataImpl(JsonNode n) { root = n; } @JsonValue public JsonNode value() { return root; } /* public Wrapper(ObjectNode n) { root = n; } @JsonValue public ObjectNode value() { return root; } */ } static class ObNodeWrapper { @JsonInclude(JsonInclude.Include.NON_EMPTY) public ObjectNode node; public ObNodeWrapper(ObjectNode n) { node = n; } } // [databind#941] static class MyValue { private final ObjectNode object; @JsonCreator public MyValue(ObjectNode object) { this.object = object; } @JsonValue public ObjectNode getObject() { return object; } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); public void testSimpleObject() throws Exception { String JSON = "{ \"key\" : 1, \"b\" : \"x\" }"; JsonNode root = MAPPER.readTree(JSON); // basic properties first: assertFalse(root.isValueNode()); assertTrue(root.isContainerNode()); assertFalse(root.isArray()); assertTrue(root.isObject()); assertEquals(2, root.size()); // Related to [JACKSON-50]: Iterator<JsonNode> it = root.iterator(); assertNotNull(it); assertTrue(it.hasNext()); JsonNode n = it.next(); assertNotNull(n); assertEquals(IntNode.valueOf(1), n); assertTrue(it.hasNext()); n = it.next(); assertNotNull(n); assertEquals(TextNode.valueOf("x"), n); assertFalse(it.hasNext()); // Ok, then, let's traverse via extended interface ObjectNode obNode = (ObjectNode) root; Iterator<Map.Entry<String,JsonNode>> fit = obNode.fields(); // we also know that LinkedHashMap is used, i.e. order preserved assertTrue(fit.hasNext()); Map.Entry<String,JsonNode> en = fit.next(); assertEquals("key", en.getKey()); assertEquals(IntNode.valueOf(1), en.getValue()); assertTrue(fit.hasNext()); en = fit.next(); assertEquals("b", en.getKey()); assertEquals(TextNode.valueOf("x"), en.getValue()); // Plus: we should be able to modify the node via iterator too: fit.remove(); assertEquals(1, obNode.size()); assertEquals(IntNode.valueOf(1), root.get("key")); assertNull(root.get("b")); } // for [Issue#346] public void testEmptyNodeAsValue() throws Exception { Data w = MAPPER.readValue("{}", Data.class); assertNotNull(w); } public void testBasics() { ObjectNode n = new ObjectNode(JsonNodeFactory.instance); assertStandardEquals(n); assertFalse(n.elements().hasNext()); assertFalse(n.fields().hasNext()); assertFalse(n.fieldNames().hasNext()); assertNull(n.get("a")); assertTrue(n.path("a").isMissingNode()); TextNode text = TextNode.valueOf("x"); assertSame(n, n.set("a", text)); assertEquals(1, n.size()); assertTrue(n.elements().hasNext()); assertTrue(n.fields().hasNext()); assertTrue(n.fieldNames().hasNext()); assertSame(text, n.get("a")); assertSame(text, n.path("a")); assertNull(n.get("b")); assertNull(n.get(0)); // not used with objects assertFalse(n.has(0)); assertFalse(n.hasNonNull(0)); assertTrue(n.has("a")); assertTrue(n.hasNonNull("a")); assertFalse(n.has("b")); assertFalse(n.hasNonNull("b")); ObjectNode n2 = new ObjectNode(JsonNodeFactory.instance); n2.put("b", 13); assertFalse(n.equals(n2)); n.setAll(n2); assertEquals(2, n.size()); n.set("null", (JsonNode)null); assertEquals(3, n.size()); // may be non-intuitive, but explicit nulls do exist in tree: assertTrue(n.has("null")); assertFalse(n.hasNonNull("null")); // should replace, not add n.put("null", "notReallNull"); assertEquals(3, n.size()); assertNotNull(n.remove("null")); assertEquals(2, n.size()); Map<String,JsonNode> nodes = new HashMap<String,JsonNode>(); nodes.put("d", text); n.setAll(nodes); assertEquals(3, n.size()); n.removeAll(); assertEquals(0, n.size()); } /** * Verify null handling */ public void testNullChecking() { ObjectNode o1 = JsonNodeFactory.instance.objectNode(); ObjectNode o2 = JsonNodeFactory.instance.objectNode(); // used to throw NPE before fix: o1.setAll(o2); assertEquals(0, o1.size()); assertEquals(0, o2.size()); // also: nulls should be converted to NullNodes... o1.set("x", null); JsonNode n = o1.get("x"); assertNotNull(n); assertSame(n, NullNode.instance); o1.put("str", (String) null); n = o1.get("str"); assertNotNull(n); assertSame(n, NullNode.instance); o1.put("d", (BigDecimal) null); n = o1.get("d"); assertNotNull(n); assertSame(n, NullNode.instance); } /** * Another test to verify [JACKSON-227]... */ public void testNullChecking2() { ObjectNode src = MAPPER.createObjectNode(); ObjectNode dest = MAPPER.createObjectNode(); src.put("a", "b"); dest.setAll(src); } public void testRemove() { ObjectNode ob = MAPPER.createObjectNode(); ob.put("a", "a"); ob.put("b", "b"); ob.put("c", "c"); assertEquals(3, ob.size()); assertSame(ob, ob.without(Arrays.asList("a", "c"))); assertEquals(1, ob.size()); assertEquals("b", ob.get("b").textValue()); } public void testRetain() { ObjectNode ob = MAPPER.createObjectNode(); ob.put("a", "a"); ob.put("b", "b"); ob.put("c", "c"); assertEquals(3, ob.size()); assertSame(ob, ob.retain("a", "c")); assertEquals(2, ob.size()); assertEquals("a", ob.get("a").textValue()); assertNull(ob.get("b")); assertEquals("c", ob.get("c").textValue()); } public void testValidWith() throws Exception { ObjectNode root = MAPPER.createObjectNode(); assertEquals("{}", MAPPER.writeValueAsString(root)); JsonNode child = root.with("prop"); assertTrue(child instanceof ObjectNode); assertEquals("{\"prop\":{}}", MAPPER.writeValueAsString(root)); } public void testValidWithArray() throws Exception { ObjectNode root = MAPPER.createObjectNode(); assertEquals("{}", MAPPER.writeValueAsString(root)); JsonNode child = root.withArray("arr"); assertTrue(child instanceof ArrayNode); assertEquals("{\"arr\":[]}", MAPPER.writeValueAsString(root)); } public void testInvalidWith() throws Exception { JsonNode root = MAPPER.createArrayNode(); try { // should not work for non-ObjectNode nodes: root.with("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "not of type ObjectNode"); } // also: should fail of we already have non-object property ObjectNode root2 = MAPPER.createObjectNode(); root2.put("prop", 13); try { // should not work for non-ObjectNode nodes: root2.with("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "has value that is not"); } } public void testInvalidWithArray() throws Exception { JsonNode root = MAPPER.createArrayNode(); try { // should not work for non-ObjectNode nodes: root.withArray("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "not of type ObjectNode"); } // also: should fail of we already have non-Array property ObjectNode root2 = MAPPER.createObjectNode(); root2.put("prop", 13); try { // should not work for non-ObjectNode nodes: root2.withArray("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "has value that is not"); } } // [Issue#93] public void testSetAll() throws Exception { ObjectNode root = MAPPER.createObjectNode(); assertEquals(0, root.size()); HashMap<String,JsonNode> map = new HashMap<String,JsonNode>(); map.put("a", root.numberNode(1)); root.setAll(map); assertEquals(1, root.size()); assertTrue(root.has("a")); assertFalse(root.has("b")); map.put("b", root.numberNode(2)); root.setAll(map); assertEquals(2, root.size()); assertTrue(root.has("a")); assertTrue(root.has("b")); assertEquals(2, root.path("b").intValue()); // Then with ObjectNodes... ObjectNode root2 = MAPPER.createObjectNode(); root2.setAll(root); assertEquals(2, root.size()); assertEquals(2, root2.size()); root2.setAll(root); assertEquals(2, root.size()); assertEquals(2, root2.size()); ObjectNode root3 = MAPPER.createObjectNode(); root3.put("a", 2); root3.put("c", 3); assertEquals(2, root3.path("a").intValue()); root3.setAll(root2); assertEquals(3, root3.size()); assertEquals(1, root3.path("a").intValue()); } // [Issue#237] (databind): support DeserializationFeature#FAIL_ON_READING_DUP_TREE_KEY public void testFailOnDupKeys() throws Exception { final String DUP_JSON = "{ \"a\":1, \"a\":2 }"; // first: verify defaults: ObjectMapper mapper = new ObjectMapper(); assertFalse(mapper.isEnabled(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY)); ObjectNode root = (ObjectNode) mapper.readTree(DUP_JSON); assertEquals(2, root.path("a").asInt()); // and then enable checks: try { mapper.reader(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY).readTree(DUP_JSON); fail("Should have thrown exception!"); } catch (JsonMappingException e) { verifyException(e, "duplicate field 'a'"); } } public void testEqualityWrtOrder() throws Exception { ObjectNode ob1 = MAPPER.createObjectNode(); ObjectNode ob2 = MAPPER.createObjectNode(); // same contents, different insertion order; should not matter ob1.put("a", 1); ob1.put("b", 2); ob1.put("c", 3); ob2.put("b", 2); ob2.put("c", 3); ob2.put("a", 1); assertTrue(ob1.equals(ob2)); assertTrue(ob2.equals(ob1)); } public void testSimplePath() throws Exception { JsonNode root = MAPPER.readTree("{ \"results\" : { \"a\" : 3 } }"); assertTrue(root.isObject()); JsonNode rnode = root.path("results"); assertNotNull(rnode); assertTrue(rnode.isObject()); assertEquals(3, rnode.path("a").intValue()); } public void testNonEmptySerialization() throws Exception { ObNodeWrapper w = new ObNodeWrapper(MAPPER.createObjectNode() .put("a", 3)); assertEquals("{\"node\":{\"a\":3}}", MAPPER.writeValueAsString(w)); w = new ObNodeWrapper(MAPPER.createObjectNode()); assertEquals("{}", MAPPER.writeValueAsString(w)); } public void testIssue941() throws Exception { ObjectNode object = MAPPER.createObjectNode(); String json = MAPPER.writeValueAsString(object); System.out.println("json: "+json); ObjectNode de1 = MAPPER.readValue(json, ObjectNode.class); // this works System.out.println("Deserialized to ObjectNode: "+de1); MyValue de2 = MAPPER.readValue(json, MyValue.class); // but this throws exception System.out.println("Deserialized to MyValue: "+de2); } }
// You are a professional Java test case writer, please create a test case named `testIssue941` for the issue `JacksonDatabind-941`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-941 // // ## Issue-Title: // Deserialization from "{}" to ObjectNode field causes "out of END_OBJECT token" error // // ## Issue-Description: // I found that deserializing from an empty object (`{}`) to ObjectNode field in a class field fails. // // // Here is the minimum code to reproduce: // // // // ``` // public class Main // { // public static class MyValue // { // private final ObjectNode object; // // @JsonCreator // public MyValue(ObjectNode object) { this.object = object; } // // @JsonValue // public ObjectNode getObject() { return object; } // } // // public static void main(String[] args) // throws Exception // { // ObjectMapper om = new ObjectMapper(); // // ObjectNode object = new ObjectNode(JsonNodeFactory.instance); // // String json = om.writeValueAsString(object); // System.out.println("json: "+json); // // ObjectNode de1 = om.readValue(json, ObjectNode.class); // this works // System.out.println("Deserialized to ObjectNode: "+de1); // // MyValue de2 = om.readValue(json, MyValue.class); // but this throws exception // System.out.println("Deserialized to MyValue: "+de2); // } // } // ``` // // Result is: // // // // ``` // json: {} // Deserialized to ObjectNode: {} // Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.fasterxml.jackson.databind.node.ObjectNode out of END_OBJECT token // at [Source: {}; line: 1, column: 2] // at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) // at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854) // at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850) // at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer$ObjectDeserializer.deserialize(JsonNodeDeserializer.java:104) // at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer$ObjectDeserializer.deserialize(JsonNodeDeserializer.java:83) // at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1095) // at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:294) // at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:131) // at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3731) // at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2724) // at Main.main(Main.java:35) // // ``` // // If the object is not empty (e.g. `{"k":"v"}`), it works public void testIssue941() throws Exception {
412
28
400
src/test/java/com/fasterxml/jackson/databind/node/TestObjectNode.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-941 ## Issue-Title: Deserialization from "{}" to ObjectNode field causes "out of END_OBJECT token" error ## Issue-Description: I found that deserializing from an empty object (`{}`) to ObjectNode field in a class field fails. Here is the minimum code to reproduce: ``` public class Main { public static class MyValue { private final ObjectNode object; @JsonCreator public MyValue(ObjectNode object) { this.object = object; } @JsonValue public ObjectNode getObject() { return object; } } public static void main(String[] args) throws Exception { ObjectMapper om = new ObjectMapper(); ObjectNode object = new ObjectNode(JsonNodeFactory.instance); String json = om.writeValueAsString(object); System.out.println("json: "+json); ObjectNode de1 = om.readValue(json, ObjectNode.class); // this works System.out.println("Deserialized to ObjectNode: "+de1); MyValue de2 = om.readValue(json, MyValue.class); // but this throws exception System.out.println("Deserialized to MyValue: "+de2); } } ``` Result is: ``` json: {} Deserialized to ObjectNode: {} Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.fasterxml.jackson.databind.node.ObjectNode out of END_OBJECT token at [Source: {}; line: 1, column: 2] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854) at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850) at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer$ObjectDeserializer.deserialize(JsonNodeDeserializer.java:104) at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer$ObjectDeserializer.deserialize(JsonNodeDeserializer.java:83) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1095) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:294) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:131) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3731) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2724) at Main.main(Main.java:35) ``` If the object is not empty (e.g. `{"k":"v"}`), it works ``` You are a professional Java test case writer, please create a test case named `testIssue941` for the issue `JacksonDatabind-941`, utilizing the provided issue report information and the following function signature. ```java public void testIssue941() throws Exception { ```
400
[ "com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer" ]
fbad6fc02162b1f032b4603476f6284b76a055ed4ce938bd926712a0f80b0bee
public void testIssue941() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue941` for the issue `JacksonDatabind-941`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-941 // // ## Issue-Title: // Deserialization from "{}" to ObjectNode field causes "out of END_OBJECT token" error // // ## Issue-Description: // I found that deserializing from an empty object (`{}`) to ObjectNode field in a class field fails. // // // Here is the minimum code to reproduce: // // // // ``` // public class Main // { // public static class MyValue // { // private final ObjectNode object; // // @JsonCreator // public MyValue(ObjectNode object) { this.object = object; } // // @JsonValue // public ObjectNode getObject() { return object; } // } // // public static void main(String[] args) // throws Exception // { // ObjectMapper om = new ObjectMapper(); // // ObjectNode object = new ObjectNode(JsonNodeFactory.instance); // // String json = om.writeValueAsString(object); // System.out.println("json: "+json); // // ObjectNode de1 = om.readValue(json, ObjectNode.class); // this works // System.out.println("Deserialized to ObjectNode: "+de1); // // MyValue de2 = om.readValue(json, MyValue.class); // but this throws exception // System.out.println("Deserialized to MyValue: "+de2); // } // } // ``` // // Result is: // // // // ``` // json: {} // Deserialized to ObjectNode: {} // Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.fasterxml.jackson.databind.node.ObjectNode out of END_OBJECT token // at [Source: {}; line: 1, column: 2] // at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) // at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854) // at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850) // at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer$ObjectDeserializer.deserialize(JsonNodeDeserializer.java:104) // at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer$ObjectDeserializer.deserialize(JsonNodeDeserializer.java:83) // at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1095) // at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:294) // at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:131) // at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3731) // at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2724) // at Main.main(Main.java:35) // // ``` // // If the object is not empty (e.g. `{"k":"v"}`), it works
JacksonDatabind
package com.fasterxml.jackson.databind.node; import java.math.BigDecimal; import java.util.*; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * Additional tests for {@link ObjectNode} container class. */ public class TestObjectNode extends BaseMapTest { @JsonDeserialize(as = DataImpl.class) public interface Data { } public static class DataImpl implements Data { protected JsonNode root; @JsonCreator public DataImpl(JsonNode n) { root = n; } @JsonValue public JsonNode value() { return root; } /* public Wrapper(ObjectNode n) { root = n; } @JsonValue public ObjectNode value() { return root; } */ } static class ObNodeWrapper { @JsonInclude(JsonInclude.Include.NON_EMPTY) public ObjectNode node; public ObNodeWrapper(ObjectNode n) { node = n; } } // [databind#941] static class MyValue { private final ObjectNode object; @JsonCreator public MyValue(ObjectNode object) { this.object = object; } @JsonValue public ObjectNode getObject() { return object; } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); public void testSimpleObject() throws Exception { String JSON = "{ \"key\" : 1, \"b\" : \"x\" }"; JsonNode root = MAPPER.readTree(JSON); // basic properties first: assertFalse(root.isValueNode()); assertTrue(root.isContainerNode()); assertFalse(root.isArray()); assertTrue(root.isObject()); assertEquals(2, root.size()); // Related to [JACKSON-50]: Iterator<JsonNode> it = root.iterator(); assertNotNull(it); assertTrue(it.hasNext()); JsonNode n = it.next(); assertNotNull(n); assertEquals(IntNode.valueOf(1), n); assertTrue(it.hasNext()); n = it.next(); assertNotNull(n); assertEquals(TextNode.valueOf("x"), n); assertFalse(it.hasNext()); // Ok, then, let's traverse via extended interface ObjectNode obNode = (ObjectNode) root; Iterator<Map.Entry<String,JsonNode>> fit = obNode.fields(); // we also know that LinkedHashMap is used, i.e. order preserved assertTrue(fit.hasNext()); Map.Entry<String,JsonNode> en = fit.next(); assertEquals("key", en.getKey()); assertEquals(IntNode.valueOf(1), en.getValue()); assertTrue(fit.hasNext()); en = fit.next(); assertEquals("b", en.getKey()); assertEquals(TextNode.valueOf("x"), en.getValue()); // Plus: we should be able to modify the node via iterator too: fit.remove(); assertEquals(1, obNode.size()); assertEquals(IntNode.valueOf(1), root.get("key")); assertNull(root.get("b")); } // for [Issue#346] public void testEmptyNodeAsValue() throws Exception { Data w = MAPPER.readValue("{}", Data.class); assertNotNull(w); } public void testBasics() { ObjectNode n = new ObjectNode(JsonNodeFactory.instance); assertStandardEquals(n); assertFalse(n.elements().hasNext()); assertFalse(n.fields().hasNext()); assertFalse(n.fieldNames().hasNext()); assertNull(n.get("a")); assertTrue(n.path("a").isMissingNode()); TextNode text = TextNode.valueOf("x"); assertSame(n, n.set("a", text)); assertEquals(1, n.size()); assertTrue(n.elements().hasNext()); assertTrue(n.fields().hasNext()); assertTrue(n.fieldNames().hasNext()); assertSame(text, n.get("a")); assertSame(text, n.path("a")); assertNull(n.get("b")); assertNull(n.get(0)); // not used with objects assertFalse(n.has(0)); assertFalse(n.hasNonNull(0)); assertTrue(n.has("a")); assertTrue(n.hasNonNull("a")); assertFalse(n.has("b")); assertFalse(n.hasNonNull("b")); ObjectNode n2 = new ObjectNode(JsonNodeFactory.instance); n2.put("b", 13); assertFalse(n.equals(n2)); n.setAll(n2); assertEquals(2, n.size()); n.set("null", (JsonNode)null); assertEquals(3, n.size()); // may be non-intuitive, but explicit nulls do exist in tree: assertTrue(n.has("null")); assertFalse(n.hasNonNull("null")); // should replace, not add n.put("null", "notReallNull"); assertEquals(3, n.size()); assertNotNull(n.remove("null")); assertEquals(2, n.size()); Map<String,JsonNode> nodes = new HashMap<String,JsonNode>(); nodes.put("d", text); n.setAll(nodes); assertEquals(3, n.size()); n.removeAll(); assertEquals(0, n.size()); } /** * Verify null handling */ public void testNullChecking() { ObjectNode o1 = JsonNodeFactory.instance.objectNode(); ObjectNode o2 = JsonNodeFactory.instance.objectNode(); // used to throw NPE before fix: o1.setAll(o2); assertEquals(0, o1.size()); assertEquals(0, o2.size()); // also: nulls should be converted to NullNodes... o1.set("x", null); JsonNode n = o1.get("x"); assertNotNull(n); assertSame(n, NullNode.instance); o1.put("str", (String) null); n = o1.get("str"); assertNotNull(n); assertSame(n, NullNode.instance); o1.put("d", (BigDecimal) null); n = o1.get("d"); assertNotNull(n); assertSame(n, NullNode.instance); } /** * Another test to verify [JACKSON-227]... */ public void testNullChecking2() { ObjectNode src = MAPPER.createObjectNode(); ObjectNode dest = MAPPER.createObjectNode(); src.put("a", "b"); dest.setAll(src); } public void testRemove() { ObjectNode ob = MAPPER.createObjectNode(); ob.put("a", "a"); ob.put("b", "b"); ob.put("c", "c"); assertEquals(3, ob.size()); assertSame(ob, ob.without(Arrays.asList("a", "c"))); assertEquals(1, ob.size()); assertEquals("b", ob.get("b").textValue()); } public void testRetain() { ObjectNode ob = MAPPER.createObjectNode(); ob.put("a", "a"); ob.put("b", "b"); ob.put("c", "c"); assertEquals(3, ob.size()); assertSame(ob, ob.retain("a", "c")); assertEquals(2, ob.size()); assertEquals("a", ob.get("a").textValue()); assertNull(ob.get("b")); assertEquals("c", ob.get("c").textValue()); } public void testValidWith() throws Exception { ObjectNode root = MAPPER.createObjectNode(); assertEquals("{}", MAPPER.writeValueAsString(root)); JsonNode child = root.with("prop"); assertTrue(child instanceof ObjectNode); assertEquals("{\"prop\":{}}", MAPPER.writeValueAsString(root)); } public void testValidWithArray() throws Exception { ObjectNode root = MAPPER.createObjectNode(); assertEquals("{}", MAPPER.writeValueAsString(root)); JsonNode child = root.withArray("arr"); assertTrue(child instanceof ArrayNode); assertEquals("{\"arr\":[]}", MAPPER.writeValueAsString(root)); } public void testInvalidWith() throws Exception { JsonNode root = MAPPER.createArrayNode(); try { // should not work for non-ObjectNode nodes: root.with("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "not of type ObjectNode"); } // also: should fail of we already have non-object property ObjectNode root2 = MAPPER.createObjectNode(); root2.put("prop", 13); try { // should not work for non-ObjectNode nodes: root2.with("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "has value that is not"); } } public void testInvalidWithArray() throws Exception { JsonNode root = MAPPER.createArrayNode(); try { // should not work for non-ObjectNode nodes: root.withArray("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "not of type ObjectNode"); } // also: should fail of we already have non-Array property ObjectNode root2 = MAPPER.createObjectNode(); root2.put("prop", 13); try { // should not work for non-ObjectNode nodes: root2.withArray("prop"); fail("Expected exception"); } catch (UnsupportedOperationException e) { verifyException(e, "has value that is not"); } } // [Issue#93] public void testSetAll() throws Exception { ObjectNode root = MAPPER.createObjectNode(); assertEquals(0, root.size()); HashMap<String,JsonNode> map = new HashMap<String,JsonNode>(); map.put("a", root.numberNode(1)); root.setAll(map); assertEquals(1, root.size()); assertTrue(root.has("a")); assertFalse(root.has("b")); map.put("b", root.numberNode(2)); root.setAll(map); assertEquals(2, root.size()); assertTrue(root.has("a")); assertTrue(root.has("b")); assertEquals(2, root.path("b").intValue()); // Then with ObjectNodes... ObjectNode root2 = MAPPER.createObjectNode(); root2.setAll(root); assertEquals(2, root.size()); assertEquals(2, root2.size()); root2.setAll(root); assertEquals(2, root.size()); assertEquals(2, root2.size()); ObjectNode root3 = MAPPER.createObjectNode(); root3.put("a", 2); root3.put("c", 3); assertEquals(2, root3.path("a").intValue()); root3.setAll(root2); assertEquals(3, root3.size()); assertEquals(1, root3.path("a").intValue()); } // [Issue#237] (databind): support DeserializationFeature#FAIL_ON_READING_DUP_TREE_KEY public void testFailOnDupKeys() throws Exception { final String DUP_JSON = "{ \"a\":1, \"a\":2 }"; // first: verify defaults: ObjectMapper mapper = new ObjectMapper(); assertFalse(mapper.isEnabled(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY)); ObjectNode root = (ObjectNode) mapper.readTree(DUP_JSON); assertEquals(2, root.path("a").asInt()); // and then enable checks: try { mapper.reader(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY).readTree(DUP_JSON); fail("Should have thrown exception!"); } catch (JsonMappingException e) { verifyException(e, "duplicate field 'a'"); } } public void testEqualityWrtOrder() throws Exception { ObjectNode ob1 = MAPPER.createObjectNode(); ObjectNode ob2 = MAPPER.createObjectNode(); // same contents, different insertion order; should not matter ob1.put("a", 1); ob1.put("b", 2); ob1.put("c", 3); ob2.put("b", 2); ob2.put("c", 3); ob2.put("a", 1); assertTrue(ob1.equals(ob2)); assertTrue(ob2.equals(ob1)); } public void testSimplePath() throws Exception { JsonNode root = MAPPER.readTree("{ \"results\" : { \"a\" : 3 } }"); assertTrue(root.isObject()); JsonNode rnode = root.path("results"); assertNotNull(rnode); assertTrue(rnode.isObject()); assertEquals(3, rnode.path("a").intValue()); } public void testNonEmptySerialization() throws Exception { ObNodeWrapper w = new ObNodeWrapper(MAPPER.createObjectNode() .put("a", 3)); assertEquals("{\"node\":{\"a\":3}}", MAPPER.writeValueAsString(w)); w = new ObNodeWrapper(MAPPER.createObjectNode()); assertEquals("{}", MAPPER.writeValueAsString(w)); } public void testIssue941() throws Exception { ObjectNode object = MAPPER.createObjectNode(); String json = MAPPER.writeValueAsString(object); System.out.println("json: "+json); ObjectNode de1 = MAPPER.readValue(json, ObjectNode.class); // this works System.out.println("Deserialized to ObjectNode: "+de1); MyValue de2 = MAPPER.readValue(json, MyValue.class); // but this throws exception System.out.println("Deserialized to MyValue: "+de2); } }
public void testIssue1056() throws Exception { testTypes( "/** @type {Array} */ var x = null;" + "x.push('hi');", "No properties on this expression\n" + "found : null\n" + "required: Object"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue1056
test/com/google/javascript/jscomp/TypeCheckTest.java
6,916
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue1056
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheck25() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({b: 'abc'});", "actual parameter 1 of foo does not match formal parameter\n" + "found : {a: (number|undefined), b: string}\n" + "required: {a: number}"); } public void testTypeCheck26() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({a: 'abc'});", "actual parameter 1 of foo does not match formal parameter\n" + "found : {a: (number|string)}\n" + "required: {a: number}"); } public void testTypeCheck27() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({a: 123});"); } public void testTypeCheck28() throws Exception { testTypes("function foo(/** ? */ obj) {};" + "foo({a: 123});"); } public void testTypeCheckInlineReturns() throws Exception { testTypes( "function /** string */ foo(x) { return x; }" + "var /** number */ a = foo('abc');", "initializing variable\n" + "found : string\n" + "required: number"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = unknown;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = unknown;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = unknown;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testGoodExtends18() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor\n" + " * @template T */\n" + "function C() {}\n" + "/** @constructor\n" + " * @extends {C.<string>} */\n" + "function D() {};\n" + "goog.inherits(D, C);\n" + "(new D())"); } public void testGoodExtends19() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */\n" + "function C() {}\n" + "" + "/** @interface\n" + " * @template T */\n" + "function D() {}\n" + "/** @param {T} t */\n" + "D.prototype.method;\n" + "" + "/** @constructor\n" + " * @template T\n" + " * @extends {C}\n" + " * @implements {D.<T>} */\n" + "function E() {};\n" + "goog.inherits(E, C);\n" + "/** @override */\n" + "E.prototype.method = function(t) {};\n" + "" + "var e = /** @type {E.<string>} */ (new E());\n" + "e.method(3);", "actual parameter 1 of E.prototype.method does not match formal " + "parameter\n" + "found : number\n" + "required: string"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testSetprop15() throws Exception { // Create static property on struct testTypes( "/** @interface */\n" + "function Peelable() {};\n" + "/** @return {undefined} */\n" + "Peelable.prototype.peel;\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Fruit() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Fruit}\n" + " * @implements {Peelable}\n" + " */\n" + "function Banana() { };\n" + "function f() {};\n" + "/** @override */\n" + "Banana.prototype.peel = f;"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar())['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = unknown;" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = unknown;" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = unknown;" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testNamespaceType1() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @param {x.} y */ function f(y) {};", "Parse error. Namespaces not supported yet (x.)"); } public void testNamespaceType2() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @namespace */ x.y = {};" + "/** @param {x.y.} y */ function f(y) {}", "Parse error. Namespaces not supported yet (x.y.)"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } public void testIssue1023() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "(function () {" + " F.prototype = {" + " /** @param {string} x */" + " bar: function (x) { }" + " };" + "})();" + "(new F()).bar(true)", "actual parameter 1 of F.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testIssue1047() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " */\n" + "function C2() {}\n" + "\n" + "/**\n" + " * @constructor\n" + " */\n" + "function C3(c2) {\n" + " /**\n" + " * @type {C2} \n" + " * @private\n" + " */\n" + " this.c2_;\n" + "\n" + " var x = this.c2_.prop;\n" + "}", "Property prop never defined on C2"); } public void testIssue1056() throws Exception { testTypes( "/** @type {Array} */ var x = null;" + "x.push('hi');", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testIssue1072() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @return {number}\n" + " */\n" + "var f1 = function (x) {\n" + " return 3;\n" + "};\n" + "\n" + "/** Function */\n" + "var f2 = function (x) {\n" + " if (!x) throw new Error()\n" + " return /** @type {number} */ (f1('x'))\n" + "}\n" + "\n" + "/**\n" + " * @param {string} x\n" + " */\n" + "var f3 = function (x) {};\n" + "\n" + "f1(f3);", "actual parameter 1 of f1 does not match formal parameter\n" + "found : function (string): undefined\n" + "required: string"); } public void testEnums() throws Exception { testTypes( "var outer = function() {" + " /** @enum {number} */" + " var Level = {" + " NONE: 0," + " };" + " /** @type {!Level} */" + " var l = Level.NONE;" + "}"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testUnnecessaryCastToSuperType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Base}\n" + " */\n" + "function Derived() {}\n" + "var d = new Derived();\n" + "var b = /** @type {!Base} */ (d);", "unnecessary cast\n" + "from: Derived\n" + "to : Base" ); } public void testUnnecessaryCastToSameType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var b = new Base();\n" + "var c = /** @type {!Base} */ (b);", "unnecessary cast\n" + "from: Base\n" + "to : Base" ); } /** * Checks that casts to unknown ({?}) are not marked as unnecessary. */ public void testUnnecessaryCastToUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var b = new Base();\n" + "var c = /** @type {?} */ (b);"); } /** * Checks that casts from unknown ({?}) are not marked as unnecessary. */ public void testUnnecessaryCastFromUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "/** @type {?} */ var x;\n" + "var y = /** @type {Base} */ (x);"); } public void testUnnecessaryCastToAndFromUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */ function A() {}\n" + "/** @constructor */ function B() {}\n" + "/** @type {!Array.<!A>} */ var x = " + "/** @type {!Array.<?>} */( /** @type {!Array.<!B>} */([]) );"); } /** * Checks that a cast from {?Base} to {!Base} is not considered unnecessary. */ public void testUnnecessaryCastToNonNullType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var c = /** @type {!Base} */ (random ? new Base() : null);" ); } public void testUnnecessaryCastToStar() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var c = /** @type {*} */ (new Base());", "unnecessary cast\n" + "from: Base\n" + "to : *" ); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType15() throws Exception { testTypes( "/**" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType16() throws Exception { testTypes( "/** @constructor */ function C() {\n" + " /** @type {number} */ this.foo = 1\n" + "}\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn(new C());", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType17() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn(new C());", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType18() throws Exception { // Until template types can be restricted to exclude undefined, they // are always optional. testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({});"); } public void testTemplateType19() throws Exception { testTypes( "/**\n" + " * @param {T} t\n" + " * @param {U} u\n" + " * @return {{t:T, u:U}} \n" + " * @template T,U\n" + " */\n" + "function fn(t, u) { return {t:t, u:u}; }\n" + "/** @type {null} */ var x = fn(1, 'str');", "initializing variable\n" + "found : {t: number, u: string}\n" + "required: null"); } public void testTemplateTypeWithUnresolvedType() throws Exception { testClosureTypes( "var goog = {};\n" + "goog.addDependency = function(a,b,c){};\n" + "goog.addDependency('a.js', ['Color'], []);\n" + "/** @interface @template T */ function C() {}\n" + "/** @return {!Color} */ C.prototype.method;\n" + "/** @constructor @implements {C} */ function D() {}\n" + "/** @override */ D.prototype.method = function() {};", null); // no warning expected. } public void testTemplateTypeWithTypeDef1a() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "" + "/** @type {Generic.<!Foo>} */ var x;\n" + "/** @type {Generic.<!Bar>} */ var y;\n" + "" + "x = y;\n" + // no warning "/** @type null */ var z1 = y;\n" + "", "initializing variable\n" + "found : (Generic.<Foo>|null)\n" + "required: null"); } public void testTemplateTypeWithTypeDef1b() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "" + "/** @type {Generic.<!Foo>} */ var x;\n" + "/** @type {Generic.<!Bar>} */ var y;\n" + "" + "y = x;\n" + // no warning. "/** @type null */ var z1 = x;\n" + "", "initializing variable\n" + "found : (Generic.<Foo>|null)\n" + "required: null"); } public void testTemplateTypeWithTypeDef2a() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Bar> */ x) {}\n" + "/** @type {Generic.<!Foo>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2b() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Bar> */ x) {}\n" + "/** @type {Generic.<!Bar>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2c() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Foo> */ x) {}\n" + "/** @type {Generic.<!Foo>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2d() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Foo> */ x) {}\n" + "/** @type {Generic.<!Bar>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeRecursion1() throws Exception { testTypes( "/** @typedef {{a: D2}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void testTemplateTypeRecursion2() throws Exception { testTypes( "/** @typedef {{a: D2}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "/** @type {D1} */ var x;" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void testTemplateTypeRecursion3() throws Exception { testTypes( "/** @typedef {{a: function(D2)}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "/** @type {D1} */ var x;" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testTemplatized6() throws Exception { testTypes( "/** @interface */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "" + "/** @constructor \n" + " * @implements {I}\n" + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "" + "/** @type {null} */ var some = new C().method('str');", "initializing variable\n" + "found : string\n" + "required: null"); } public void testTemplatized7() throws Exception { testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @implements {I.<number>}\n" + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {null} */ var some = new C().method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void disable_testTemplatized8() throws Exception { // TODO(johnlenz): this should generate a warning but does not. testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @implements {I.<R>}\n" + " * @template R\n " + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {C.<number>} var x = new C();" + "/** @type {null} */ var some = x.method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void testTemplatized9() throws Exception { testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @param {R} a\n" + " * @implements {I.<R>}\n" + " * @template R\n " + " */ function C(a){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {null} */ var some = new C(1).method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void testTemplatized10() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " */\n" + "function Parent() {};\n" + "\n" + "/** @param {T} x */\n" + "Parent.prototype.method = function(x) {};\n" + "\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent.<string>}\n" + " */\n" + "function Child() {};\n" + "Child.prototype = new Parent();\n" + "\n" + "(new Child()).method(123); \n", "actual parameter 1 of Parent.prototype.method does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTemplatized11() throws Exception { testTypes( "/** \n" + " * @template T\n" + " * @constructor\n" + " */\n" + "function C() {}\n" + "\n" + "/**\n" + " * @param {T|K} a\n" + " * @return {T}\n" + " * @template K\n" + " */\n" + "C.prototype.method = function (a) {};\n" + "\n" + // method returns "?" "/** @type {void} */ var x = new C().method(1);"); } public void testIssue1058() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template CLASS\n" + " */\n" + "var Class = function() {};\n" + "\n" + "/**\n" + " * @param {function(CLASS):CLASS} a\n" + " * @template T\n" + " */\n" + "Class.prototype.foo = function(a) {\n" + " return 'string';\n" + "};\n" + "\n" + "/** @param {number} a\n" + " * @return {string} */\n" + "var a = function(a) { return '' };\n" + "\n" + "new Class().foo(a);"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};" + "" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {A}\n" + " */\n" + "var B = function() { this.bar = function(){}; };" + "" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype2() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " this.x = 123;\n" + "}\n" + "var objlit = /** @struct */ { y: 234 };\n" + "Foo.prototype = objlit;\n" + "var n = objlit.x;\n", "Property x never defined on Foo.prototype", false); } public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, false) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testIssue1056` for the issue `Closure-1056`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1056 // // ## Issue-Title: // initial type of variable wrong when initialize in a "var" statement with type declaration. // // ## Issue-Description: // The following code doesn't give any warning even though it is an obvious bug: // // -------------===============================--------- // /\*\* // \* @constructor // \*/ // function MyClass() { // this.value = 1; // } // // MyClass.prototype.show = function() { // window.console.log(this.value) // } // // /\*\* // \* @type {MyClass} // \*/ // var x = null; // x.show(); // -------------===============================--------- // // However, if you remove the @type from the var declaration, then closure realizes the problem and warns about x being null rather than an Object. // // In any case, since x "can be null", closure should warn about a potential null pointer error, and suggest to guard against the null value, like it does if we try to pass x as an argument where a non-null type is expected. That could be an optional behavior protected behind a flag, but it would definitely help catch lots of errors and write safer code. // // I am using the latest closure version available to date, on Ubuntu 13.04, on an amd64 machine. // // public void testIssue1056() throws Exception {
6,916
176
6,909
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-1056 ## Issue-Title: initial type of variable wrong when initialize in a "var" statement with type declaration. ## Issue-Description: The following code doesn't give any warning even though it is an obvious bug: -------------===============================--------- /\*\* \* @constructor \*/ function MyClass() { this.value = 1; } MyClass.prototype.show = function() { window.console.log(this.value) } /\*\* \* @type {MyClass} \*/ var x = null; x.show(); -------------===============================--------- However, if you remove the @type from the var declaration, then closure realizes the problem and warns about x being null rather than an Object. In any case, since x "can be null", closure should warn about a potential null pointer error, and suggest to guard against the null value, like it does if we try to pass x as an argument where a non-null type is expected. That could be an optional behavior protected behind a flag, but it would definitely help catch lots of errors and write safer code. I am using the latest closure version available to date, on Ubuntu 13.04, on an amd64 machine. ``` You are a professional Java test case writer, please create a test case named `testIssue1056` for the issue `Closure-1056`, utilizing the provided issue report information and the following function signature. ```java public void testIssue1056() throws Exception { ```
6,909
[ "com.google.javascript.jscomp.TypeInference" ]
fc74772c2f52a07443dfc60ebedeeddbba5dcee59e5eac8e6b9e9e5a9feaa6f9
public void testIssue1056() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue1056` for the issue `Closure-1056`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1056 // // ## Issue-Title: // initial type of variable wrong when initialize in a "var" statement with type declaration. // // ## Issue-Description: // The following code doesn't give any warning even though it is an obvious bug: // // -------------===============================--------- // /\*\* // \* @constructor // \*/ // function MyClass() { // this.value = 1; // } // // MyClass.prototype.show = function() { // window.console.log(this.value) // } // // /\*\* // \* @type {MyClass} // \*/ // var x = null; // x.show(); // -------------===============================--------- // // However, if you remove the @type from the var declaration, then closure realizes the problem and warns about x being null rather than an Object. // // In any case, since x "can be null", closure should warn about a potential null pointer error, and suggest to guard against the null value, like it does if we try to pass x as an argument where a non-null type is expected. That could be an optional behavior protected behind a flag, but it would definitely help catch lots of errors and write safer code. // // I am using the latest closure version available to date, on Ubuntu 13.04, on an amd64 machine. // //
Closure
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import com.google.javascript.rhino.testing.Asserts; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Tests {@link TypeCheck}. * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; private static final String SUGGESTION_CLASS = "/** @constructor\n */\n" + "function Suggest() {}\n" + "Suggest.prototype.a = 1;\n" + "Suggest.prototype.veryPossible = 1;\n" + "Suggest.prototype.veryPossible2 = 1;\n"; @Override public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).createInitialScope( new Node(Token.BLOCK)); assertTypeEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertTypeEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertTypeEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertTypeEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertTypeEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertTypeEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertTypeEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertTypeEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertTypeEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertTypeEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertTypeEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertTypeEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertTypeEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testPrivateType() throws Exception { testTypes( "/** @private {number} */ var x = false;", "initializing variable\n" + "found : boolean\n" + "required: number"); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo(); x--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheck25() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({b: 'abc'});", "actual parameter 1 of foo does not match formal parameter\n" + "found : {a: (number|undefined), b: string}\n" + "required: {a: number}"); } public void testTypeCheck26() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({a: 'abc'});", "actual parameter 1 of foo does not match formal parameter\n" + "found : {a: (number|string)}\n" + "required: {a: number}"); } public void testTypeCheck27() throws Exception { testTypes("function foo(/** {a: number} */ obj) {};" + "foo({a: 123});"); } public void testTypeCheck28() throws Exception { testTypes("function foo(/** ? */ obj) {};" + "foo({a: 123});"); } public void testTypeCheckInlineReturns() throws Exception { testTypes( "function /** string */ foo(x) { return x; }" + "var /** number */ a = foo('abc');", "initializing variable\n" + "found : string\n" + "required: number"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testTypeCheckCustomExterns2() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @enum {string} */ var Enum = {FOO: 1, BAR: 1};", "/** @param {Enum} x */ function f(x) {} f(Enum.FOO); f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: Enum.<string>", false); } public void testTemplatizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array.<number>\n" + "required: number"); } public void testTemplatizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testTemplatizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testTemplatizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testTemplatizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testTemplatizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testTemplatizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testTemplatizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testTemplatizedObject5() throws Exception { testTypes("/** @constructor */ function F() {" + " /** @type {Object.<number, string>} */ this.numbers = {};" + "}" + "(new F()).numbers['ten'] = '10';", "restricted index type\n" + "found : string\n" + "required: number"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Bad type annotation. variable length argument must be last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }", "condition always evaluates to false\n" + "left : Function\n" + "right: string"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?|boolean} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(x) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction16() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @interface */ function I() {}\n" + "/**\n" + " * @param {*} x\n" + " * @return {I}\n" + " */\n" + "function f(x) { " + " if(goog.isObject(x)) {" + " return /** @type {I} */(x);" + " }" + " return null;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testQualifiedNameReduction5a() throws Exception { testTypes("var x = {/** @type {string} */ a:'b' };\n" + "/** @return {string} */ var f = function() {\n" + "return x.a; }"); } public void testQualifiedNameReduction5b() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "/** @return {string} */\n" + "var f = function() {\n" + " return x.a;\n" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction5c() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @type {number} */ a:0 };\n" + "return (x.a) ? (x.a) : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testQualifiedNameReduction6() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {string?} */ get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction7() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {/** @return {number} */ get a() {return 12}};\n" + "return x.a; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testQualifiedNameReduction7a() throws Exception { // It would be nice to find a way to make this an error. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 12}};\n" + "return x.a; }"); } public void testQualifiedNameReduction8() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = {get a() {return 'a'}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction9() throws Exception { testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {string} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction10() throws Exception { // TODO(johnlenz): separate setter property types from getter property // types. testTypes( "/** @return {string} */ var f = function() {\n" + "var x = { /** @param {number} b */ set a(b) {}};\n" + "return x.a ? x.a : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjLitDef1a() throws Exception { testTypes( "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef1b() throws Exception { testTypes( "function f(){" + "var x = {/** @type {number} */ a:12 };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2a() throws Exception { testTypes( "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef2b() throws Exception { testTypes( "function f(){" + "var x = {/** @param {number} b */ set a(b){} };\n" + "x.a = 'a';" + "};\n" + "f();", "assignment to property a of x\n" + "found : string\n" + "required: number"); } public void testObjLitDef3a() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef3b() throws Exception { testTypes( "/** @type {string} */ var y;\n" + "function f(){" + "var x = {/** @return {number} */ get a(){} };\n" + "y = x.a;" + "};\n" + "f();", "assignment\n" + "found : number\n" + "required: string"); } public void testObjLitDef4() throws Exception { testTypes( "var x = {" + "/** @return {number} */ a:12 };\n", "assignment to property a of {a: function (): number}\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef5() throws Exception { testTypes( "var x = {};\n" + "/** @return {number} */ x.a = 12;\n", "assignment to property a of x\n" + "found : number\n" + "required: function (): number"); } public void testObjLitDef6() throws Exception { testTypes("var lit = /** @struct */ { 'x': 1 };", "Illegal key, the object literal is a struct"); } public void testObjLitDef7() throws Exception { testTypes("var lit = /** @dict */ { x: 1 };", "Illegal key, the object literal is a dict"); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testUndeclaredGlobalProperty1() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f(a) { x.y = a; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }"); } public void testUndeclaredGlobalProperty2() throws Exception { testTypes("/** @const */ var x = {}; x.y = null;" + "function f() { x.y = 3; }" + "/** @param {string} a */ function g(a) { }" + "function h() { g(x.y); }", "actual parameter 1 of g does not match formal parameter\n" + "found : (null|number)\n" + "required: string"); } public void testLocallyInferredGlobalProperty1() throws Exception { // We used to have a bug where x.y.z leaked from f into h. testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.z;" + "/** @const */ var x = {}; /** @type {F} */ x.y;" + "function f() { x.y.z = 'abc'; }" + "/** @param {number} x */ function g(x) {}" + "function h() { g(x.y.z); }", "assignment to property z of F\n" + "found : string\n" + "required: number"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testPropertyInference9() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = null;", "assignment\n" + "found : null\n" + "required: number"); } public void testPropertyInference10() throws Exception { // NOTE(nicksantos): There used to be a bug where a property // on the prototype of one structural function would leak onto // the prototype of other variables with the same structural // function type. testTypes( "/** @constructor */ function A() {}" + "/** @return {function(): ?} */ function f() { " + " return function() {};" + "}" + "var g = f();" + "/** @type {number} */ g.prototype.bar_ = 1;" + "var h = f();" + "/** @type {string} */ h.prototype.bar_ = 1;", "assignment\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = unknown;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = unknown;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = unknown;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return {void} */ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return {void} */ " + "function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is OK since the type of b is ? testTypes( "/** @return {number} */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testScoping12() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {number} */ F.prototype.bar = 3;" + "/** @param {!F} f */ function g(f) {" + " /** @return {string} */" + " function h() {" + " return f.bar;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return {string} */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(opt_a) {}", "function (number=): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return {string} */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return {string} */" + "function f(a,opt_a) {}", "function (?, number=): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have non-inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return {?boolean} */" + "function f(b) { if (u()) { b = null; } return b; }", "assignment\n" + "found : null\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionArguments17() throws Exception { testClosureTypesMultipleWarnings( "/** @param {booool|string} x */" + "function f(x) { g(x) }" + "/** @param {number} x */" + "function g(x) {}", Lists.newArrayList( "Bad type annotation. Unknown type booool", "actual parameter 1 of g does not match formal parameter\n" + "found : (booool|null|string)\n" + "required: number")); } public void testFunctionArguments18() throws Exception { testTypes( "function f(x) {}" + "f(/** @param {number} y */ (function() {}));", "parameter y does not appear in <anonymous>'s parameter list"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return {string} */function f(opt_a) {}", "function (this:Date, ?=): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return {string} */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return {number}*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testFunctionInference21() throws Exception { testTypes( "var f = function() { throw 'x' };" + "/** @return {boolean} */ var g = f;"); testFunctionType( "var f = function() { throw 'x' };", "f", "function (): ?"); } public void testFunctionInference22() throws Exception { testTypes( "/** @type {!Function} */ var f = function() { g(this); };" + "/** @param {boolean} x */ var g = function(x) {};"); } public void testFunctionInference23() throws Exception { // We want to make sure that 'prop' isn't declared on all objects. testTypes( "/** @type {!Function} */ var f = function() {\n" + " /** @type {number} */ this.prop = 3;\n" + "};" + "/**\n" + " * @param {Object} x\n" + " * @return {string}\n" + " */ var g = function(x) { return x.prop; };"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testInnerFunction10() throws Exception { testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {string} */" + " function g() {" + " if (!x) {" + " x = 1;" + " }" + " return x;" + " }" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInnerFunction11() throws Exception { // TODO(nicksantos): This is actually bad inference, because // h sets x to null. We should fix this, but for now we do it // this way so that we don't break existing binaries. We will // need to change TypeInference#isUnflowable to fix this. testTypes( "function f() {" + " /** @type {?number} */ var x = null;" + " /** @return {number} */" + " function g() {" + " x = 1;" + " h();" + " return x;" + " }" + " function h() {" + " x = null;" + " }" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {!Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);"); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };", "mismatch of the foo property type and the type of the property " + "it overrides from superclass F\n" + "original: function (this:F): undefined\n" + "override: function (this:G, ?, ?): undefined"); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(opt_b, var_args) { };" + "(new G()).foo(1, 2, 3);"); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 " + "with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticMethodDecl6() throws Exception { // Make sure the CAST node doesn't interfere with the @suppress // annotation. testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/**\n" + " * @suppress {duplicate}\n" + " * @return {undefined}\n" + " */\n" + "goog.foo = " + " /** @type {!Function} */ (function(x) {});"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl5() throws Exception { testClosureTypesMultipleWarnings( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", Lists.newArrayList( "assignment to property foo of goog\n" + "found : string\n" + "required: Foo", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo")); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateStaticPropertyDec20() throws Exception { testTypes( "/**\n" + " * @fileoverview\n" + " * @suppress {duplicate}\n" + " */" + "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string} */ goog.foo = 'x';"); } public void testDuplicateLocalVarDecl() throws Exception { testClosureTypesMultipleWarnings( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", Lists.newArrayList( "variable x redefined with type string, original definition" + " at [testcode]:2 with type number", "initializing variable\n" + "found : string\n" + "required: number")); } public void testDuplicateInstanceMethod1() throws Exception { // If there's no jsdoc on the methods, then we treat them like // any other inferred properties. testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "/** jsdoc */ F.prototype.bar = function() {};", "variable F.prototype.bar redefined with type " + "function (this:F): undefined, original definition at " + "[testcode]:1 with type function (this:F): undefined"); } public void testDuplicateInstanceMethod4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc */ F.prototype.bar = function() {};" + "F.prototype.bar = function() {};"); } public void testDuplicateInstanceMethod5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testDuplicateInstanceMethod6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** jsdoc \n * @return {number} */ F.prototype.bar = function() {" + " return 3;" + "};" + "/** jsdoc \n * @return {string} * \n @suppress {duplicate} */ " + "F.prototype.bar = function() { return ''; };", "assignment to property bar of F.prototype\n" + "found : function (this:F): string\n" + "required: function (this:F): number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testExternFunctionType( // externs "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (new:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } /** * Tests the type of a function definition in externs. * The function defined by {@code functionDef} should be * named {@code functionName}. */ private void testExternFunctionType(String functionDef, String functionName, String functionType) throws Exception { testTypes( functionDef, "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number", false); } public void testTypeRedefinition() throws Exception { testClosureTypesMultipleWarnings("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", Lists.newArrayList( "variable a.A redefined with type function (new:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}", "assignment to property A of a\n" + "found : function (new:a.A): undefined\n" + "required: enum{a.A}")); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (new:Date, ?=, ?=, ?=, ?=, ?=, ?=, ?=): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testForIn1() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "for (var k in {}) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } public void testForIn2() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, string>} */ var obj = {};" + "var k = null;" + "for (k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : E.<string>\n" + "required: boolean"); } public void testForIn3() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @type {Object.<number>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testForIn4() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @enum {string} */ var E = {FOO: 'bar'};" + "/** @type {Object.<E, Array>} */ var obj = {};" + "for (var k in obj) {" + " f(obj[k]);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : (Array|null)\n" + "required: boolean"); } public void testForIn5() throws Exception { testTypes( "/** @param {boolean} x */ function f(x) {}" + "/** @constructor */ var E = function(){};" + "/** @type {Object.<E, number>} */ var obj = {};" + "for (var k in obj) {" + " f(k);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: boolean"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to true\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testComparison11() throws Exception { testTypes( "(function(){}) == 'x'", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: string"); } public void testComparison12() throws Exception { testTypes( "(function(){}) == 3", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: number"); } public void testComparison13() throws Exception { testTypes( "(function(){}) == false", "condition always evaluates to false\n" + "left : function (): undefined\n" + "right: boolean"); } public void testComparison14() throws Exception { testTypes("/** @type {function((Array|string), Object): number} */" + "function f(x, y) { return x === y; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testComparison15() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @constructor */ function F() {}" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {F}\n" + " */\n" + "function G(x) {}\n" + "goog.inherits(G, F);\n" + "/**\n" + " * @param {number} x\n" + " * @constructor\n" + " * @extends {G}\n" + " */\n" + "function H(x) {}\n" + "goog.inherits(H, G);\n" + "/** @param {G} x */" + "function f(x) { return x.constructor === H; }", null); } public void testDeleteOperator1() throws Exception { testTypes( "var x = {};" + "/** @return {string} */ function f() { return delete x['a']; }", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testDeleteOperator2() throws Exception { testTypes( "var obj = {};" + "/** \n" + " * @param {string} x\n" + " * @return {Object} */ function f(x) { return obj; }" + "/** @param {?number} x */ function g(x) {" + " if (x) { delete f(x)['a']; }" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "variable a.BB redefined with type a.<number>, " + "original definition at [testcode]:1 with type a.<number>"); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "assignment to property BB of enum{a}\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testClosureTypesMultipleWarnings("/** @enum */var a=8;", Lists.newArrayList( "enum initializer must be an object literal or an enum", "initializing variable\n" + "found : number\n" + "required: enum{a}")); } public void testEnum9() throws Exception { testClosureTypesMultipleWarnings( "var goog = {};" + "/** @enum */goog.a=8;", Lists.newArrayList( "assignment to property a of goog\n" + "found : number\n" + "required: enum{goog.a}", "enum initializer must be an object literal or an enum")); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog .a={BB:1,BB:2}", "variable goog.a.BB redefined with type goog.a.<number>, " + "original definition at [testcode]:1 with type goog.a.<number>"); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "assignment to property BB of enum{goog.a}\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum41() throws Exception { testTypes( "/** @enum {number} */ var MyEnum = {/** @const */ FOO: 1};" + "/** @return {string} */" + "function f() { return MyEnum.FOO; }", "inconsistent return type\n" + "found : MyEnum.<number>\n" + "required: string"); } public void testEnum42() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @enum {Object} */ var MyEnum = {FOO: {newProperty: 1, b: 2}};" + "f(MyEnum.FOO.newProperty);"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsTypedefUse2() throws Exception { testTypes( "/** @this {MyTypedef} */ function f() {}" + "/** @typedef {!(Date|Array)} */ var MyTypedef;"); } public void testBackwardsTypedefUse4() throws Exception { testTypes( "/** @return {MyTypedef} */ function f() { return null; }" + "/** @typedef {string} */ var MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse6() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {string} */ goog.MyTypedef;", "inconsistent return type\n" + "found : null\n" + "required: string"); } public void testBackwardsTypedefUse7() throws Exception { testTypes( "/** @return {goog.MyTypedef} */ function f() { return null; }" + "var goog = {};" + "/** @typedef {Object} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse8() throws Exception { // Technically, this isn't quite right, because the JS runtime // will coerce null -> the global object. But we'll punt on that for now. testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"); } public void testBackwardsTypedefUse9() throws Exception { testTypes( "/** @param {!Array} x */ function g(x) {}" + "/** @this {goog.MyTypedef} */ function f() { g(this); }" + "var goog = {};" + "/** @typedef {(Error|null|undefined)} */ goog.MyTypedef;", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: Array"); } public void testBackwardsTypedefUse10() throws Exception { testTypes( "/** @param {goog.MyEnum} x */ function g(x) {}" + "var goog = {};" + "/** @enum {goog.MyTypedef} */ goog.MyEnum = {FOO: 1};" + "/** @typedef {number} */ goog.MyTypedef;" + "g(1);", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: goog.MyEnum.<number>"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (new:derived, ...[?]): ?"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testGoodExtends12() throws Exception { testTypes( "/** @constructor \n * @extends {Super} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @constructor */ function Super() {}" + "/** @param {Super} x */ function foo(x) {}" + "foo(new Sub2());"); } public void testGoodExtends13() throws Exception { testTypes( "/** @constructor \n * @extends {B} */ function C() {}" + "/** @constructor \n * @extends {D} */ function E() {}" + "/** @constructor \n * @extends {C} */ function D() {}" + "/** @constructor \n * @extends {A} */ function B() {}" + "/** @constructor */ function A() {}" + "/** @param {number} x */ function f(x) {} f(new E());", "actual parameter 1 of f does not match formal parameter\n" + "found : E\n" + "required: number"); } public void testGoodExtends14() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(NewType, f);" + " (new NewType());" + "}"); } public void testGoodExtends15() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function OldType() {}" + "/** @param {?function(new:OldType)} f */ function g(f) {" + " /**\n" + " * @constructor\n" + " * @extends {OldType}\n" + " */\n" + " function NewType() {};" + " goog.inherits(NewType, f);" + " NewType.prototype.method = function() {" + " NewType.superClass_.foo.call(this);" + " };" + "}", "Property foo never defined on OldType.prototype"); } public void testGoodExtends16() throws Exception { testTypes( CLOSURE_DEFS + "/** @param {Function} f */ function g(f) {" + " /** @constructor */ function NewType() {};" + " goog.inherits(f, NewType);" + " (new NewType());" + "}"); } public void testGoodExtends17() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @param {number} x */ base.prototype.bar = function(x) {};\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor.prototype.bar", "function (this:base, number): undefined"); } public void testGoodExtends18() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor\n" + " * @template T */\n" + "function C() {}\n" + "/** @constructor\n" + " * @extends {C.<string>} */\n" + "function D() {};\n" + "goog.inherits(D, C);\n" + "(new D())"); } public void testGoodExtends19() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */\n" + "function C() {}\n" + "" + "/** @interface\n" + " * @template T */\n" + "function D() {}\n" + "/** @param {T} t */\n" + "D.prototype.method;\n" + "" + "/** @constructor\n" + " * @template T\n" + " * @extends {C}\n" + " * @implements {D.<T>} */\n" + "function E() {};\n" + "goog.inherits(E, C);\n" + "/** @override */\n" + "E.prototype.method = function(t) {};\n" + "" + "var e = /** @type {E.<string>} */ (new E());\n" + "e.method(3);", "actual parameter 1 of E.prototype.method does not match formal " + "parameter\n" + "found : number\n" + "required: string"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Bad type annotation. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testBadExtends4() throws Exception { // If there's a subclass of a class with a bad extends, // we only want to warn about the first one. testTypes( "/** @constructor \n * @extends {bad} */ function Sub() {}" + "/** @constructor \n * @extends {Sub} */ function Sub2() {}" + "/** @param {Sub} x */ function foo(x) {}" + "foo(new Sub2());", "Bad type annotation. Unknown type bad"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testDirectPrototypeAssignment3() throws Exception { // This verifies that the compiler doesn't crash if the user // overwrites the prototype of a global variable in a local scope. testTypes( "/** @constructor */ var MainWidgetCreator = function() {};" + "/** @param {Function} ctor */" + "function createMainWidget(ctor) {" + " /** @constructor */ function tempCtor() {};" + " tempCtor.prototype = ctor.prototype;" + " MainWidgetCreator.superClass_ = ctor.prototype;" + " MainWidgetCreator.prototype = new tempCtor();" + "}"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @constructor \n @implements {Disposable} */function f() {}"); } public void testGoodImplements4() throws Exception { testTypes("var goog = {};" + "/** @type {!Function} */" + "goog.abstractMethod = function() {};" + "/** @interface */\n" + "goog.Disposable = goog.abstractMethod;" + "goog.Disposable.prototype.dispose = goog.abstractMethod;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @inheritDoc */ " + "goog.SubDisposable.prototype.dispose = function() {};"); } public void testGoodImplements5() throws Exception { testTypes( "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @type {Function} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @param {number} key \n @override */ " + "goog.SubDisposable.prototype.dispose = function(key) {};"); } public void testGoodImplements6() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = myNullFunction;" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testGoodImplements7() throws Exception { testTypes( "var myNullFunction = function() {};" + "/** @interface */\n" + "goog.Disposable = function() {};" + "/** @return {number} */" + "goog.Disposable.prototype.dispose = function() {};" + "/** @implements {goog.Disposable}\n * @constructor */" + "goog.SubDisposable = function() {};" + "/** @return {number} \n @override */ " + "goog.SubDisposable.prototype.dispose = function() { return 0; };"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor for f"); } public void testBadImplements3() throws Exception { testTypes( "var goog = {};" + "/** @type {!Function} */ goog.abstractMethod = function(){};" + "/** @interface */ var Disposable = goog.abstractMethod;" + "Disposable.prototype.method = goog.abstractMethod;" + "/** @implements {Disposable}\n * @constructor */function f() {}", "property method on interface Disposable is not implemented by type f"); } public void testBadImplements4() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}", "f cannot implement this type; an interface can only extend, " + "but not implement interfaces"); } public void testBadImplements5() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @type {number} */ Disposable.prototype.bar = function() {};", "assignment to property bar of Disposable.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testBadImplements6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */function Disposable() {}\n" + "/** @type {function()} */ Disposable.prototype.bar = 3;", Lists.newArrayList( "assignment to property bar of Disposable.prototype\n" + "found : number\n" + "required: function (): ?", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testConstructorClassTemplate() throws Exception { testTypes("/** @constructor \n @template S,T */ function A() {}\n"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Bad type annotation. Unknown type nonExistent"); } public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { String js = "/** @interface \n" + " * @extends {nonExistent1} \n" + " * @extends {nonExistent2} \n" + " */function A() {}"; String[] expectedWarnings = { "Bad type annotation. Unknown type nonExistent1", "Bad type annotation. Unknown type nonExistent2" }; testTypes(js, expectedWarnings); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; interfaces can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; constructors can only extend constructors"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testBadImplementsDuplicateInterface1() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<?>}\n" + " * @implements {Foo}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testBadImplementsDuplicateInterface2() throws Exception { // verify that the same base (not templatized) interface cannot be // @implemented more than once. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " * @implements {Foo.<number>}\n" + " */\n" + "function A() {}\n", "Cannot @implement the same interface more than once\n" + "Repeated interface: Foo"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;\n" + "new Object().prototype = i.prototype;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testGetprop2() throws Exception { testTypes("var x = null; x.alert();", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testGetprop3() throws Exception { testTypes( "/** @constructor */ " + "function Foo() { /** @type {?Object} */ this.x = null; }" + "Foo.prototype.initX = function() { this.x = {foo: 1}; };" + "Foo.prototype.bar = function() {" + " if (this.x == null) { this.initX(); alert(this.x.foo); }" + "};"); } public void testGetprop4() throws Exception { testTypes("var x = null; x.prop = 3;", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testSetprop1() throws Exception { // Create property on struct in the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }"); } public void testSetprop2() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop3() throws Exception { // Create property on struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(function() { (new Foo()).x = 123; })();", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop4() throws Exception { // Assign to existing property of struct outside the constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() { this.x = 123; }\n" + "(new Foo()).x = \"asdf\";"); } public void testSetprop5() throws Exception { // Create a property on union that includes a struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(true ? new Foo() : {}).x = 123;", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop6() throws Exception { // Create property on struct in another constructor testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/**\n" + " * @constructor\n" + " * @param{Foo} f\n" + " */\n" + "function Bar(f) { f.x = 123; }", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop7() throws Exception { //Bug b/c we require THIS when creating properties on structs for simplicity testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " var t = this;\n" + " t.x = 123;\n" + "}", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop8() throws Exception { // Create property on struct using DEC testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x--;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop9() throws Exception { // Create property on struct using ASSIGN_ADD testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "(new Foo()).x += 123;", new String[] { "Property x never defined on Foo", "Cannot add a property to a struct instance " + "after it is constructed." }); } public void testSetprop10() throws Exception { // Create property on object literal that is a struct testTypes("/** \n" + " * @constructor \n" + " * @struct \n" + " */ \n" + "function Square(side) { \n" + " this.side = side; \n" + "} \n" + "Square.prototype = /** @struct */ {\n" + " area: function() { return this.side * this.side; }\n" + "};\n" + "Square.prototype.id = function(x) { return x; };"); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;"); } public void testSetprop12() throws Exception { // Create property on a constructor of structs (which isn't itself a struct) testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "Foo.someprop = 123;"); } public void testSetprop13() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Parent() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent}\n" + " */\n" + "function Kid() {}\n" + "Kid.prototype.foo = 123;\n" + "var x = (new Kid()).foo;"); } public void testSetprop14() throws Exception { // Create static property on struct testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Top() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Top}\n" + " */\n" + "function Mid() {}\n" + "/** blah blah */\n" + "Mid.prototype.foo = function() { return 1; };\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {Mid}\n" + " */\n" + "function Bottom() {}\n" + "/** @override */\n" + "Bottom.prototype.foo = function() { return 3; };"); } public void testSetprop15() throws Exception { // Create static property on struct testTypes( "/** @interface */\n" + "function Peelable() {};\n" + "/** @return {undefined} */\n" + "Peelable.prototype.peel;\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Fruit() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Fruit}\n" + " * @implements {Peelable}\n" + " */\n" + "function Banana() { };\n" + "function f() {};\n" + "/** @override */\n" + "Banana.prototype.peel = f;"); } public void testGetpropDict1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/** @param{Dict1} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Dict1}\n" + " */" + "function Dict1kid(){ this['prop'] = 123; }" + "/** @param{Dict1kid} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @constructor */" + "function NonDict() { this.prop = 321; }" + "/** @param{(NonDict|Dict1)} x */" + "function takesDict(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x.prop; }", "Cannot do '.' access on a dict"); } public void testGetpropDict5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1(){ this.prop = 123; }", "Cannot do '.' access on a dict"); } public void testGetpropDict6() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @dict\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot do '.' access on a dict"); } public void testGetpropDict7() throws Exception { testTypes("(/** @dict */ {'x': 123}).x = 321;", "Cannot do '.' access on a dict"); } public void testGetelemStruct1() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/** @param{Struct1} x */" + "function takesStruct(x) {" + " var z = x;" + " return z['prop'];" + "}", "Cannot do '[]' access on a struct"); } public void testGetelemStruct2() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}" + " */" + "function Struct1kid(){ this.prop = 123; }" + "/** @param{Struct1kid} x */" + "function takesStruct2(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct3() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1(){ this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @extends {Struct1}\n" + " */" + "function Struct1kid(){ this.prop = 123; }" + "var x = (new Struct1kid())['prop'];", "Cannot do '[]' access on a struct"); } public void testGetelemStruct4() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/** @constructor */" + "function NonStruct() { this.prop = 321; }" + "/** @param{(NonStruct|Struct1)} x */" + "function takesStruct(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct5() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Struct1() { this.prop = 123; }" + "/**\n" + " * @constructor\n" + " * @dict\n" + " */" + "function Dict1() { this['prop'] = 123; }" + "/** @param{(Struct1|Dict1)} x */" + "function takesNothing(x) { return x['prop']; }", "Cannot do '[]' access on a struct"); } public void testGetelemStruct6() throws Exception { // By casting Bar to Foo, the illegal bracket access is not detected testTypes("/** @interface */ function Foo(){}\n" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @implements {Foo}\n" + " */" + "function Bar(){ this.x = 123; }\n" + "var z = /** @type {Foo} */(new Bar())['x'];"); } public void testGetelemStruct7() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype['someprop'] = 123;\n", "Cannot do '[]' access on a struct"); } public void testInOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "if ('prop' in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testForinOnStruct() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */" + "function Foo() {}\n" + "for (var prop in (new Foo())) {}", "Cannot use the IN operator with structs"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess9() throws Exception { testTypes("/** @return {?Array} */ function f() { return []; }" + "f()[{}]", "array access\n" + "found : {}\n" + "required: number"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "No properties on this expression\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertTypeEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertTypeEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertTypeEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions5() throws Exception { testTypes( "/** @param {number} x */ function g(x) {}" + "/** @type {function(new:Error,...[number]):Date} */ var f;" + "g(new f());", "actual parameter 1 of g does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ " + "goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ " + "var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return {string} */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam7() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "var bar = /** @type {function(number=,number=)} */ (" + " function(x, y) { f(y); });", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenParams1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...?} var_args */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[?])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};"); } public void testOverriddenParams3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {...number} var_args */" + "Foo.prototype.bar = function(var_args) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenParams4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {function(...[number])} */" + "Foo.prototype.bar = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {function(number)}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (...[number]): ?\n" + "override: function (number): ?"); } public void testOverriddenParams5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar();"); } public void testOverriddenParams6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function() {};" + "(new SubFoo()).bar(true);", "actual parameter 1 of SubFoo.prototype.bar " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testOverriddenParams7() throws Exception { testTypes( "/** @constructor\n * @template T */ function Foo() {}" + "/** @param {T} x */" + "Foo.prototype.bar = function(x) { };" + "/**\n" + " * @constructor\n" + " * @extends {Foo.<string>}\n" + " */ function SubFoo() {}" + "/**\n" + " * @param {number} x\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = function(x) {};", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo, string): undefined\n" + "override: function (this:SubFoo, number): undefined"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testOverriddenReturn3() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testOverriddenReturn4() throws Exception { testTypes( "/** @constructor \n * @template T */ function Foo() {}" + "/** @return {T} */ Foo.prototype.bar = " + " function() { return null; };" + "/** @constructor \n * @extends {Foo.<string>} */ function SubFoo() {}" + "/** @return {number}\n * @override */ SubFoo.prototype.bar = " + " function() { return 3; }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): string\n" + "override: function (this:SubFoo): number"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testOverriddenProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {Object} */" + "Foo.prototype.bar = {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {" + " /** @type {Object} */" + " this.bar = {};" + "}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/**\n" + " * @type {Array}\n" + " * @override\n" + " */" + "SubFoo.prototype.bar = [];"); } public void testOverriddenProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {" + "}" + "/** @type {string} */ Foo.prototype.data;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {string|Object} \n @override */ " + "SubFoo.prototype.data = null;", "mismatch of the data property type and the type " + "of the property it overrides from superclass Foo\n" + "original: string\n" + "override: (Object|null|string)"); } public void testOverriddenProperty4() throws Exception { // These properties aren't declared, so there should be no warning. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty5() throws Exception { // An override should be OK if the superclass property wasn't declared. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @override */ SubFoo.prototype.bar = 3;"); } public void testOverriddenProperty6() throws Exception { // The override keyword shouldn't be neccessary if the subclass property // is inferred. testTypes( "/** @constructor */ function Foo() {}" + "/** @type {?number} */ Foo.prototype.bar = null;" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "SubFoo.prototype.bar = 3;"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return {number} */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return {number}*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return {!Date} */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return {number} */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return {number} */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testThis11() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {" + " /** @this {Date} */" + " this.method = function() {" + " f(this);" + " };" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Date\n" + "required: number"); } public void testThis12() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype['method'] = function() {" + " f(this);" + "}", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis13() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Ctor() {}" + "Ctor.prototype = {" + " method: function() {" + " f(this);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : Ctor\n" + "required: number"); } public void testThis14() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(this.Object);", "actual parameter 1 of f does not match formal parameter\n" + "found : function (new:Object, *=): ?\n" + "required: number"); } public void testThisTypeOfFunction1() throws Exception { testTypes( "/** @type {function(this:Object)} */ function f() {}" + "f();"); } public void testThisTypeOfFunction2() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @type {function(this:F)} */ function f() {}" + "f();", "\"function (this:F): ?\" must be called with a \"this\" type"); } public void testThisTypeOfFunction3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.bar = function() {};" + "var f = (new F()).bar; f();", "\"function (this:F): undefined\" must be called with a \"this\" type"); } public void testThisTypeOfFunction4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.moveTo = function(x, y) {};" + "F.prototype.lineTo = function(x, y) {};" + "function demo() {" + " var path = new F();" + " var points = [[1,1], [2,2]];" + " for (var i = 0; i < points.length; i++) {" + " (i == 0 ? path.moveTo : path.lineTo)(" + " points[i][0], points[i][1]);" + " }" + "}", "\"function (this:F, ?, ?): undefined\" " + "must be called with a \"this\" type"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { // this.alert = 3 doesn't count as a declaration, so this isn't a warning. testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)"); } public void testGlobalThis2b() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "/** @return {number} */ this.alert = function() { return 3; };" + "(new Bindow()).alert(this.alert())", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of global this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on global this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testGlobalThis7() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {Window} msg */ " + "var foo = function(msg) {};" + "foo(this);"); } public void testGlobalThis8() throws Exception { testTypes( "/** @constructor */ function Window() {}" + "/** @param {number} msg */ " + "var foo = function(msg) {};" + "foo(this);", "actual parameter 1 of foo does not match formal parameter\n" + "found : global this\n" + "required: number"); } public void testGlobalThis9() throws Exception { testTypes( // Window is not marked as a constructor, so the // inheritance doesn't happen. "function Window() {}" + "Window.prototype.alert = function() {};" + "this.alert();", "Property alert never defined on global this"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testControlFlowRestrictsType10() throws Exception { // We should correctly infer that y will be (null|{}) because // the loop wraps around. testTypes("/** @param {number} x */ function f(x) {}" + "function g() {" + " var y = null;" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " if (y != null) {" + " // y is None the first time it goes through this branch\n" + " } else {" + " y = {};" + " }" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{})\n" + "required: number"); } public void testControlFlowRestrictsType11() throws Exception { testTypes("/** @param {boolean} x */ function f(x) {}" + "function g() {" + " var y = null;" + " if (y != null) {" + " for (var i = 0; i < 10; i++) {" + " f(y);" + " }" + " }" + "};", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = unknown;" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = unknown;" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = unknown;" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertTypeEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertTypeEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertTypeEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertTypeEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertTypeEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIIFE1() throws Exception { testTypes( "var namespace = {};" + "/** @type {number} */ namespace.prop = 3;" + "(function(ns) {" + " ns.prop = true;" + "})(namespace);", "assignment to property prop of ns\n" + "found : boolean\n" + "required: number"); } public void testIIFE2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @return {number} */ function f() { return Foo.prop; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIIFE3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "(function(ctor) {" + " /** @type {boolean} */ ctor.prop = true;" + "})(Foo);" + "/** @param {number} x */ function f(x) {}" + "f(Foo.prop);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE4() throws Exception { testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " * @param {number} x\n" + " */\n" + " ns.Ctor = function(x) {};" + "})(namespace);" + "new namespace.Ctor(true);", "actual parameter 1 of namespace.Ctor " + "does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIIFE5() throws Exception { // TODO(nicksantos): This behavior is currently incorrect. // To handle this case properly, we'll need to change how we handle // type resolution. testTypes( "/** @const */ var namespace = {};" + "(function(ns) {" + " /**\n" + " * @constructor\n" + " */\n" + " ns.Ctor = function() {};" + " /** @type {boolean} */ ns.Ctor.prototype.bar = true;" + "})(namespace);" + "/** @param {namespace.Ctor} x\n" + " * @return {number} */ function f(x) { return x.bar; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testNotIIFE1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @param {...?} x */ function g(x) {}" + "g(function(y) { f(y); }, true);"); } public void testNamespaceType1() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @param {x.} y */ function f(y) {};", "Parse error. Namespaces not supported yet (x.)"); } public void testNamespaceType2() throws Exception { testTypes( "/** @namespace */ var x = {};" + "/** @namespace */ x.y = {};" + "/** @param {x.y.} y */ function f(y) {}", "Parse error. Namespaces not supported yet (x.y.)"); } public void testIssue61() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "function d() {" + " ns.a(123);" + "}", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue61b() throws Exception { testTypes( "var ns = {};" + "(function() {" + " /** @param {string} b */" + " ns.a = function(b) {};" + "})();" + "ns.a(123);", "actual parameter 1 of ns.a does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } public void testIssue259() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */" + "var Clock = function() {" + " /** @constructor */" + " this.Date = function() {};" + " f(new this.Date());" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : this.Date\n" + "required: number"); } public void testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); } public void testIssue368() throws Exception { testTypes( "/** @constructor */ function Foo(){}" + "/**\n" + " * @param {number} one\n" + " * @param {string} two\n" + " */\n" + "Foo.prototype.add = function(one, two) {};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar(){}" + "/** @override */\n" + "Bar.prototype.add = function(ignored) {};" + "(new Bar()).add(1, 2);", "actual parameter 2 of Bar.prototype.add does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testIssue380() throws Exception { testTypes( "/** @type { function(string): {innerHTML: string} } */\n" + "document.getElementById;\n" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();", // Parse warning, but still applied. "Type annotations are not allowed here. " + "Are you missing parentheses?"); } public void testIssue483() throws Exception { testTypes( "/** @constructor */ function C() {" + " /** @type {?Array} */ this.a = [];" + "}" + "C.prototype.f = function() {" + " if (this.a.length > 0) {" + " g(this.a);" + " }" + "};" + "/** @param {number} a */ function g(a) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : Array\n" + "required: number"); } public void testIssue537a() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz()) this.method(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Foo.prototype.method: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537b() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {method: function() {}};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz(1)) this.method();" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Function Bar.prototype.baz: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testIssue537c() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " Foo.call(this);" + " if (this.baz2()) alert(1);" + "}" + "Bar.prototype = {" + " baz: function() {" + " return true;" + " }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;", "Property baz2 never defined on Bar"); } public void testIssue537d() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {" + " this.xy = 3;" + "}" + "/** @return {Bar} */ function f() { return new Bar(); }" + "/** @return {Foo} */ function g() { return new Bar(); }" + "Bar.prototype = {" + " /** @return {Bar} */ x: function() { new Bar(); }," + " /** @return {Foo} */ y: function() { new Bar(); }" + "};" + "Bar.prototype.__proto__ = Foo.prototype;"); } public void testIssue586() throws Exception { testTypes( "/** @constructor */" + "var MyClass = function() {};" + "/** @param {boolean} success */" + "MyClass.prototype.fn = function(success) {};" + "MyClass.prototype.test = function() {" + " this.fn();" + " this.fn = function() {};" + "};", "Function MyClass.prototype.fn: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testIssue635() throws Exception { // TODO(nicksantos): Make this emit a warning, because of the 'this' type. testTypes( "/** @constructor */" + "function F() {}" + "F.prototype.bar = function() { this.baz(); };" + "F.prototype.baz = function() {};" + "/** @constructor */" + "function G() {}" + "G.prototype.bar = F.prototype.bar;"); } public void testIssue635b() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "/** @constructor */" + "function G() {}" + "/** @type {function(new:G)} */ var x = F;", "initializing variable\n" + "found : function (new:F): undefined\n" + "required: function (new:G): ?"); } public void testIssue669() throws Exception { testTypes( "/** @return {{prop1: (Object|undefined)}} */" + "function f(a) {" + " var results;" + " if (a) {" + " results = {};" + " results.prop1 = {a: 3};" + " } else {" + " results = {prop2: 3};" + " }" + " return results;" + "}"); } public void testIssue688() throws Exception { testTypes( "/** @const */ var SOME_DEFAULT =\n" + " /** @type {TwoNumbers} */ ({first: 1, second: 2});\n" + "/**\n" + "* Class defining an interface with two numbers.\n" + "* @interface\n" + "*/\n" + "function TwoNumbers() {}\n" + "/** @type number */\n" + "TwoNumbers.prototype.first;\n" + "/** @type number */\n" + "TwoNumbers.prototype.second;\n" + "/** @return {number} */ function f() { return SOME_DEFAULT; }", "inconsistent return type\n" + "found : (TwoNumbers|null)\n" + "required: number"); } public void testIssue700() throws Exception { testTypes( "/**\n" + " * @param {{text: string}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp1(opt_data) {\n" + " return opt_data.text;\n" + "}\n" + "\n" + "/**\n" + " * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp2(opt_data) {\n" + " /** @notypecheck */\n" + " function __inner() {\n" + " return temp1(opt_data.activity);\n" + " }\n" + " return __inner();\n" + "}\n" + "\n" + "/**\n" + " * @param {{n: number, text: string, b: boolean}} opt_data\n" + " * @return {string}\n" + " */\n" + "function temp3(opt_data) {\n" + " return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n" + "}\n" + "\n" + "function callee() {\n" + " var output = temp3({\n" + " n: 0,\n" + " text: 'a string',\n" + " b: true\n" + " })\n" + " alert(output);\n" + "}\n" + "\n" + "callee();"); } public void testIssue725() throws Exception { testTypes( "/** @typedef {{name: string}} */ var RecordType1;" + "/** @typedef {{name2222: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2222);" + "}", "Property name2222 never defined on rec"); } public void testIssue726() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @return {!Function} */ " + "Foo.prototype.getDeferredBar = function() { " + " var self = this;" + " return function() {" + " self.bar(true);" + " };" + "};", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIssue765() throws Exception { testTypes( "/** @constructor */" + "var AnotherType = function (parent) {" + " /** @param {string} stringParameter Description... */" + " this.doSomething = function (stringParameter) {};" + "};" + "/** @constructor */" + "var YetAnotherType = function () {" + " this.field = new AnotherType(self);" + " this.testfun=function(stringdata) {" + " this.field.doSomething(null);" + " };" + "};", "actual parameter 1 of AnotherType.doSomething " + "does not match formal parameter\n" + "found : null\n" + "required: string"); } public void testIssue783() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + " /** @type {Type} */" + " this.me_ = this;" + "};" + "Type.prototype.doIt = function() {" + " var me = this.me_;" + " for (var i = 0; i < me.unknownProp; i++) {}" + "};", "Property unknownProp never defined on Type"); } public void testIssue791() throws Exception { testTypes( "/** @param {{func: function()}} obj */" + "function test1(obj) {}" + "var fnStruc1 = {};" + "fnStruc1.func = function() {};" + "test1(fnStruc1);"); } public void testIssue810() throws Exception { testTypes( "/** @constructor */" + "var Type = function () {" + "};" + "Type.prototype.doIt = function(obj) {" + " this.prop = obj.unknownProp;" + "};", "Property unknownProp never defined on obj"); } public void testIssue1002() throws Exception { testTypes( "/** @interface */" + "var I = function() {};" + "/** @constructor @implements {I} */" + "var A = function() {};" + "/** @constructor @implements {I} */" + "var B = function() {};" + "var f = function() {" + " if (A === B) {" + " new B();" + " }" + "};"); } public void testIssue1023() throws Exception { testTypes( "/** @constructor */" + "function F() {}" + "(function () {" + " F.prototype = {" + " /** @param {string} x */" + " bar: function (x) { }" + " };" + "})();" + "(new F()).bar(true)", "actual parameter 1 of F.prototype.bar does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testIssue1047() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " */\n" + "function C2() {}\n" + "\n" + "/**\n" + " * @constructor\n" + " */\n" + "function C3(c2) {\n" + " /**\n" + " * @type {C2} \n" + " * @private\n" + " */\n" + " this.c2_;\n" + "\n" + " var x = this.c2_.prop;\n" + "}", "Property prop never defined on C2"); } public void testIssue1056() throws Exception { testTypes( "/** @type {Array} */ var x = null;" + "x.push('hi');", "No properties on this expression\n" + "found : null\n" + "required: Object"); } public void testIssue1072() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @return {number}\n" + " */\n" + "var f1 = function (x) {\n" + " return 3;\n" + "};\n" + "\n" + "/** Function */\n" + "var f2 = function (x) {\n" + " if (!x) throw new Error()\n" + " return /** @type {number} */ (f1('x'))\n" + "}\n" + "\n" + "/**\n" + " * @param {string} x\n" + " */\n" + "var f3 = function (x) {};\n" + "\n" + "f1(f3);", "actual parameter 1 of f1 does not match formal parameter\n" + "found : function (string): undefined\n" + "required: string"); } public void testEnums() throws Exception { testTypes( "var outer = function() {" + " /** @enum {number} */" + " var Level = {" + " NONE: 0," + " };" + " /** @type {!Level} */" + " var l = Level.NONE;" + "}"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}", "Type annotations are not allowed here. Are you missing parentheses?"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return {boolean}*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n" + " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testBug7701884() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} x\n" + " * @param {function(T)} y\n" + " * @template T\n" + " */\n" + "var forEach = function(x, y) {\n" + " for (var i = 0; i < x.length; i++) y(x[i]);\n" + "};" + "/** @param {number} x */" + "function f(x) {}" + "/** @param {?} x */" + "function h(x) {" + " var top = null;" + " forEach(x, function(z) { top = z; });" + " if (top) f(top);" + "}"); } public void testBug8017789() throws Exception { testTypes( "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};" + "/** @typedef {Object.<string, number>} */" + "var map;"); } public void testTypedefBeforeUse() throws Exception { testTypes( "/** @typedef {Object.<string, number>} */" + "var map;" + "/** @param {(map|function())} isResult */" + "var f = function(isResult) {" + " while (true)" + " isResult['t'];" + "};"); } public void testScopedConstructors1() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testScopedConstructors2() throws Exception { testTypes( "/** @param {Function} f */" + "function foo1(f) {" + " /** @param {Function} g */" + " f.prototype.bar = function(g) {};" + "}"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testQualifiedNameInference5() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @param {number} x */ ns.foo = function(x) {}; })();" + "(function() { ns.foo(true); })();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference6() throws Exception { testTypes( "/** @const */ var ns = {}; " + "/** @param {number} x */ ns.foo = function(x) {};" + "(function() { " + " ns.foo = function(x) {};" + " ns.foo(true); " + "})();", "actual parameter 1 of ns.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference7() throws Exception { testTypes( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + " /** @param {ns.Foo} x */ function f(x) {}" + " f(new ns.Foo(true));" + "})();", "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference8() throws Exception { testClosureTypesMultipleWarnings( "var ns = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.Foo = function(x) {};" + "})();" + "/** @param {ns.Foo} x */ function f(x) {}" + "f(new ns.Foo(true));", Lists.newArrayList( "actual parameter 1 of ns.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number")); } public void testQualifiedNameInference9() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @constructor \n * @param {number} x */ " + " ns.ns2.Foo = function(x) {};" + " /** @param {ns.ns2.Foo} x */ function f(x) {}" + " f(new ns.ns2.Foo(true));" + "})();", "actual parameter 1 of ns.ns2.Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testQualifiedNameInference10() throws Exception { testTypes( "var ns = {}; " + "ns.ns2 = {}; " + "(function() { " + " /** @interface */ " + " ns.ns2.Foo = function() {};" + " /** @constructor \n * @implements {ns.ns2.Foo} */ " + " function F() {}" + " (new F());" + "})();"); } public void testQualifiedNameInference11() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f() {" + " var x = new Foo();" + " x.onload = function() {" + " x.onload = null;" + " };" + "}"); } public void testQualifiedNameInference12() throws Exception { // We should be able to tell that the two 'this' properties // are different. testTypes( "/** @param {function(this:Object)} x */ function f(x) {}" + "/** @constructor */ function Foo() {" + " /** @type {number} */ this.bar = 3;" + " f(function() { this.bar = true; });" + "}"); } public void testQualifiedNameInference13() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "function f(z) {" + " var x = new Foo();" + " if (z) {" + " x.onload = function() {};" + " } else {" + " x.onload = null;" + " };" + "}"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return {number} */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertTypeEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNew17() throws Exception { testTypes("var goog = {}; goog.x = 3; new goog.x", "cannot instantiate non-constructor"); } public void testNew18() throws Exception { testTypes("var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @constructor */ goog.G = goog.F;"); } public void testName1() throws Exception { assertTypeEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertTypeEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertTypeEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertTypeEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertTypeEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); parent.setInputId(new InputId("code")); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Bad type annotation. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testFunctionCall9() throws Exception { testTypes( "/** @constructor\n * @template T\n **/ function Foo() {}\n" + "/** @param {T} x */ Foo.prototype.bar = function(x) {}\n" + "var foo = /** @type {Foo.<string>} */ (new Foo());\n" + "foo.bar(3);", "actual parameter 1 of Foo.prototype.bar does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind1() throws Exception { testTypes( "/** @type {function(string, number): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionBind2() throws Exception { testTypes( "/** @type {function(number): boolean} */" + "function f(x) { return true; }" + "f(f.bind(null, 3)());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testFunctionBind3() throws Exception { testTypes( "/** @type {function(number, string): boolean} */" + "function f(x, y) { return true; }" + "f.bind(null, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: string"); } public void testFunctionBind4() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, 3, 3, 3)(true);", "actual parameter 1 of function does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testFunctionBind5() throws Exception { testTypes( "/** @param {...number} x */" + "function f(x) {}" + "f.bind(null, true)(3, 3, 3);", "actual parameter 2 of f.bind does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testGoogBind1() throws Exception { testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testGoogBind2() throws Exception { // TODO(nicksantos): We do not currently type-check the arguments // of the goog.bind. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(boolean): boolean} */" + "function f(x, y) { return true; }" + "f(goog.bind(f, null, 'x')());", null); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast3a() throws Exception { // cannot downcast testTypes("/** @constructor */function Base() {}\n" + "/** @constructor @extends {Base} */function Derived() {}\n" + "var baseInstance = new Base();" + "/** @type {!Derived} */ var baz = baseInstance;\n", "initializing variable\n" + "found : Base\n" + "required: Derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast5a() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var barInstance = new bar;\n" + "var baz = /** @type {!foo} */(barInstance);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Bad type annotation. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Bad type annotation. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Bad type annotation. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testCast15() throws Exception { // This fixes a bug where a type cast on an object literal // would cause a run-time cast exception if the node was visited // more than once. // // Some code assumes that an object literal must have a object type, // while because of the cast, it could have any type (including // a union). testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ ({foo: 3});" + "/** @param {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() throws Exception { // A type cast should not invalidate the checks on the members testTypes( "for (var i = 0; i < 10; i++) {" + "var x = /** @type {Object|number} */ (" + " {/** @type {string} */ foo: 3});" + "}", "assignment to property foo of {foo: string}\n" + "found : number\n" + "required: string"); } public void testCast17a() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ (y)"); } public void testCast17b() throws Exception { // Mostly verifying that rhino actually understands these JsDocs. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ ({})"); } public void testCast19() throws Exception { testTypes( "var x = 'string';\n" + "/** @type {number} */\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: string\n" + "to : number"); } public void testCast20() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var y = /** @type {X} */(true);"); } public void testCast21() throws Exception { testTypes( "/** @enum {boolean|null} */\n" + "var X = {" + " AA: true," + " BB: false," + " CC: null" + "};\n" + "var value = true;\n" + "var y = /** @type {X} */(value);"); } public void testCast22() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: null\n" + "to : number"); } public void testCast23() throws Exception { testTypes( "var x = null;\n" + "var y = /** @type {Number} */(x);"); } public void testCast24() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number} */(x);", "invalid cast - must be a subtype or supertype\n" + "from: undefined\n" + "to : number"); } public void testCast25() throws Exception { testTypes( "var x = undefined;\n" + "var y = /** @type {number|undefined} */(x);"); } public void testCast26() throws Exception { testTypes( "function fn(dir) {\n" + " var node = dir ? 1 : 2;\n" + " fn(/** @type {number} */ (node));\n" + "}"); } public void testCast27() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {I} */(x);"); } public void testCast27a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x ;\n" + "var y = /** @type {I} */(x);"); } public void testCast28() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {!I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast28a() throws Exception { // C doesn't implement I but a subtype might. testTypes( "/** @interface */ function I() {}\n" + "/** @constructor */ function C() {}\n" + "/** @type {I} */ var x;\n" + "var y = /** @type {C} */(x);"); } public void testCast29a() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "var x = new C();\n" + "var y = /** @type {{remoteJids: Array, sessionId: string}} */(x);"); } public void testCast29b() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {C} */ var x;\n" + "var y = /** @type {{prop1: Array, prop2: string}} */(x);"); } public void testCast29c() throws Exception { // C doesn't implement the record type but a subtype might. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {{remoteJids: Array, sessionId: string}} */ var x ;\n" + "var y = /** @type {C} */(x);"); } public void testCast30() throws Exception { // Should be able to cast to a looser return type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function():string} */ var x ;\n" + "var y = /** @type {function():?} */(x);"); } public void testCast31() throws Exception { // Should be able to cast to a tighter parameter type testTypes( "/** @constructor */ function C() {}\n" + "/** @type {function(*)} */ var x ;\n" + "var y = /** @type {function(string)} */(x);"); } public void testCast32() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {null|{length:number}} */(x);"); } public void testCast33() throws Exception { // null and void should be assignable to any type that accepts one or the // other or both. testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string|undefined} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {string?} */(x);"); testTypes( "/** @constructor */ function C() {}\n" + "/** @type {null|undefined} */ var x ;\n" + "var y = /** @type {null} */(x);"); } public void testCast34a() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Object} */ var x ;\n" + "var y = /** @type {Function} */(x);"); } public void testCast34b() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "/** @type {Function} */ var x ;\n" + "var y = /** @type {Object} */(x);"); } public void testUnnecessaryCastToSuperType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "/**\n" + " * @constructor\n" + " * @extends {Base}\n" + " */\n" + "function Derived() {}\n" + "var d = new Derived();\n" + "var b = /** @type {!Base} */ (d);", "unnecessary cast\n" + "from: Derived\n" + "to : Base" ); } public void testUnnecessaryCastToSameType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var b = new Base();\n" + "var c = /** @type {!Base} */ (b);", "unnecessary cast\n" + "from: Base\n" + "to : Base" ); } /** * Checks that casts to unknown ({?}) are not marked as unnecessary. */ public void testUnnecessaryCastToUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var b = new Base();\n" + "var c = /** @type {?} */ (b);"); } /** * Checks that casts from unknown ({?}) are not marked as unnecessary. */ public void testUnnecessaryCastFromUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "/** @type {?} */ var x;\n" + "var y = /** @type {Base} */ (x);"); } public void testUnnecessaryCastToAndFromUnknown() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */ function A() {}\n" + "/** @constructor */ function B() {}\n" + "/** @type {!Array.<!A>} */ var x = " + "/** @type {!Array.<?>} */( /** @type {!Array.<!B>} */([]) );"); } /** * Checks that a cast from {?Base} to {!Base} is not considered unnecessary. */ public void testUnnecessaryCastToNonNullType() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var c = /** @type {!Base} */ (random ? new Base() : null);" ); } public void testUnnecessaryCastToStar() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.UNNECESSARY_CASTS, CheckLevel.WARNING); testTypes( "/** @constructor */\n" + "function Base() {}\n" + "var c = /** @type {*} */ (new Base());", "unnecessary cast\n" + "from: Base\n" + "to : *" ); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/** @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (new:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testTypeof2() throws Exception { testTypes("function f(){ if (typeof 123 == 'numbr') return 321; }", "unknown type: numbr"); } public void testTypeof3() throws Exception { testTypes("function f() {" + "return (typeof 123 == 'number' ||" + "typeof 123 == 'string' ||" + "typeof 123 == 'boolean' ||" + "typeof 123 == 'undefined' ||" + "typeof 123 == 'function' ||" + "typeof 123 == 'object' ||" + "typeof 123 == 'unknown'); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testConstructorType8() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = {x: 0, y: 0};" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorType9() throws Exception { testTypes( "var ns = {};" + "ns.create = function() { return function() {}; };" + "ns.extend = function(x) { return x; };" + "/** @constructor */ ns.Foo = ns.create();" + "ns.Foo.prototype = ns.extend({x: 0, y: 0});" + "/**\n" + " * @param {ns.Foo} foo\n" + " * @return {string}\n" + " */\n" + "function f(foo) {" + " return foo.x;" + "}"); } public void testConstructorType10() throws Exception { testTypes("/** @constructor */" + "function NonStr() {}" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends{NonStr}\n" + " */" + "function NonStrKid() {}", "NonStrKid cannot extend this type; " + "structs can only extend structs"); } public void testConstructorType11() throws Exception { testTypes("/** @constructor */" + "function NonDict() {}" + "/**\n" + " * @constructor\n" + " * @dict\n" + " * @extends{NonDict}\n" + " */" + "function NonDictKid() {}", "NonDictKid cannot extend this type; " + "dicts can only extend dicts"); } public void testConstructorType12() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Bar() {}\n" + "Bar.prototype = {};\n", "Bar cannot extend this type; " + "structs can only extend structs"); } public void testBadStruct() throws Exception { testTypes("/** @struct */function Struct1() {}", "@struct used without @constructor for Struct1"); } public void testBadDict() throws Exception { testTypes("/** @dict */function Dict1() {}", "@dict used without @constructor for Dict1"); } public void testAnonymousPrototype1() throws Exception { testTypes( "var ns = {};" + "/** @constructor */ ns.Foo = function() {" + " this.bar(3, 5);" + "};" + "ns.Foo.prototype = {" + " bar: function(x) {}" + "};", "Function ns.Foo.prototype.bar: called with 2 argument(s). " + "Function requires at least 1 argument(s) and no more " + "than 1 argument(s)."); } public void testAnonymousPrototype2() throws Exception { testTypes( "/** @interface */ var Foo = function() {};" + "Foo.prototype = {" + " foo: function(x) {}" + "};" + "/**\n" + " * @constructor\n" + " * @implements {Foo}\n" + " */ var Bar = function() {};", "property foo on interface Foo is not implemented by type Bar"); } public void testAnonymousType1() throws Exception { testTypes("function f() { return {}; }" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() { return {}; }" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() { return {}; }" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return {Array} */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */(new f()); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top-level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertTypeEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertTypeEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertTypeEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertTypeEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertTypeEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertTypeEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertTypeEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return {number} */" + "Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return {number} */" + "Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return {string} */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testClosureTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Bad type annotation. Unknown type goog.Missing"); } public void testInheritanceCheck15() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo;" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + "function(bar) {};"); } public void testInheritanceCheck16() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @type {number} */ goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @type {number} */ goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck17() throws Exception { // Make sure this warning still works, even when there's no // @override tag. reportMissingOverrides = CheckLevel.OFF; testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "/** @param {number} x */ goog.Super.prototype.foo = function(x) {};" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @param {string} x */ goog.Sub.prototype.foo = function(x) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: function (this:goog.Super, number): undefined\n" + "override: function (this:goog.Sub, string): undefined"); } public void testInterfacePropertyOverride1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfacePropertyOverride2() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @desc description */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @interface\n @extends {Super} */function Sub() {};" + "/** @desc description */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return {string} */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {string} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return {number} */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Bad type annotation. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfaceInheritanceCheck9() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.bar = function() {return 3; };" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck10() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.bar = function() {};" + "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() {return 3; };" + "/** @constructor \n * @extends {F} \n * @implements {I} */ " + "function G() {}" + "/** @return {number} \n * @override */ " + "G.prototype.bar = G.prototype.foo;" + "/** @return {string} */ function f() { return new G().bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfaceInheritanceCheck12() throws Exception { testTypes( "/** @interface */ function I() {};\n" + "/** @type {string} */ I.prototype.foobar;\n" + "/** \n * @constructor \n * @implements {I} */\n" + "function C() {\n" + "/** \n * @type {number} */ this.foobar = 2;};\n" + "/** @type {I} */ \n var test = new C(); alert(test.foobar);", "mismatch of the foobar property type and the type of the property" + " it overrides from interface I\n" + "original: string\n" + "override: number"); } public void testInterfaceInheritanceCheck13() throws Exception { testTypes( "function abstractMethod() {};\n" + "/** @interface */var base = function() {};\n" + "/** @extends {base} \n @interface */ var Int = function() {}\n" + "/** @type {{bar : !Function}} */ var x; \n" + "/** @type {!Function} */ base.prototype.bar = abstractMethod; \n" + "/** @type {Int} */ var foo;\n" + "foo.bar();"); } /** * Verify that templatized interfaces can extend one another and share * template values. */ public void testInterfaceInheritanceCheck14() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @implements {B.<string>} */function C() {};" + "/** @return {string}\n @override */C.prototype.foo = function() {};" + "/** @return {string}\n @override */C.prototype.bar = function() {};"); } /** * Verify that templatized instances can correctly implement templatized * interfaces. */ public void testInterfaceInheritanceCheck15() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @interface\n @template U\n @extends {A.<U>} */function B() {};" + "/** @desc description\n @return {U} */B.prototype.bar = function() {};" + "/** @constructor\n @template V\n @implements {B.<V>}\n */function C() {};" + "/** @return {V}\n @override */C.prototype.foo = function() {};" + "/** @return {V}\n @override */C.prototype.bar = function() {};"); } /** * Verify that using @override to declare the signature for an implementing * class works correctly when the interface is generic. */ public void testInterfaceInheritanceCheck16() throws Exception { testTypes( "/** @interface\n @template T */function A() {};" + "/** @desc description\n @return {T} */A.prototype.foo = function() {};" + "/** @desc description\n @return {T} */A.prototype.bar = function() {};" + "/** @constructor\n @implements {A.<string>} */function B() {};" + "/** @override */B.prototype.foo = function() { return 'string'};" + "/** @override */B.prototype.bar = function() { return 3 };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } /** * Verify that templatized interfaces enforce their template type values. */ public void testInterfacePropertyNotImplemented3() throws Exception { testTypes( "/** @interface\n @template T */function Int() {};" + "/** @desc description\n @return {T} */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int.<string>} */function Foo() {};" + "/** @return {number}\n @override */Foo.prototype.foo = function() {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Int\n" + "original: function (this:Int): string\n" + "override: function (this:Foo): number"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes( // externs "/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n", "", null, false); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertTypeEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertTypeEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertTypeEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testObjectLiteralDeclaration2() throws Exception { testTypes( "var x = {" + " /** @type {boolean} */ abc: true" + "};" + "x.abc = 0;", "assignment to property abc of x\n" + "found : number\n" + "required: boolean"); } public void testObjectLiteralDeclaration3() throws Exception { testTypes( "/** @param {{foo: !Function}} x */ function f(x) {}" + "f({foo: function() {}});"); } public void testObjectLiteralDeclaration4() throws Exception { testClosureTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {string} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};", "assignment to property abc of x\n" + "found : function (string): undefined\n" + "required: function (boolean): undefined"); // TODO(user): suppress {duplicate} currently also silence the // redefining type error in the TypeValidator. Maybe it needs // a new suppress name instead? } public void testObjectLiteralDeclaration5() throws Exception { testTypes( "var x = {" + " /** @param {boolean} x */ abc: function(x) {}" + "};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};"); } public void testObjectLiteralDeclaration6() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testObjectLiteralDeclaration7() throws Exception { testTypes( "var x = {};" + "/**\n" + " * @type {function(boolean): undefined}\n" + " */ x.abc = function(x) {};" + "x = {" + " /**\n" + " * @param {boolean} x\n" + " * @suppress {duplicate}\n" + " */" + " abc: function(x) {}" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertTypeEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertTypeEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertTypeEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface outside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface outside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface1() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testDataPropertyOnInterface2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() {}\n" + "/** @override */\n" + "C.prototype.x = 'foo';", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;\n" + "/** @constructor \n" + " * @implements {T} \n" + " */\n" + "function C() { /** @type {string} */ \n this.x = 'foo'; }\n", "mismatch of the x property type and the type of the property it " + "overrides from interface T\n" + "original: number\n" + "override: string"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testClosureTypesMultipleWarnings( "/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", Lists.newArrayList( "assignment to property x of T.prototype\n" + "found : number\n" + "required: function (this:T): number", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod")); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f = function(){}; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T", "Could not resolve type in @extends tag of T")); } public void testImplementsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {T} */var T = function() {};" + "alert((new T).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type T")); } public void testImplementsExtendsLoop() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @constructor \n * @implements {F} */var G = function() {};" + "/** @constructor \n * @extends {G} */var F = function() {};" + "alert((new F).foo);", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type F")); } public void testInterfaceExtendsLoop() throws Exception { // TODO(user): This should give a cycle in inheritance graph error, // not a cannot resolve error. testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface \n * @extends {F} */var G = function() {};" + "/** @interface \n * @extends {G} */var F = function() {};", Lists.newArrayList( "Could not resolve type in @extends tag of G")); } public void testConversionFromInterfaceToRecursiveConstructor() throws Exception { testClosureTypesMultipleWarnings( suppressMissingProperty("foo") + "/** @interface */ var OtherType = function() {}\n" + "/** @implements {MyType} \n * @constructor */\n" + "var MyType = function() {}\n" + "/** @type {MyType} */\n" + "var x = /** @type {!OtherType} */ (new Object());", Lists.newArrayList( "Parse error. Cycle detected in inheritance chain of type MyType", "initializing variable\n" + "found : OtherType\n" + "required: (MyType|null)")); } public void testDirectPrototypeAssign() throws Exception { // For now, we just ignore @type annotations on the prototype. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTypeEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); Asserts.assertTypeCollectionEquals( Lists.newArrayList(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to false\n" + "left : (null|string)\n" + "right: number"); } public void testTypeInferenceWithNoEntry1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " f(this.bar.baz);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testTypeInferenceWithNoEntry2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number} x */ function f(x) {}" + "/** @param {!Object} x */ function g(x) {}" + "/** @constructor */ function Foo() {}" + "Foo.prototype.init = function() {" + " /** @type {?{baz: number}} */ this.bar = {baz: 3};" + "};" + "/**\n" + " * @extends {Foo}\n" + " * @constructor\n" + " */" + "function SubFoo() {}" + "/** Method */" + "SubFoo.prototype.method = function() {" + " for (var i = 0; i < 10; i++) {" + " f(this.bar);" + " goog.asserts.assert(this.bar);" + " g(this.bar);" + " }" + "};", "actual parameter 1 of f does not match formal parameter\n" + "found : (null|{baz: number})\n" + "required: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Bad type annotation. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return 3; }", null); } public void testForwardTypeDeclaration2() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testForwardTypeDeclaration4() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(new MyType());", null); } public void testForwardTypeDeclaration5() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @extends {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", "Could not resolve type in @extends tag of YourType"); } public void testForwardTypeDeclaration6() throws Exception { testClosureTypesMultipleWarnings( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @constructor\n" + " * @implements {MyType}\n" + " */ var YourType = function() {};" + "/** @override */ YourType.prototype.method = function() {};", Lists.newArrayList( "Could not resolve type in @implements tag of YourType", "property method not defined on any superclass of YourType")); } public void testForwardTypeDeclaration7() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType=} x */" + "function f(x) { return x == undefined; }", null); } public void testForwardTypeDeclaration8() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { return x.name == undefined; }", null); } public void testForwardTypeDeclaration9() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */" + "function f(x) { x.name = 'Bob'; }", null); } public void testForwardTypeDeclaration10() throws Exception { String f = "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType|number} x */ function f(x) { }"; testClosureTypes(f, null); testClosureTypes(f + "f(3);", null); testClosureTypes(f + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: (MyType|null|number)"); } public void testForwardTypeDeclaration12() throws Exception { // We assume that {Function} types can produce anything, and don't // want to type-check them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return new ctor(); }", null); } public void testForwardTypeDeclaration13() throws Exception { // Some projects use {Function} registries to register constructors // that aren't in their binaries. We want to make sure we can pass these // around, but still do other checks on them. testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/**\n" + " * @param {!Function} ctor\n" + " * @return {MyType}\n" + " */\n" + "function f(ctor) { return (new ctor()).impossibleProp; }", "Property impossibleProp never defined on ?"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (new:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef4() throws Exception { testTypes( "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "/** @param {AB} x */ function f(x) {}" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testTypeDef5() throws Exception { // Notice that the error message is slightly different than // the one for testTypeDef4, even though they should be the same. // This is an implementation detail necessary for NamedTypes work out // OK, and it should change if NamedTypes ever go away. testTypes( "/** @param {AB} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "/** @constructor */ function B() {}" + "/** @typedef {(A|B)} */ var AB;" + "f(new A()); f(new B()); f(1);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (A|B|null)"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent6() throws Exception { String js = "a = {TRUE: 1, FALSE: 0};"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private static ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testMissingProperty35() throws Exception { // Bar has specialProp defined, so Bar|Baz may have specialProp defined. testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @constructor */ function Baz() {}" + "/** @param {Foo|Bar} x */ function f(x) { x.specialProp = 1; }" + "/** @param {Bar|Baz} x */ function g(x) { return x.specialProp; }"); } public void testMissingProperty36() throws Exception { // Foo has baz defined, and SubFoo has bar defined, so some objects with // bar may have baz. testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.baz = 0;" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "SubFoo.prototype.bar = 0;" + "/** @param {{bar: number}} x */ function f(x) { return x.baz; }"); } public void testMissingProperty37() throws Exception { // This used to emit a missing property warning because we couldn't // determine that the inf(Foo, {isVisible:boolean}) == SubFoo. testTypes( "/** @param {{isVisible: boolean}} x */ function f(x){" + " x.isVisible = false;" + "}" + "/** @constructor */ function Foo() {}" + "/**\n" + " * @constructor \n" + " * @extends {Foo}\n" + " */ function SubFoo() {}" + "/** @type {boolean} */ SubFoo.prototype.isVisible = true;" + "/**\n" + " * @param {Foo} x\n" + " * @return {boolean}\n" + " */\n" + "function g(x) { return x.isVisible; }"); } public void testMissingProperty38() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @return {Foo|Bar} */ function f() { return new Foo(); }" + "f().missing;", "Property missing never defined on (Bar|Foo|null)"); } public void testMissingProperty39() throws Exception { testTypes( "/** @return {string|number} */ function f() { return 3; }" + "f().length;"); } public void testMissingProperty40() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {(Array|MissingType)} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty41() throws Exception { testTypes( "/** @param {(Array|Date)} x */" + "function f(x) { if (x.impossible) x.impossible(); }"); } public void testMissingProperty42() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { " + " if (typeof x.impossible == 'undefined') throw Error();" + " return x.impossible;" + "}"); } public void testMissingProperty43() throws Exception { testTypes( "function f(x) { " + " return /** @type {number} */ (x.impossible) && 1;" + "}"); } public void testReflectObject1() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: 3});", null); } public void testReflectObject2() throws Exception { testClosureTypes( "var goog = {}; goog.reflect = {}; " + "goog.reflect.object = function(x, y){};" + "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function A() {}" + "goog.reflect.object(A, {x: f(1 + 1)});", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testLends1() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends */ ({bar: 1}));", "Bad type annotation. missing object name in @lends tag"); } public void testLends2() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foob} */ ({bar: 1}));", "Variable Foob not declared before @lends annotation."); } public void testLends3() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert(Foo.bar);", "Property bar never defined on Foo"); } public void testLends4() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));" + "alert(Foo.bar);"); } public void testLends5() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, {bar: 1});" + "alert((new Foo()).bar);", "Property bar never defined on Foo"); } public void testLends6() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype} */ ({bar: 1}));" + "alert((new Foo()).bar);"); } public void testLends7() throws Exception { testTypes( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {Foo.prototype|Foo} */ ({bar: 1}));", "Bad type annotation. expected closing }"); } public void testLends8() throws Exception { testTypes( "function extend(x, y) {}" + "/** @type {number} */ var Foo = 3;" + "extend(Foo, /** @lends {Foo} */ ({bar: 1}));", "May only lend properties to object types. Foo has type number."); } public void testLends9() throws Exception { testClosureTypesMultipleWarnings( "function extend(x, y) {}" + "/** @constructor */ function Foo() {}" + "extend(Foo, /** @lends {!Foo} */ ({bar: 1}));", Lists.newArrayList( "Bad type annotation. expected closing }", "Bad type annotation. missing object name in @lends tag")); } public void testLends10() throws Exception { testTypes( "function defineClass(x) { return function() {}; } " + "/** @constructor */" + "var Foo = defineClass(" + " /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));" + "/** @return {string} */ function f() { return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testLends11() throws Exception { testTypes( "function defineClass(x, y) { return function() {}; } " + "/** @constructor */" + "var Foo = function() {};" + "/** @return {*} */ Foo.prototype.bar = function() { return 3; };" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "var SubFoo = defineClass(Foo, " + " /** @lends {SubFoo.prototype} */ ({\n" + " /** @return {number} */ bar: function() { return 3; }}));" + "/** @return {string} */ function f() { return (new SubFoo()).bar(); }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertTypeEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertTypeEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertTypeEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertTypeEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); MemoizedScopeCreator scopeCreator = new MemoizedScopeCreator( new TypedScopeCreator(compiler)); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testUpdateParameterTypeOnClosure() throws Exception { testTypes( "/**\n" + "* @constructor\n" + "* @param {*=} opt_value\n" + "* @return {?}\n" + "*/\n" + "function Object(opt_value) {}\n" + "/**\n" + "* @constructor\n" + "* @param {...*} var_args\n" + "*/\n" + "function Function(var_args) {}\n" + "/**\n" + "* @type {Function}\n" + "*/\n" + // The line below sets JSDocInfo on Object so that the type of the // argument to function f has JSDoc through its prototype chain. "Object.prototype.constructor = function() {};\n", "/**\n" + "* @param {function(): boolean} fn\n" + "*/\n" + "function f(fn) {}\n" + "f(function(g) { });\n", null, false); } public void testTemplatedThisType1() throws Exception { testTypes( "/** @constructor */\n" + "function Foo() {}\n" + "/**\n" + " * @this {T}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Foo.prototype.method = function() {};\n" + "/**\n" + " * @constructor\n" + " * @extends {Foo}\n" + " */\n" + "function Bar() {}\n" + "var g = new Bar().method();\n" + "/**\n" + " * @param {number} a\n" + " */\n" + "function compute(a) {};\n" + "compute(g);\n", "actual parameter 1 of compute does not match formal parameter\n" + "found : Bar\n" + "required: number"); } public void testTemplatedThisType2() throws Exception { testTypes( "/**\n" + " * @this {Array.<T>|{length:number}}\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "Array.prototype.method = function() {};\n" + "(function(){\n" + " Array.prototype.method.call(arguments);" + "})();"); } public void testTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() { this });"); } public void testTemplateType2() throws Exception { // "this" types need to be coerced for ES3 style function or left // allow for ES5-strict methods. testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});"); } public void testTemplateType3() throws Exception { testTypes( "/**" + " * @param {T} v\n" + " * @param {function(T)} f\n" + " * @template T\n" + " */\n" + "function call(v, f) { f.call(null, v); }" + "/** @type {string} */ var s;" + "call(3, function(x) {" + " x = true;" + " s = x;" + "});", "assignment\n" + "found : boolean\n" + "required: string"); } public void testTemplateType4() throws Exception { testTypes( "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "x = fn(3, null);", "assignment\n" + "found : (null|number)\n" + "required: Object"); } public void testTemplateType5() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes( "var CGI_PARAM_RETRY_COUNT = 'rc';" + "" + "/**" + " * @param {...T} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p; }\n" + "/** @type {!Object} */ var x;" + "" + "/** @return {void} */\n" + "function aScope() {\n" + " x = fn(CGI_PARAM_RETRY_COUNT, 1);\n" + "}", "assignment\n" + "found : (number|string)\n" + "required: Object"); } public void testTemplateType6() throws Exception { testTypes( "/**" + " * @param {Array.<T>} arr \n" + " * @param {?function(T)} f \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(arr, f) { return arr[0]; }\n" + "/** @param {Array.<number>} arr */ function g(arr) {" + " /** @type {!Object} */ var x = fn.call(null, arr, null);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType7() throws Exception { // TODO(johnlenz): As the @this type for Array.prototype.push includes // "{length:number}" (and this includes "Array.<number>") we don't // get a type warning here. Consider special-casing array methods. testTypes( "/** @type {!Array.<string>} */\n" + "var query = [];\n" + "query.push(1);\n"); } public void testTemplateType8() throws Exception { testTypes( "/** @constructor \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType9() throws Exception { // verify interface type parameters are recognized. testTypes( "/** @interface \n" + " * @template S,T\n" + " */\n" + "function Bar() {}\n" + "/**" + " * @param {Bar.<T>} bar \n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(bar) {}\n" + "/** @param {Bar.<number>} bar */ function g(bar) {" + " /** @type {!Object} */ var x = fn(bar);" + "}", "initializing variable\n" + "found : number\n" + "required: Object"); } public void testTemplateType10() throws Exception { // verify a type parameterized with unknown can be assigned to // the same type with any other type parameter. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Bar() {}\n" + "\n" + "" + "/** @type {!Bar.<?>} */ var x;" + "/** @type {!Bar.<number>} */ var y;" + "y = x;"); } public void testTemplateType11() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @extends {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType12() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<string>}\n" + " */\n" + "function A() {}\n" + "" + "/** @constructor \n" + " * @implements {Foo.<number>}\n" + " */\n" + "function B() {}\n" + "" + "/** @type {!Foo.<string>} */ var a = new A();\n" + "/** @type {!Foo.<string>} */ var b = new B();", "initializing variable\n" + "found : B\n" + "required: Foo.<string>"); } public void testTemplateType13() throws Exception { // verify that assignment/subtype relationships work when extending // templatized types. testTypes( "/** @constructor \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @extends {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType14() throws Exception { // verify that assignment/subtype relationships work when implementing // templatized types. testTypes( "/** @interface \n" + " * @template T\n" + " */\n" + "function Foo() {}\n" + "" + "/** @constructor \n" + " * @template T\n" + " * @implements {Foo.<T>}\n" + " */\n" + "function A() {}\n" + "" + "var a1 = new A();\n" + "var a2 = /** @type {!A.<string>} */ (new A());\n" + "var a3 = /** @type {!A.<number>} */ (new A());\n" + "/** @type {!Foo.<string>} */ var f1 = a1;\n" + "/** @type {!Foo.<string>} */ var f2 = a2;\n" + "/** @type {!Foo.<string>} */ var f3 = a3;", "initializing variable\n" + "found : A.<number>\n" + "required: Foo.<string>"); } public void testTemplateType15() throws Exception { testTypes( "/**" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({foo:3});", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType16() throws Exception { testTypes( "/** @constructor */ function C() {\n" + " /** @type {number} */ this.foo = 1\n" + "}\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn(new C());", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType17() throws Exception { testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn(new C());", "assignment\n" + "found : number\n" + "required: Object"); } public void testTemplateType18() throws Exception { // Until template types can be restricted to exclude undefined, they // are always optional. testTypes( "/** @constructor */ function C() {}\n" + "C.prototype.foo = 1;\n" + "/**\n" + " * @param {{foo:T}} p\n" + " * @return {T} \n" + " * @template T\n" + " */\n" + "function fn(p) { return p.foo; }\n" + "/** @type {!Object} */ var x;" + "x = fn({});"); } public void testTemplateType19() throws Exception { testTypes( "/**\n" + " * @param {T} t\n" + " * @param {U} u\n" + " * @return {{t:T, u:U}} \n" + " * @template T,U\n" + " */\n" + "function fn(t, u) { return {t:t, u:u}; }\n" + "/** @type {null} */ var x = fn(1, 'str');", "initializing variable\n" + "found : {t: number, u: string}\n" + "required: null"); } public void testTemplateTypeWithUnresolvedType() throws Exception { testClosureTypes( "var goog = {};\n" + "goog.addDependency = function(a,b,c){};\n" + "goog.addDependency('a.js', ['Color'], []);\n" + "/** @interface @template T */ function C() {}\n" + "/** @return {!Color} */ C.prototype.method;\n" + "/** @constructor @implements {C} */ function D() {}\n" + "/** @override */ D.prototype.method = function() {};", null); // no warning expected. } public void testTemplateTypeWithTypeDef1a() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "" + "/** @type {Generic.<!Foo>} */ var x;\n" + "/** @type {Generic.<!Bar>} */ var y;\n" + "" + "x = y;\n" + // no warning "/** @type null */ var z1 = y;\n" + "", "initializing variable\n" + "found : (Generic.<Foo>|null)\n" + "required: null"); } public void testTemplateTypeWithTypeDef1b() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "" + "/** @type {Generic.<!Foo>} */ var x;\n" + "/** @type {Generic.<!Bar>} */ var y;\n" + "" + "y = x;\n" + // no warning. "/** @type null */ var z1 = x;\n" + "", "initializing variable\n" + "found : (Generic.<Foo>|null)\n" + "required: null"); } public void testTemplateTypeWithTypeDef2a() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Bar> */ x) {}\n" + "/** @type {Generic.<!Foo>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2b() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Bar> */ x) {}\n" + "/** @type {Generic.<!Bar>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2c() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Foo> */ x) {}\n" + "/** @type {Generic.<!Foo>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeWithTypeDef2d() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " * @param {T} x\n" + " */\n" + "function Generic(x) {}\n" + "\n" + "/** @constructor */\n" + "function Foo() {}\n" + "\n" + "/** @typedef {!Foo} */\n" + "var Bar;\n" + "\n" + "function f(/** Generic.<!Foo> */ x) {}\n" + "/** @type {Generic.<!Bar>} */ var x;\n" + "f(x);\n"); // no warning expected. } public void testTemplateTypeRecursion1() throws Exception { testTypes( "/** @typedef {{a: D2}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void testTemplateTypeRecursion2() throws Exception { testTypes( "/** @typedef {{a: D2}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "/** @type {D1} */ var x;" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void testTemplateTypeRecursion3() throws Exception { testTypes( "/** @typedef {{a: function(D2)}} */\n" + "var D1;\n" + "\n" + "/** @typedef {{b: D1}} */\n" + "var D2;\n" + "\n" + "/** @type {D1} */ var x;" + "fn(x);\n" + "\n" + "\n" + "/**\n" + " * @param {!D1} s\n" + " * @template T\n" + " */\n" + "var fn = function(s) {};" ); } public void disable_testBadTemplateType4() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testBadTemplateType5() throws Exception { // TODO(johnlenz): Add a check for useless of template types. // Unless there are at least two references to a Template type in // a definition it isn't useful. testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void disable_testFunctionLiteralUndefinedThisArgument() throws Exception { // TODO(johnlenz): this was a weird error. We should add a general // restriction on what is accepted for T. Something like: // "@template T of {Object|string}" or some such. testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; });", "Function literal argument refers to undefined this argument"); } public void testFunctionLiteralDefinedThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() { this; }, {});"); } public void testFunctionLiteralDefinedThisArgument2() throws Exception { testTypes("" + "/** @param {string} x */ function f(x) {}" + "/**\n" + " * @param {?function(this:T, ...)} fn\n" + " * @param {T=} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "function g() { baz(function() { f(this.length); }, []); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testFunctionLiteralUnreadNullThisArgument() throws Exception { testTypes("" + "/**\n" + " * @param {function(this:T, ...)?} fn\n" + " * @param {?T} opt_obj\n" + " * @template T\n" + " */\n" + "function baz(fn, opt_obj) {}\n" + "baz(function() {}, null);"); } public void testUnionTemplateThisType() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {F|Array} */ function g() { return []; }" + "/** @param {F} x */ function h(x) { }" + "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(g(), function() { h(this); });", "actual parameter 1 of h does not match formal parameter\n" + "found : (Array|F|null)\n" + "required: (F|null)"); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } public void testRecordType1() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: {prop: number}"); } public void testRecordType2() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "f({});"); } public void testRecordType3() throws Exception { testTypes( "/** @param {{prop: number}} x */" + "function f(x) {}" + "f({prop: 'x'});", "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string)}\n" + "required: {prop: number}"); } public void testRecordType4() throws Exception { // Notice that we do not do flow-based inference on the object type: // We don't try to prove that x.prop may not be string until x // gets passed to g. testClosureTypesMultipleWarnings( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{prop: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);", Lists.newArrayList( "actual parameter 1 of f does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (number|undefined)}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|string|undefined)}\n" + "required: {prop: (string|undefined)}")); } public void testRecordType5() throws Exception { testTypes( "/** @param {{prop: (number|undefined)}} x */" + "function f(x) {}" + "/** @param {{otherProp: (string|undefined)}} x */" + "function g(x) {}" + "var x = {}; f(x); g(x);"); } public void testRecordType6() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { return {}; }"); } public void testRecordType7() throws Exception { testTypes( "/** @return {{prop: (number|undefined)}} x */" + "function f() { var x = {}; g(x); return x; }" + "/** @param {number} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : {prop: (number|undefined)}\n" + "required: number"); } public void testRecordType8() throws Exception { testTypes( "/** @return {{prop: (number|string)}} x */" + "function f() { var x = {prop: 3}; g(x.prop); return x; }" + "/** @param {string} x */" + "function g(x) {}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testDuplicateRecordFields1() throws Exception { testTypes("/**" + "* @param {{x:string, x:number}} a" + "*/" + "function f(a) {};", "Parse error. Duplicate record field x"); } public void testDuplicateRecordFields2() throws Exception { testTypes("/**" + "* @param {{name:string,number:x,number:y}} a" + " */" + "function f(a) {};", new String[] {"Bad type annotation. Unknown type x", "Parse error. Duplicate record field number", "Bad type annotation. Unknown type y"}); } public void testMultipleExtendsInterface1() throws Exception { testTypes("/** @interface */ function base1() {}\n" + "/** @interface */ function base2() {}\n" + "/** @interface\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}"); } public void testMultipleExtendsInterface2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int0.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int0 is not implemented by type Foo"); } public void testMultipleExtendsInterface3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @desc description */Int1.prototype.foo = function() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int1 is not implemented by type Foo"); } public void testMultipleExtendsInterface4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + " @extends {number} */" + "function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "Int2 @extends non-object type number"); } public void testMultipleExtendsInterface5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @constructor */function Int1() {};" + "/** @desc description @ return {string} x */" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Int2 cannot extend this type; interfaces can only extend interfaces"); } public void testMultipleExtendsInterface6() throws Exception { testTypes( "/** @interface */function Super1() {};" + "/** @interface */function Super2() {};" + "/** @param {number} bar */Super2.prototype.foo = function(bar) {};" + "/** @interface\n @extends {Super1}\n " + "@extends {Super2} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super2\n" + "original: function (this:Super2, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testMultipleExtendsInterfaceAssignment() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "/** @type {I3} */var i3 = t;\n" + "i1 = i3;\n" + "i2 = i3;\n"); } public void testMultipleExtendsInterfaceParamPass() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */ var I2 = function() {}\n" + "/** @interface\n@extends {I1}\n@extends {I2}*/" + "var I3 = function() {};\n" + "/** @constructor\n@implements {I3}*/var T = function() {};\n" + "var t = new T();\n" + "/** @param x I1 \n@param y I2\n@param z I3*/function foo(x,y,z){};\n" + "foo(t,t,t)\n"); } public void testBadMultipleExtendsClass() throws Exception { testTypes("/** @constructor */ function base1() {}\n" + "/** @constructor */ function base2() {}\n" + "/** @constructor\n" + "* @extends {base1}\n" + "* @extends {base2}\n" + "*/\n" + "function derived() {}", "Bad type annotation. type annotation incompatible " + "with other annotations"); } public void testInterfaceExtendsResolution() throws Exception { testTypes("/** @interface \n @extends {A} */ function B() {};\n" + "/** @constructor \n @implements {B} */ function C() {};\n" + "/** @interface */ function A() {};"); } public void testPropertyCanBeDefinedInObject() throws Exception { testTypes("/** @interface */ function I() {};" + "I.prototype.bar = function() {};" + "/** @type {Object} */ var foo;" + "foo.bar();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertTypeEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } public void testExtendedInterfacePropertiesCompatibility1() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility2() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @interface */function Int2() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @type {Object} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int0} \n @extends {Int1} \n" + "@extends {Int2}*/" + "function Int3() {};", new String[] { "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int0 and Int1", "Interface Int3 has a property foo with incompatible types in " + "its super interfaces Int1 and Int2" }); } public void testExtendedInterfacePropertiesCompatibility3() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};", "Interface Int3 has a property foo with incompatible types in its " + "super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility4() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface \n @extends {Int0} */ function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @interface */function Int2() {};" + "/** @interface \n @extends {Int2} */ function Int3() {};" + "/** @type {string} */" + "Int2.prototype.foo;" + "/** @interface \n @extends {Int1} \n @extends {Int3} */" + "function Int4() {};", "Interface Int4 has a property foo with incompatible types in its " + "super interfaces Int0 and Int2"); } public void testExtendedInterfacePropertiesCompatibility5() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {number} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility6() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {string} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1"); } public void testExtendedInterfacePropertiesCompatibility7() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int3 has a property foo with incompatible types in its" + " super interfaces Int0 and Int1", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int1 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility8() throws Exception { testTypes( "/** @interface */function Int0() {};" + "/** @interface */function Int1() {};" + "/** @type {number} */" + "Int0.prototype.foo;" + "/** @type {string} */" + "Int1.prototype.bar;" + "/** @interface \n @extends {Int1} */ function Int2() {};" + "/** @interface \n @extends {Int0} \n @extends {Int2} */" + "function Int3() {};" + "/** @interface */function Int4() {};" + "/** @type {Object} */" + "Int4.prototype.foo;" + "/** @type {Null} */" + "Int4.prototype.bar;" + "/** @interface \n @extends {Int3} \n @extends {Int4} */" + "function Int5() {};", new String[] { "Interface Int5 has a property bar with incompatible types in its" + " super interfaces Int1 and Int4", "Interface Int5 has a property foo with incompatible types in its" + " super interfaces Int0 and Int4"}); } public void testExtendedInterfacePropertiesCompatibility9() throws Exception { testTypes( "/** @interface\n * @template T */function Int0() {};" + "/** @interface\n * @template T */function Int1() {};" + "/** @type {T} */" + "Int0.prototype.foo;" + "/** @type {T} */" + "Int1.prototype.foo;" + "/** @interface \n @extends {Int0.<number>} \n @extends {Int1.<string>} */" + "function Int2() {};", "Interface Int2 has a property foo with incompatible types in its " + "super interfaces Int0.<number> and Int1.<string>"); } public void testGenerics1() throws Exception { String fnDecl = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( fnDecl + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( fnDecl + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( fnDecl + "var out;" + "/** @type {string} */" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); } public void testFilter0() throws Exception { testTypes( "/**\n" + " * @param {T} arr\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter1() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<string>} */" + "var result = filter(arr);"); } public void testFilter2() throws Exception { testTypes( "/**\n" + " * @param {!Array.<T>} arr\n" + " * @return {!Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {!Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testFilter3() throws Exception { testTypes( "/**\n" + " * @param {Array.<T>} arr\n" + " * @return {Array.<T>}\n" + " * @template T\n" + " */\n" + "var filter = function(arr){};\n" + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {Array.<number>} */" + "var result = filter(arr);", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testBackwardsInferenceGoogArrayFilter1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {Array.<string>} */" + "var arr;\n" + "/** @type {!Array.<number>} */" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {return false;});", "initializing variable\n" + "found : Array.<string>\n" + "required: Array.<number>"); } public void testBackwardsInferenceGoogArrayFilter2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {number} */" + "var out;" + "/** @type {Array.<string>} */" + "var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,src) {out = item;});", "assignment\n" + "found : string\n" + "required: number"); } public void testBackwardsInferenceGoogArrayFilter3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var result = goog.array.filter(" + " arr," + " function(item,index,src) {out = index;});", "assignment\n" + "found : number\n" + "required: string"); } public void testBackwardsInferenceGoogArrayFilter4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string} */" + "var out;" + "/** @type {Array.<string>} */ var arr;\n" + "var out4 = goog.array.filter(" + " arr," + " function(item,index,srcArr) {out = srcArr;});", "assignment\n" + "found : (null|{length: number})\n" + "required: string"); } public void testCatchExpression1() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " try {\n" + " foo();\n" + " } catch (/** @type {string} */ e) {\n" + " out = e;" + " }" + "}\n", "assignment\n" + "found : string\n" + "required: number"); } public void testCatchExpression2() throws Exception { testTypes( "function fn() {" + " /** @type {number} */" + " var out = 0;" + " /** @type {string} */" + " var e;" + " try {\n" + " foo();\n" + " } catch (e) {\n" + " out = e;" + " }" + "}\n"); } public void testTemplatized1() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = [];\n" + "/** @type {!Array.<number>} */" + "var arr2 = [];\n" + "arr1 = arr2;", "assignment\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testTemplatized3() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: (Array.<string>|null)"); } public void testTemplatized4() throws Exception { testTypes( "/** @type {Array.<string>} */" + "var arr1 = [];\n" + "/** @type {Array.<number>} */" + "var arr2 = arr1;\n", "initializing variable\n" + "found : (Array.<string>|null)\n" + "required: (Array.<number>|null)"); } public void testTemplatized5() throws Exception { testTypes( "/**\n" + " * @param {Object.<T>} obj\n" + " * @return {boolean|undefined}\n" + " * @template T\n" + " */\n" + "var some = function(obj) {" + " for (var key in obj) if (obj[key]) return true;" + "};" + "/** @return {!Array} */ function f() { return []; }" + "/** @return {!Array.<string>} */ function g() { return []; }" + "some(f());\n" + "some(g());\n"); } public void testTemplatized6() throws Exception { testTypes( "/** @interface */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "" + "/** @constructor \n" + " * @implements {I}\n" + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "" + "/** @type {null} */ var some = new C().method('str');", "initializing variable\n" + "found : string\n" + "required: null"); } public void testTemplatized7() throws Exception { testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @implements {I.<number>}\n" + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {null} */ var some = new C().method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void disable_testTemplatized8() throws Exception { // TODO(johnlenz): this should generate a warning but does not. testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @implements {I.<R>}\n" + " * @template R\n " + " */ function C(){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {C.<number>} var x = new C();" + "/** @type {null} */ var some = x.method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void testTemplatized9() throws Exception { testTypes( "/** @interface\n" + " * @template Q\n " + " */ function I(){}\n" + "/** @param {T} a\n" + " * @return {T|Q}\n" + " * @template T\n" + "*/\n" + "I.prototype.method;\n" + "/** @constructor \n" + " * @param {R} a\n" + " * @implements {I.<R>}\n" + " * @template R\n " + " */ function C(a){}\n" + "/** @override*/ C.prototype.method = function(a) {}\n" + "/** @type {null} */ var some = new C(1).method('str');", "initializing variable\n" + "found : (number|string)\n" + "required: null"); } public void testTemplatized10() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template T\n" + " */\n" + "function Parent() {};\n" + "\n" + "/** @param {T} x */\n" + "Parent.prototype.method = function(x) {};\n" + "\n" + "/**\n" + " * @constructor\n" + " * @extends {Parent.<string>}\n" + " */\n" + "function Child() {};\n" + "Child.prototype = new Parent();\n" + "\n" + "(new Child()).method(123); \n", "actual parameter 1 of Parent.prototype.method does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTemplatized11() throws Exception { testTypes( "/** \n" + " * @template T\n" + " * @constructor\n" + " */\n" + "function C() {}\n" + "\n" + "/**\n" + " * @param {T|K} a\n" + " * @return {T}\n" + " * @template K\n" + " */\n" + "C.prototype.method = function (a) {};\n" + "\n" + // method returns "?" "/** @type {void} */ var x = new C().method(1);"); } public void testIssue1058() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @template CLASS\n" + " */\n" + "var Class = function() {};\n" + "\n" + "/**\n" + " * @param {function(CLASS):CLASS} a\n" + " * @template T\n" + " */\n" + "Class.prototype.foo = function(a) {\n" + " return 'string';\n" + "};\n" + "\n" + "/** @param {number} a\n" + " * @return {string} */\n" + "var a = function(a) { return '' };\n" + "\n" + "new Class().foo(a);"); } public void testUnknownTypeReport() throws Exception { compiler.getOptions().setWarningLevel(DiagnosticGroups.REPORT_UNKNOWN_TYPES, CheckLevel.WARNING); testTypes("function id(x) { return x; }", "could not determine the type of this expression"); } public void testUnknownTypeDisabledByDefault() throws Exception { testTypes("function id(x) { return x; }"); } public void testTemplatizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testNonexistentPropertyAccessOnStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A"); } public void testNonexistentPropertyAccessOnStructOrObject() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};\n" + "/** @param {A|Object} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}"); } public void testNonexistentPropertyAccessOnExternStruct() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};", "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "var A = function() {};" + "" + "/**\n" + " * @constructor\n" + " * @struct\n" + " * @extends {A}\n" + " */\n" + "var B = function() { this.bar = function(){}; };" + "" + "/** @param {A} a */\n" + "function foo(a) {\n" + " if (a.bar) { a.bar(); }\n" + "}", "Property bar never defined on A", false); } public void testNonexistentPropertyAccessStructSubtype2() throws Exception { testTypes( "/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {\n" + " this.x = 123;\n" + "}\n" + "var objlit = /** @struct */ { y: 234 };\n" + "Foo.prototype = objlit;\n" + "var n = objlit.x;\n", "Property x never defined on Foo.prototype", false); } public void testIssue1024() throws Exception { testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = '__proto'\n" + "}\n" + "/** @param {Object} b\n" + " * @return {!Object}\n" + " */\n" + "function g(b) {\n" + " return b.prototype\n" + "}\n"); /* TODO(blickly): Make this warning go away. * This is old behavior, but it doesn't make sense to warn about since * both assignments are inferred. */ testTypes( "/** @param {Object} a */\n" + "function f(a) {\n" + " a.prototype = {foo:3};\n" + "}\n" + "/** @param {Object} b\n" + " */\n" + "function g(b) {\n" + " b.prototype = function(){};\n" + "}\n", "assignment to property prototype of Object\n" + "found : {foo: number}\n" + "required: function (): undefined"); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { testClosureTypesMultipleWarnings(js, description == null ? null : Lists.newArrayList(description)); } private void testClosureTypesMultipleWarnings( String js, List<String> descriptions) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, false) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals( "unexpected error(s) : " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); if (descriptions == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), descriptions.size(), compiler.getWarningCount()); Set<String> actualWarningDescriptions = Sets.newHashSet(); for (int i = 0; i < descriptions.size(); i++) { actualWarningDescriptions.add(compiler.getWarnings()[i].description); } assertEquals( Sets.newHashSet(descriptions), actualWarningDescriptions); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(SourceFile.fromCode("[externs]", externs)), Lists.newArrayList(SourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler); Node externsNode = compiler.getInput(new InputId("[externs]")) .getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); // create a parent node for the extern and source blocks new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); }
com.google.javascript.jscomp.TypeCheckTest::testFunctionArguments16
test/com/google/javascript/jscomp/TypeCheckTest.java
1,367
test/com/google/javascript/jscomp/TypeCheckTest.java
testFunctionArguments16
/* * Copyright 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; /** * Tests {@link TypeCheck}. * * * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, new DefaultCodingConvention()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ foo()--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck7() throws Exception { testTypes("function foo() {delete 'abc';}", TypeCheck.BAD_DELETE); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Parse error. variable length argument must be " + "last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return number */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return string */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return string */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return boolean */" + "function f(b) { if (u()) { b = null; } return b; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return string */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return number*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateLocalVarDecl() throws Exception { testTypes( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", "variable x redefined with type string, " + "original definition at [testcode]:2 with type number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (this:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { /** TODO(user): This is not exactly correct yet. The var itself is nullable. */ testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE). restrictByNotNullOrUndefined().toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (this:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (this:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testTypes("/** @enum */var a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum9() throws Exception { testTypes( "var goog = {};" + "/** @enum */goog.a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (this:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Parse error. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Parse error. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Parse error. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "goog.asserts = {};" + "/** @return {*} */ goog.asserts.assert = function(x) { return x; };" + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return number */goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return number */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return number*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return !Date */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return number */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return boolean*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return number */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Parse error. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Parse error. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/* @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (this:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return Array */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return string */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return string */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Parse error. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes("/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n"); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface2() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testTypes( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", "Parse error. Cycle detected in inheritance chain of type T"); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Parse error. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { // To better support third-party code, we do not warn when // there are no braces around an unknown type name. testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return x; }", null); } public void testForwardTypeDeclaration2() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }" + "f(3);", null); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testMalformedOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testMalformedOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @typedef {boolean} */ goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testDuplicateOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @constructor */ goog.Bar = function() {};" + "/** @type {number} */ goog.Bar = goog.typedef", "variable goog.Bar redefined with type number, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testOldTypeDef1() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testOldTypeDef3() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ var Bar = goog.typedef;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number|Array.<goog.Bar>} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() {});", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format(), true); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format(), true); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format(), true); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (description == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals(1, compiler.getWarningCount()); assertEquals(description, compiler.getWarnings()[0].description); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput("[testcode]").getAstRoot(compiler); Node externsNode = compiler.getInput("[externs]").getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
// You are a professional Java test case writer, please create a test case named `testFunctionArguments16` for the issue `Closure-229`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-229 // // ## Issue-Title: // Missing type-checks for var_args notation // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile this: // //------------------------------------- // // ==ClosureCompiler== // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @warning\_level VERBOSE // // @output\_file\_name default.js // // @formatting pretty\_print // // ==/ClosureCompiler== // // /\*\* // \* @param {...string} var\_args // \*/ // function foo(var\_args) { // return arguments.length; // } // // foo('hello'); // no warning - ok // foo(123); // warning - ok // foo('hello', 123); // no warning! error. // //------------------------------------- // // **What is the expected output? What do you see instead?** // Should get a type-mismatch warning for the second parameter in the third foo() call. // // **What version of the product are you using? On what operating system?** // Both online compiler and the 20100616 release. // // **Please provide any additional information below.** // Seems like the type-checker treats 'var\_args' as a single param and thus fails to type check the subsequent parameters. // // // Fredrik // // public void testFunctionArguments16() throws Exception {
1,367
96
1,360
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-229 ## Issue-Title: Missing type-checks for var_args notation ## Issue-Description: **What steps will reproduce the problem?** 1. Compile this: //------------------------------------- // ==ClosureCompiler== // @compilation\_level SIMPLE\_OPTIMIZATIONS // @warning\_level VERBOSE // @output\_file\_name default.js // @formatting pretty\_print // ==/ClosureCompiler== /\*\* \* @param {...string} var\_args \*/ function foo(var\_args) { return arguments.length; } foo('hello'); // no warning - ok foo(123); // warning - ok foo('hello', 123); // no warning! error. //------------------------------------- **What is the expected output? What do you see instead?** Should get a type-mismatch warning for the second parameter in the third foo() call. **What version of the product are you using? On what operating system?** Both online compiler and the 20100616 release. **Please provide any additional information below.** Seems like the type-checker treats 'var\_args' as a single param and thus fails to type check the subsequent parameters. // Fredrik ``` You are a professional Java test case writer, please create a test case named `testFunctionArguments16` for the issue `Closure-229`, utilizing the provided issue report information and the following function signature. ```java public void testFunctionArguments16() throws Exception { ```
1,360
[ "com.google.javascript.jscomp.TypeCheck" ]
fcf4538a3fb1a01fee7c72f543d330094297e2c53d09a9b21c6c2f805e4372c6
public void testFunctionArguments16() throws Exception
// You are a professional Java test case writer, please create a test case named `testFunctionArguments16` for the issue `Closure-229`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-229 // // ## Issue-Title: // Missing type-checks for var_args notation // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile this: // //------------------------------------- // // ==ClosureCompiler== // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @warning\_level VERBOSE // // @output\_file\_name default.js // // @formatting pretty\_print // // ==/ClosureCompiler== // // /\*\* // \* @param {...string} var\_args // \*/ // function foo(var\_args) { // return arguments.length; // } // // foo('hello'); // no warning - ok // foo(123); // warning - ok // foo('hello', 123); // no warning! error. // //------------------------------------- // // **What is the expected output? What do you see instead?** // Should get a type-mismatch warning for the second parameter in the third foo() call. // // **What version of the product are you using? On what operating system?** // Both online compiler and the 20100616 release. // // **Please provide any additional information below.** // Seems like the type-checker treats 'var\_args' as a single param and thus fails to type check the subsequent parameters. // // // Fredrik // //
Closure
/* * Copyright 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.Scope.Var; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.FunctionType; import com.google.javascript.rhino.jstype.JSType; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.ObjectType; import java.util.Arrays; /** * Tests {@link TypeCheck}. * * * */ public class TypeCheckTest extends CompilerTypeTestCase { private CheckLevel reportMissingOverrides = CheckLevel.WARNING; public void setUp() throws Exception { super.setUp(); reportMissingOverrides = CheckLevel.WARNING; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, new DefaultCodingConvention()).createInitialScope( new Node(Token.BLOCK)); assertEquals(ARRAY_FUNCTION_TYPE, s.getVar("Array").getType()); assertEquals(BOOLEAN_OBJECT_FUNCTION_TYPE, s.getVar("Boolean").getType()); assertEquals(DATE_FUNCTION_TYPE, s.getVar("Date").getType()); assertEquals(ERROR_FUNCTION_TYPE, s.getVar("Error").getType()); assertEquals(EVAL_ERROR_FUNCTION_TYPE, s.getVar("EvalError").getType()); assertEquals(NUMBER_OBJECT_FUNCTION_TYPE, s.getVar("Number").getType()); assertEquals(OBJECT_FUNCTION_TYPE, s.getVar("Object").getType()); assertEquals(RANGE_ERROR_FUNCTION_TYPE, s.getVar("RangeError").getType()); assertEquals(REFERENCE_ERROR_FUNCTION_TYPE, s.getVar("ReferenceError").getType()); assertEquals(REGEXP_FUNCTION_TYPE, s.getVar("RegExp").getType()); assertEquals(STRING_OBJECT_FUNCTION_TYPE, s.getVar("String").getType()); assertEquals(SYNTAX_ERROR_FUNCTION_TYPE, s.getVar("SyntaxError").getType()); assertEquals(TYPE_ERROR_FUNCTION_TYPE, s.getVar("TypeError").getType()); assertEquals(URI_ERROR_FUNCTION_TYPE, s.getVar("URIError").getType()); } public void testTypeCheck1() throws Exception { testTypes("/**@return {void}*/function foo(){ if (foo()) return; }"); } public void testTypeCheck2() throws Exception { testTypes("/**@return {void}*/function foo(){ foo()--; }", "increment/decrement\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck4() throws Exception { testTypes("/**@return {void}*/function foo(){ !foo(); }"); } public void testTypeCheck5() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = +foo(); }", "sign operator\n" + "found : undefined\n" + "required: number"); } public void testTypeCheck6() throws Exception { testTypes( "/**@return {void}*/function foo(){" + "/** @type {undefined|number} */var a;if (a == foo())return;}"); } public void testTypeCheck7() throws Exception { testTypes("function foo() {delete 'abc';}", TypeCheck.BAD_DELETE); } public void testTypeCheck8() throws Exception { testTypes("/**@return {void}*/function foo(){do {} while (foo());}"); } public void testTypeCheck9() throws Exception { testTypes("/**@return {void}*/function foo(){while (foo());}"); } public void testTypeCheck10() throws Exception { testTypes("/**@return {void}*/function foo(){for (;foo(););}"); } public void testTypeCheck11() throws Exception { testTypes("/**@type !Number */var a;" + "/**@type !String */var b;" + "a = b;", "assignment\n" + "found : String\n" + "required: Number"); } public void testTypeCheck12() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = 3^foo();}", "bad right operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testTypeCheck13() throws Exception { testTypes("/**@type {!Number|!String}*/var i; i=/xx/;", "assignment\n" + "found : RegExp\n" + "required: (Number|String)"); } public void testTypeCheck14() throws Exception { testTypes("/**@param opt_a*/function foo(opt_a){}"); } public void testTypeCheck15() throws Exception { testTypes("/**@type {Number|null} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null)"); } public void testTypeCheck16() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null)"); } public void testTypeCheck17() throws Exception { testTypes("/**@return {Number}\n@param {Number} opt_foo */\n" + "function a(opt_foo){\nreturn /**@type {Number}*/(opt_foo);\n}"); } public void testTypeCheck18() throws Exception { testTypes("/**@return {RegExp}\n*/\n function a(){return new RegExp();}"); } public void testTypeCheck19() throws Exception { testTypes("/**@return {Array}\n*/\n function a(){return new Array();}"); } public void testTypeCheck20() throws Exception { testTypes("/**@return {Date}\n*/\n function a(){return new Date();}"); } public void testTypeCheckBasicDowncast() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {Object} */ var bar = new foo();\n"); } public void testTypeCheckNoDowncastToNumber() throws Exception { testTypes("/** @constructor */function foo() {}\n" + "/** @type {!Number} */ var bar = new foo();\n", "initializing variable\n" + "found : foo\n" + "required: Number"); } public void testTypeCheck21() throws Exception { testTypes("/** @type Array.<String> */var foo;"); } public void testTypeCheck22() throws Exception { testTypes("/** @param {Element|Object} p */\nfunction foo(p){}\n" + "/** @constructor */function Element(){}\n" + "/** @type {Element|Object} */var v;\n" + "foo(v);\n"); } public void testTypeCheck23() throws Exception { testTypes("/** @type {(Object,Null)} */var foo; foo = null;"); } public void testTypeCheck24() throws Exception { testTypes("/** @constructor */function MyType(){}\n" + "/** @type {(MyType,Null)} */var foo; foo = null;"); } public void testTypeCheckDefaultExterns() throws Exception { testTypes("/** @param {string} x */ function f(x) {}" + "f([].length);" , "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testTypeCheckCustomExterns() throws Exception { testTypes( DEFAULT_EXTERNS + "/** @type {boolean} */ Array.prototype.oogabooga;", "/** @param {string} x */ function f(x) {}" + "f([].oogabooga);" , "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: string", false); } public void testParameterizedArray1() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedArray2() throws Exception { testTypes("/** @param {!Array.<!Array.<number>>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : Array\n" + "required: number"); } public void testParameterizedArray3() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "* @return {number}\n" + "*/ var f = function(a) { a[1] = 0; return a[0]; };"); } public void testParameterizedArray4() throws Exception { testTypes("/** @param {!Array.<number>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };", "assignment\n" + "found : string\n" + "required: number"); } public void testParameterizedArray5() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "*/ var f = function(a) { a[0] = 'a'; };"); } public void testParameterizedArray6() throws Exception { testTypes("/** @param {!Array.<*>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : *\n" + "required: string"); } public void testParameterizedArray7() throws Exception { testTypes("/** @param {?Array.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject1() throws Exception { testTypes("/** @param {!Object.<number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a[0]; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject2() throws Exception { testTypes("/** @param {!Object.<string,number>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testParameterizedObject3() throws Exception { testTypes("/** @param {!Object.<number,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: number"); } public void testParameterizedObject4() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!Object.<E,string>} a\n" + "* @return {string}\n" + "*/ var f = function(a) { return a['x']; };", "restricted index type\n" + "found : string\n" + "required: E.<string>"); } public void testUnionOfFunctionAndType() throws Exception { testTypes("/** @type {null|(function(Number):void)} */ var a;" + "/** @type {(function(Number):void)|null} */ var b = null; a = b;"); } public void testOptionalParameterComparedToUndefined() throws Exception { testTypes("/**@param opt_a {Number}*/function foo(opt_a)" + "{if (opt_a==undefined) var b = 3;}"); } public void testOptionalAllType() throws Exception { testTypes("/** @param {*} opt_x */function f(opt_x) { return opt_x }\n" + "/** @type {*} */var y;\n" + "f(y);"); } public void testOptionalUnknownNamedType() throws Exception { testTypes("/** @param {!T} opt_x\n@return {undefined} */\n" + "function f(opt_x) { return opt_x; }\n" + "/** @constructor */var T = function() {};", "inconsistent return type\n" + "found : (T|undefined)\n" + "required: undefined"); } public void testOptionalArgFunctionParam() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a()};"); } public void testOptionalArgFunctionParam2() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionParam3() throws Exception { testTypes("/** @param {function(number=)} a */" + "function f(a) {a(undefined)};"); } public void testOptionalArgFunctionParam4() throws Exception { String expectedWarning = "Function a: called with 2 argument(s). " + "Function requires at least 0 argument(s) and no more than 1 " + "argument(s)."; testTypes("/** @param {function(number=)} a */function f(a) {a(3,4)};", expectedWarning, false); } public void testOptionalArgFunctionParamError() throws Exception { String expectedWarning = "Parse error. variable length argument must be " + "last"; testTypes("/** @param {function(...[number], number=)} a */" + "function f(a) {};", expectedWarning, false); } public void testOptionalNullableArgFunctionParam() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a()};"); } public void testOptionalNullableArgFunctionParam2() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(null)};"); } public void testOptionalNullableArgFunctionParam3() throws Exception { testTypes("/** @param {function(?number=)} a */" + "function f(a) {a(3)};"); } public void testOptionalArgFunctionReturn() throws Exception { testTypes("/** @return {function(number=)} */" + "function f() { return function(opt_x) { }; };" + "f()()"); } public void testOptionalArgFunctionReturn2() throws Exception { testTypes("/** @return {function(Object=)} */" + "function f() { return function(opt_x) { }; };" + "f()({})"); } public void testBooleanType() throws Exception { testTypes("/**@type {boolean} */var x = 1 < 2;"); } public void testBooleanReduction1() throws Exception { testTypes("/**@type {string} */var x; x = null || \"a\";"); } public void testBooleanReduction2() throws Exception { // It's important for the type system to recognize that in no case // can the boolean expression evaluate to a boolean value. testTypes("/** @param {string} s\n @return {string} */" + "(function(s) { return ((s == 'a') && s) || 'b'; })"); } public void testBooleanReduction3() throws Exception { testTypes("/** @param {string} s\n @return {string?} */" + "(function(s) { return s && null && 3; })"); } public void testBooleanReduction4() throws Exception { testTypes("/** @param {Object} x\n @return {Object} */" + "(function(x) { return null || x || null ; })"); } public void testBooleanReduction5() throws Exception { testTypes("/**\n" + "* @param {Array|string} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x || typeof x == 'string') {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction6() throws Exception { testTypes("/**\n" + "* @param {Array|string|null} x\n" + "* @return {string?}\n" + "*/\n" + "var f = function(x) {\n" + "if (!(x && typeof x != 'string')) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testBooleanReduction7() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/**\n" + "* @param {Array|T} x\n" + "* @return {null}\n" + "*/\n" + "var f = function(x) {\n" + "if (!x) {\n" + "return x;\n" + "}\n" + "return null;\n" + "};"); } public void testNullAnd() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x && x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testNullOr() throws Exception { testTypes("/** @type null */var x;\n" + "/** @type number */var r = x || x;", "initializing variable\n" + "found : null\n" + "required: number"); } public void testBooleanPreservation1() throws Exception { testTypes("/**@type {string} */var x = \"a\";" + "x = ((x == \"a\") && x) || x == \"b\";", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation2() throws Exception { testTypes("/**@type {string} */var x = \"a\"; x = (x == \"a\") || x;", "assignment\n" + "found : (boolean|string)\n" + "required: string"); } public void testBooleanPreservation3() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean?} */" + "function f(x) { return x && x == \"a\"; }"); } public void testBooleanPreservation4() throws Exception { testTypes("/** @param {Function?} x\n @return {boolean} */" + "function f(x) { return x && x == \"a\"; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testTypeOfReduction1() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x == 'number' ? String(x) : x; }"); } public void testTypeOfReduction2() throws Exception { testTypes("/** @param {string|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'string' ? String(x) : x; }"); } public void testTypeOfReduction3() throws Exception { testTypes("/** @param {number|null} x\n @return {number} */ " + "function f(x) { return typeof x == 'object' ? 1 : x; }"); } public void testTypeOfReduction4() throws Exception { testTypes("/** @param {Object|undefined} x\n @return {Object} */ " + "function f(x) { return typeof x == 'undefined' ? {} : x; }"); } public void testTypeOfReduction5() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {!E|number} x\n @return {string} */ " + "function f(x) { return typeof x != 'number' ? x : 'a'; }"); } public void testTypeOfReduction6() throws Exception { testTypes("/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return typeof x == 'string' && x.length == 3 ? x : 'a';\n" + "}"); } public void testTypeOfReduction7() throws Exception { testTypes("/** @return {string} */var f = function(x) { " + "return typeof x == 'number' ? x : 'a'; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testTypeOfReduction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {number|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isString(x) && x.length == 3 ? x : 'a';\n" + "}", null); } public void testTypeOfReduction9() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {!Array|string} x\n@return {string} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? 'a' : x;\n" + "}", null); } public void testTypeOfReduction10() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isArray(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction11() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {Array|string} x\n@return {Array} */\n" + "function f(x) {\n" + "return goog.isObject(x) ? x : [];\n" + "}", null); } public void testTypeOfReduction12() throws Exception { testTypes("/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n @return {Array} */ " + "function f(x) { return typeof x == 'object' ? x : []; }"); } public void testTypeOfReduction13() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @enum {string} */ var E = {A: 'a', B: 'b'};\n" + "/** @param {E|Array} x\n@return {Array} */ " + "function f(x) { return goog.isObject(x) ? x : []; }", null); } public void testTypeOfReduction14() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return goog.isString(arguments[0]) ? arguments[0] : 0;" + "}", null); } public void testTypeOfReduction15() throws Exception { // Don't do type inference on GETELEMs. testClosureTypes( CLOSURE_DEFS + "function f(arguments) { " + " return typeof arguments[0] == 'string' ? arguments[0] : 0;" + "}", null); } public void testQualifiedNameReduction1() throws Exception { testTypes("var x = {}; /** @type {string?} */ x.a = 'a';\n" + "/** @return {string} */ var f = function() {\n" + "return x.a ? x.a : 'a'; }"); } public void testQualifiedNameReduction2() throws Exception { testTypes("/** @param {string?} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return this.a ? this.a : 'a'; }"); } public void testQualifiedNameReduction3() throws Exception { testTypes("/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return typeof this.a == 'string' ? this.a : 'a'; }"); } public void testQualifiedNameReduction4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @param {string|Array} a\n@constructor */ var T = " + "function(a) {this.a = a};\n" + "/** @return {string} */ T.prototype.f = function() {\n" + "return goog.isString(this.a) ? this.a : 'a'; }", null); } public void testInstanceOfReduction1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T|string} x\n@return {T} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return x; } else { return new T(); }\n" + "};"); } public void testInstanceOfReduction2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {!T|string} x\n@return {string} */\n" + "var f = function(x) {\n" + "if (x instanceof T) { return ''; } else { return x; }\n" + "};"); } public void testPropertyInferredPropagation() throws Exception { testTypes("/** @return {Object} */function f() { return {}; }\n" + "function g() { var x = f(); if (x.p) x.a = 'a'; else x.a = 'b'; }\n" + "function h() { var x = f(); x.a = false; }"); } public void testPropertyInference1() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference2() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = null; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference3() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : (boolean|number)\n" + "required: string"); } public void testPropertyInference4() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyInference5() throws Exception { testTypes( "/** @constructor */ function F() { }" + "F.prototype.baz = function() { this.x_ = 3; };" + "/** @return {string} */" + "F.prototype.bar = function() { if (this.x_) return this.x_; };"); } public void testPropertyInference6() throws Exception { testTypes( "/** @constructor */ function F() { }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };"); } public void testPropertyInference7() throws Exception { testTypes( "/** @constructor */ function F() { this.x_ = true; }" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "inconsistent return type\n" + "found : boolean\n" + "required: string"); } public void testPropertyInference8() throws Exception { testTypes( "/** @constructor */ function F() { " + " /** @type {string} */ this.x_ = 'x';" + "}" + "(new F).x_ = 3;" + "/** @return {string} */" + "F.prototype.bar = function() { return this.x_; };", "assignment to property x_ of F\n" + "found : number\n" + "required: string"); } public void testNoPersistentTypeInferenceForObjectProperties() throws Exception { testTypes("/** @param {Object} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Object} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Object} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testNoPersistentTypeInferenceForFunctionProperties() throws Exception { testTypes("/** @param {Function} o\n@param {string} x */\n" + "function s1(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {string} */\n" + "function g1(o) { return typeof o.x == 'undefined' ? '' : o.x; }\n" + "/** @param {Function} o\n@param {number} x */\n" + "function s2(o,x) { o.x = x; }\n" + "/** @param {Function} o\n@return {number} */\n" + "function g2(o) { return typeof o.x == 'undefined' ? 0 : o.x; }"); } public void testObjectPropertyTypeInferredInLocalScope1() throws Exception { testTypes("/** @param {!Object} o\n@return {string} */\n" + "function f(o) { o.x = 1; return o.x; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope2() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { o.x = 'a';\nif (x) {o.x = x;}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testObjectPropertyTypeInferredInLocalScope3() throws Exception { testTypes("/**@param {!Object} o\n@param {number?} x\n@return {string}*/" + "function f(o, x) { if (x) {o.x = x;} else {o.x = 'a';}\nreturn o.x; }", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty1() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x = 0;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty2() throws Exception { testTypes("/** @constructor */var T = function() { this.x = ''; };\n" + "/** @type {number} */ T.prototype.x;", "assignment to property x of T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty3() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testMismatchingOverridingInferredPropertyBeforeDeclaredProperty4() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() { this.x = ''; };\n" + "/** @type {number} */ n.T.prototype.x = 0;", "assignment to property x of n.T\n" + "found : string\n" + "required: number"); } public void testPropertyUsedBeforeDefinition1() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @return {string} */" + "T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testPropertyUsedBeforeDefinition2() throws Exception { testTypes("var n = {};\n" + "/** @constructor */ n.T = function() {};\n" + "/** @return {string} */" + "n.T.prototype.f = function() { return this.g(); };\n" + "/** @return {number} */ n.T.prototype.g = function() { return 1; };\n", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testAdd1() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 'abc'+foo();}"); } public void testAdd2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()+4;}"); } public void testAdd3() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd4() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {string} */ var c = a + b;"); } public void testAdd5() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;"); } public void testAdd6() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;"); } public void testAdd7() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {string} */ var b = 'b';" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd8() throws Exception { testTypes("/** @type {string} */ var a = 'a';" + "/** @type {number} */ var b = 5;" + "/** @type {number} */ var c = a + b;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd9() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {number} */ var b = 5;" + "/** @type {string} */ var c = a + b;", "initializing variable\n" + "found : number\n" + "required: string"); } public void testAdd10() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {string} */ var c = a + d.e.f;"); } public void testAdd11() throws Exception { // d.e.f will have unknown type. testTypes( suppressMissingProperty("e", "f") + "/** @type {number} */ var a = 5;" + "/** @type {number} */ var c = a + d.e.f;"); } public void testAdd12() throws Exception { testTypes("/** @return {(number,string)} */ function a() { return 5; }" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a() + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd13() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd14() throws Exception { testTypes("/** @type {(null,string)} */ var a = null;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd15() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @return {(number,string)} */ function b() { return 5; }" + "/** @type {boolean} */ var c = a + b();", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd16() throws Exception { testTypes("/** @type {(undefined,string)} */ var a = undefined;" + "/** @type {number} */ var b = 5;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd17() throws Exception { testTypes("/** @type {number} */ var a = 5;" + "/** @type {(undefined,string)} */ var b = undefined;" + "/** @type {boolean} */ var c = a + b;", "initializing variable\n" + "found : (number|string)\n" + "required: boolean"); } public void testAdd18() throws Exception { testTypes("function f() {};" + "/** @type {string} */ var a = 'a';" + "/** @type {number} */ var c = a + f();", "initializing variable\n" + "found : string\n" + "required: number"); } public void testAdd19() throws Exception { testTypes("/** @param {number} opt_x\n@param {number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd20() throws Exception { testTypes("/** @param {!Number} opt_x\n@param {!Number} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testAdd21() throws Exception { testTypes("/** @param {Number|Boolean} opt_x\n" + "@param {number|boolean} opt_y\n" + "@return {number} */ function f(opt_x, opt_y) {" + "return opt_x + opt_y;}"); } public void testNumericComparison1() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison2() throws Exception { testTypes("/**@param {!Object} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : Object\n" + "required: number"); } public void testNumericComparison3() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 3;}"); } public void testNumericComparison4() throws Exception { testTypes("/**@param {(number,undefined)} a*/ " + "function f(a) {return a < 3;}"); } public void testNumericComparison5() throws Exception { testTypes("/**@param {*} a*/ function f(a) {return a < 3;}", "left side of numeric comparison\n" + "found : *\n" + "required: number"); } public void testNumericComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if (3 >= foo()) return; }", "right side of numeric comparison\n" + "found : undefined\n" + "required: number"); } public void testStringComparison1() throws Exception { testTypes("/**@param {string} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison2() throws Exception { testTypes("/**@param {Object} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison3() throws Exception { testTypes("/**@param {number} a*/ function f(a) {return a < 'x';}"); } public void testStringComparison4() throws Exception { testTypes("/**@param {string|undefined} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison5() throws Exception { testTypes("/**@param {*} a*/ " + "function f(a) {return a < 'x';}"); } public void testStringComparison6() throws Exception { testTypes("/**@return void*/ function foo() { if ('a' >= foo()) return; }", "right side of comparison\n" + "found : undefined\n" + "required: string"); } public void testValueOfComparison1() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {!O} b*/ function f(a,b) { return a < b; }"); } public void testValueOfComparison2() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.valueOf = function() { return 1; };" + "/**@param {!O} a\n@param {number} b*/" + "function f(a,b) { return a < b; }"); } public void testValueOfComparison3() throws Exception { testTypes("/** @constructor */function O() {};" + "/**@override*/O.prototype.toString = function() { return 'o'; };" + "/**@param {!O} a\n@param {string} b*/" + "function f(a,b) { return a < b; }"); } public void testGenericRelationalExpression() throws Exception { testTypes("/**@param {*} a\n@param {*} b*/ " + "function f(a,b) {return a < b;}"); } public void testInstanceof1() throws Exception { testTypes("function foo(){" + "if (bar instanceof 3)return;}", "instanceof requires an object\n" + "found : number\n" + "required: Object"); } public void testInstanceof2() throws Exception { testTypes("/**@return {void}*/function foo(){" + "if (foo() instanceof Object)return;}", "deterministic instanceof yields false\n" + "found : undefined\n" + "required: NoObject"); } public void testInstanceof3() throws Exception { testTypes("/**@return {*} */function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof4() throws Exception { testTypes("/**@return {(Object|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceof5() throws Exception { // No warning for unknown types. testTypes("/** @return {?} */ function foo(){" + "if (foo() instanceof Object)return;}"); } public void testInstanceof6() throws Exception { testTypes("/**@return {(Array|number)} */function foo(){" + "if (foo() instanceof Object)return 3;}"); } public void testInstanceOfReduction3() throws Exception { testTypes( "/** \n" + " * @param {Object} x \n" + " * @param {Function} y \n" + " * @return {boolean} \n" + " */\n" + "var f = function(x, y) {\n" + " return x instanceof y;\n" + "};"); } public void testScoping1() throws Exception { testTypes( "/**@param {string} a*/function foo(a){" + " /**@param {Array|string} a*/function bar(a){" + " if (a instanceof Array)return;" + " }" + "}"); } public void testScoping2() throws Exception { testTypes( "/** @type number */ var a;" + "function Foo() {" + " /** @type string */ var a;" + "}"); } public void testScoping3() throws Exception { testTypes("\n\n/** @type{Number}*/var b;\n/** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:3 with type (Number|null)"); } public void testScoping4() throws Exception { testTypes("/** @type{Number}*/var b; if (true) /** @type{!String} */var b;", "variable b redefined with type String, original " + "definition at [testcode]:1 with type (Number|null)"); } public void testScoping5() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; var b;"); } public void testScoping6() throws Exception { // multiple definitions are not checked by the type checker but by a // subsequent pass testTypes("if (true) var b; if (true) var b;"); } public void testScoping7() throws Exception { testTypes("/** @constructor */function A() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of A\n" + "found : null\n" + "required: A"); } public void testScoping8() throws Exception { testTypes("/** @constructor */function A() {}" + "/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping9() throws Exception { testTypes("/** @constructor */function B() {" + " /** @type !A */this.a = null;" + "}" + "/** @constructor */function A() {}", "assignment to property a of B\n" + "found : null\n" + "required: A"); } public void testScoping10() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = function b(){};"); // a declared, b is not assertTrue(p.scope.isDeclared("a", false)); assertFalse(p.scope.isDeclared("b", false)); // checking that a has the correct assigned type assertEquals("function (): undefined", p.scope.getVar("a").getType().toString()); } public void testScoping11() throws Exception { // named function expressions create a binding in their body only // the return is wrong but the assignment is ok since the type of b is ? testTypes( "/** @return number */var a = function b(){ return b };", "inconsistent return type\n" + "found : function (): number\n" + "required: number"); } public void testFunctionArguments1() throws Exception { testFunctionType( "/** @param {number} a\n@return string */" + "function f(a) {}", "function (number): string"); } public void testFunctionArguments2() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(opt_a) {}", "function ((number|undefined)): string"); } public void testFunctionArguments3() throws Exception { testFunctionType( "/** @param {number} b\n@return string */" + "function f(a,b) {}", "function (?, number): string"); } public void testFunctionArguments4() throws Exception { testFunctionType( "/** @param {number} opt_a\n@return string */" + "function f(a,opt_a) {}", "function (?, (number|undefined)): string"); } public void testFunctionArguments5() throws Exception { testTypes( "function a(opt_a,a) {}", "optional arguments must be at the end"); } public void testFunctionArguments6() throws Exception { testTypes( "function a(var_args,a) {}", "variable length argument must be last"); } public void testFunctionArguments7() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(a,opt_a,var_args) {}"); } public void testFunctionArguments8() throws Exception { testTypes( "function a(a,opt_a,var_args,b) {}", "variable length argument must be last"); } public void testFunctionArguments9() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,var_args,b,c) {}", "variable length argument must be last"); } public void testFunctionArguments10() throws Exception { // testing that only one error is reported testTypes( "function a(a,opt_a,b,c) {}", "optional arguments must be at the end"); } public void testFunctionArguments11() throws Exception { testTypes( "function a(a,opt_a,b,c,var_args,d) {}", "optional arguments must be at the end"); } public void testFunctionArguments12() throws Exception { testTypes("/** @param foo {String} */function bar(baz){}", "parameter foo does not appear in bar's parameter list"); } public void testFunctionArguments13() throws Exception { // verifying that the argument type have inferable types testTypes( "/** @return {boolean} */ function u() { return true; }" + "/** @param {boolean} b\n@return boolean */" + "function f(b) { if (u()) { b = null; } return b; }", "inconsistent return type\n" + "found : (boolean|null)\n" + "required: boolean"); } public void testFunctionArguments14() throws Exception { testTypes( "/**\n" + " * @param {string} x\n" + " * @param {number} opt_y\n" + " * @param {boolean} var_args\n" + " */ function f(x, opt_y, var_args) {}" + "f('3'); f('3', 2); f('3', 2, true); f('3', 2, true, false);"); } public void testFunctionArguments15() throws Exception { testTypes( "/** @param {?function(*)} f */" + "function g(f) { f(1, 2); }", "Function f: called with 2 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionArguments16() throws Exception { testTypes( "/** @param {...number} var_args */" + "function g(var_args) {} g(1, true);", "actual parameter 2 of g does not match formal parameter\n" + "found : boolean\n" + "required: (number|undefined)"); } public void testPrintFunctionName1() throws Exception { // Ensures that the function name is pretty. testTypes( "var goog = {}; goog.run = function(f) {};" + "goog.run();", "Function goog.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testPrintFunctionName2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {}; " + "Foo.prototype.run = function(f) {};" + "(new Foo).run();", "Function Foo.prototype.run: called with 0 argument(s). " + "Function requires at least 1 argument(s) " + "and no more than 1 argument(s)."); } public void testFunctionInference1() throws Exception { testFunctionType( "function f(a) {}", "function (?): undefined"); } public void testFunctionInference2() throws Exception { testFunctionType( "function f(a,b) {}", "function (?, ?): undefined"); } public void testFunctionInference3() throws Exception { testFunctionType( "function f(var_args) {}", "function (...[?]): undefined"); } public void testFunctionInference4() throws Exception { testFunctionType( "function f(a,b,c,var_args) {}", "function (?, ?, ?, ...[?]): undefined"); } public void testFunctionInference5() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(a) {}", "function (this:Date, ?): string"); } public void testFunctionInference6() throws Exception { testFunctionType( "/** @this Date\n@return string */function f(opt_a) {}", "function (this:Date, ?): string"); } public void testFunctionInference7() throws Exception { testFunctionType( "/** @this Date */function f(a,b,c,var_args) {}", "function (this:Date, ?, ?, ?, ...[?]): undefined"); } public void testFunctionInference8() throws Exception { testFunctionType( "function f() {}", "function (): undefined"); } public void testFunctionInference9() throws Exception { testFunctionType( "var f = function() {};", "function (): undefined"); } public void testFunctionInference10() throws Exception { testFunctionType( "/** @this Date\n@param {boolean} b\n@return string */" + "var f = function(a,b) {};", "function (this:Date, ?, boolean): string"); } public void testFunctionInference11() throws Exception { testFunctionType( "var goog = {};" + "/** @return number*/goog.f = function(){};", "goog.f", "function (): number"); } public void testFunctionInference12() throws Exception { testFunctionType( "var goog = {};" + "goog.f = function(){};", "goog.f", "function (): undefined"); } public void testFunctionInference13() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @param {!goog.Foo} f */function eatFoo(f){};", "eatFoo", "function (goog.Foo): undefined"); } public void testFunctionInference14() throws Exception { testFunctionType( "var goog = {};" + "/** @constructor */ goog.Foo = function(){};" + "/** @return {!goog.Foo} */function eatFoo(){ return new goog.Foo; };", "eatFoo", "function (): goog.Foo"); } public void testFunctionInference15() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "f.prototype.foo", "function (this:f): undefined"); } public void testFunctionInference16() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "f.prototype.foo = function(){};", "(new f).foo", "function (this:f): undefined"); } public void testFunctionInference17() throws Exception { testFunctionType( "/** @constructor */ function f() {}" + "function abstractMethod() {}" + "/** @param {number} x */ f.prototype.foo = abstractMethod;", "(new f).foo", "function (this:f, number): ?"); } public void testFunctionInference18() throws Exception { testFunctionType( "var goog = {};" + "/** @this {Date} */ goog.eatWithDate;", "goog.eatWithDate", "function (this:Date): ?"); } public void testFunctionInference19() throws Exception { testFunctionType( "/** @param {string} x */ var f;", "f", "function (string): ?"); } public void testFunctionInference20() throws Exception { testFunctionType( "/** @this {Date} */ var f;", "f", "function (this:Date): ?"); } public void testInnerFunction1() throws Exception { testTypes( "function f() {" + " /** @type {number} */ var x = 3;\n" + " function g() { x = null; }" + " return x;" + "}", "assignment\n" + "found : null\n" + "required: number"); } public void testInnerFunction2() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = null;\n" + " function g() { x = 3; }" + " g();" + " return x;" + "}", "inconsistent return type\n" + "found : (null|number)\n" + "required: number"); } public void testInnerFunction3() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = 3;\n" + " /** @return {number} */\n" + " function g() { x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction4() throws Exception { testTypes( "var x = null;" + "/** @return {number} */\n" + "function f() {" + " x = '3';\n" + " /** @return {number} */\n" + " function g() { x = 3; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testInnerFunction5() throws Exception { testTypes( "/** @return {number} */\n" + "function f() {" + " var x = 3;\n" + " /** @return {number} */" + " function g() { var x = 3;x = true; return x; }" + " return x;" + "}", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testInnerFunction6() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", null); } public void testInnerFunction7() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " /** @type {number|function()} */" + " var x = 0 || function() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction8() throws Exception { testClosureTypes( CLOSURE_DEFS + "function f() {" + " function x() {};\n" + " function g() { if (goog.isFunction(x)) { x(1); } }" + " g();" + "}", "Function x: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testInnerFunction9() throws Exception { testTypes( "function f() {" + " var x = 3;\n" + " function g() { x = null; };\n" + " function h() { return x == null; }" + " return h();" + "}"); } public void testAbstractMethodHandling1() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "abstractFn(1);"); } public void testAbstractMethodHandling2() throws Exception { testTypes( "var abstractFn = function() {};" + "abstractFn(1);", "Function abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling3() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "goog.abstractFn(1);"); } public void testAbstractMethodHandling4() throws Exception { testTypes( "var goog = {};" + "goog.abstractFn = function() {};" + "goog.abstractFn(1);", "Function goog.abstractFn: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testAbstractMethodHandling5() throws Exception { testTypes( "/** @type {Function} */ var abstractFn = function() {};" + "/** @param {number} x */ var f = abstractFn;" + "f('x');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testAbstractMethodHandling6() throws Exception { testTypes( "var goog = {};" + "/** @type {Function} */ goog.abstractFn = function() {};" + "/** @param {number} x */ goog.f = abstractFn;" + "goog.f('x');", "actual parameter 1 of goog.f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testMethodInference1() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @return {number} */ F.prototype.foo = function() { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference2() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.F = function() {};" + "/** @return {number} */ goog.F.prototype.foo = " + " function() { return 3; };" + "/** @constructor \n * @extends {goog.F} */ " + "goog.G = function() {};" + "/** @override */ goog.G.prototype.foo = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference3() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(x) { return x; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference4() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {boolean} x \n * @return {number} */ " + "F.prototype.foo = function(x) { return 3; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(y) { return y; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testMethodInference5() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x \n * @return {string} */ " + "F.prototype.foo = function(x) { return 'x'; };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @type {number} */ G.prototype.num = 3;" + "/** @override */ " + "G.prototype.foo = function(y) { return this.num + y; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testMethodInference6() throws Exception { testTypes( "/** @constructor */ function F() {}" + "/** @param {number} x */ F.prototype.foo = function(x) { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function() { };" + "(new G()).foo(1);", "Function G.prototype.foo: called with 1 argument(s). " + "Function requires at least 0 argument(s) " + "and no more than 0 argument(s)."); } public void testMethodInference7() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ G.prototype.foo = function(x, y) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 2 argument(s) " + "and no more than 2 argument(s)."); } public void testMethodInference8() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, opt_b, var_args) { };" + "(new G()).foo();", "Function G.prototype.foo: called with 0 argument(s). " + "Function requires at least 1 argument(s)."); } public void testMethodInference9() throws Exception { testTypes( "/** @constructor */ function F() {}" + "F.prototype.foo = function() { };" + "/** @constructor \n * @extends {F} */ " + "function G() {}" + "/** @override */ " + "G.prototype.foo = function(a, var_args, opt_b) { };", "variable length argument must be last"); } public void testStaticMethodDeclaration1() throws Exception { testTypes( "/** @constructor */ function F() { F.foo(true); }" + "/** @param {number} x */ F.foo = function(x) {};", "actual parameter 1 of F.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration2() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "/** @param {number} x */ goog.foo = function(x) {};", "actual parameter 1 of goog.foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testStaticMethodDeclaration3() throws Exception { testTypes( "var goog = goog || {}; function f() { goog.foo(true); }" + "goog.foo = function() {};", "Function goog.foo: called with 1 argument(s). Function requires " + "at least 0 argument(s) and no more than 0 argument(s)."); } public void testDuplicateStaticMethodDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (number): undefined, " + "original definition at [testcode]:1 with type function (number): undefined"); } public void testDuplicateStaticMethodDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {number} x */ goog.foo = function(x) {};" + "/** @param {number} x \n * @suppress {duplicate} */ " + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl3() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Function} */ goog.foo = function(x) {};" + "goog.foo = function(x) {};"); } public void testDuplicateStaticMethodDecl5() throws Exception { testTypes( "var goog = goog || {};" + "goog.foo = function(x) {};" + "/** @return {undefined} */ goog.foo = function(x) {};", "variable goog.foo redefined with type function (?): undefined, " + "original definition at [testcode]:1 with type " + "function (?): undefined"); } public void testDuplicateStaticPropertyDecl1() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl2() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {Foo} */ goog.foo;" + "/** @type {Foo} \n * @suppress {duplicate} */ goog.foo;" + "/** @constructor */ function Foo() {}"); } public void testDuplicateStaticPropertyDecl3() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo;" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl4() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl5() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {!Foo} */ goog.foo;" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';" + "/** @constructor */ function Foo() {}", "variable goog.foo redefined with type string, " + "original definition at [testcode]:1 with type Foo"); } public void testDuplicateStaticPropertyDecl6() throws Exception { testTypes( "var goog = goog || {};" + "/** @type {string} */ goog.foo = 'y';" + "/** @type {string}\n * @suppress {duplicate} */ goog.foo = 'x';"); } public void testDuplicateStaticPropertyDecl7() throws Exception { testTypes( "var goog = goog || {};" + "/** @param {string} x */ goog.foo;" + "/** @type {function(string)} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl8() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}" + "/** @return {EventCopy} */ goog.foo;"); } public void testDuplicateStaticPropertyDecl9() throws Exception { testTypes( "var goog = goog || {};" + "/** @return {EventCopy} */ goog.foo;" + "/** @return {EventCopy} */ goog.foo;" + "/** @constructor */ function EventCopy() {}"); } public void testDuplicateLocalVarDecl() throws Exception { testTypes( "/** @param {number} x */\n" + "function f(x) { /** @type {string} */ var x = ''; }", "variable x redefined with type string, " + "original definition at [testcode]:2 with type number"); } public void testStubFunctionDeclaration1() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @param {number} x \n * @param {string} y \n" + " * @return {number} */ f.prototype.foo;", "(new f).foo", "function (this:f, number, string): number"); } public void testStubFunctionDeclaration2() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @constructor \n * @extends {f} */ f.subclass;", "f.subclass", "function (this:f.subclass): ?"); } public void testStubFunctionDeclaration3() throws Exception { testFunctionType( "/** @constructor */ function f() {};" + "/** @return {undefined} */ f.foo;", "f.foo", "function (): undefined"); } public void testStubFunctionDeclaration4() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @return {number} */ this.foo;" + "}", "(new f).foo", "function (this:f): number"); } public void testStubFunctionDeclaration5() throws Exception { testFunctionType( "/** @constructor */ function f() { " + " /** @type {Function} */ this.foo;" + "}", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createNullableType(U2U_CONSTRUCTOR_TYPE).toString()); } public void testStubFunctionDeclaration8() throws Exception { /** TODO(user): This is not exactly correct yet. The var itself is nullable. */ testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createNullableType(U2U_CONSTRUCTOR_TYPE). restrictByNotNullOrUndefined().toString()); } public void testStubFunctionDeclaration9() throws Exception { testFunctionType( "/** @type {function():number} */ var f; ", "f", "function (): number"); } public void testStubFunctionDeclaration10() throws Exception { testFunctionType( "/** @type {function(number):number} */ var f = function(x) {};", "f", "function (number): number"); } public void testNestedFunctionInference1() throws Exception { String nestedAssignOfFooAndBar = "/** @constructor */ function f() {};" + "f.prototype.foo = f.prototype.bar = function(){};"; testFunctionType(nestedAssignOfFooAndBar, "(new f).bar", "function (this:f): undefined"); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code "f"}. */ private void testFunctionType(String functionDef, String functionType) throws Exception { testFunctionType(functionDef, "f", functionType); } /** * Tests the type of a function definition. The function defined by * {@code functionDef} should be named {@code functionName}. */ private void testFunctionType(String functionDef, String functionName, String functionType) throws Exception { // using the variable initialization check to verify the function's type testTypes( functionDef + "/** @type number */var a=" + functionName + ";", "initializing variable\n" + "found : " + functionType + "\n" + "required: number"); } public void testTypeRedefinition() throws Exception { testTypes("a={};/**@enum {string}*/ a.A = {ZOR:'b'};" + "/** @constructor */ a.A = function() {}", "variable a.A redefined with type function (this:a.A): undefined, " + "original definition at [testcode]:1 with type enum{a.A}"); } public void testIn1() throws Exception { testTypes("'foo' in Object"); } public void testIn2() throws Exception { testTypes("3 in Object"); } public void testIn3() throws Exception { testTypes("undefined in Object"); } public void testIn4() throws Exception { testTypes("Date in Object", "left side of 'in'\n" + "found : function (this:Date, ?, ?, ?, ?, ?, ?, ?): string\n" + "required: string"); } public void testIn5() throws Exception { testTypes("'x' in null", "'in' requires an object\n" + "found : null\n" + "required: Object"); } public void testIn6() throws Exception { testTypes( "/** @param {number} x */" + "function g(x) {}" + "g(1 in {});", "actual parameter 1 of g does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testIn7() throws Exception { // Make sure we do inference in the 'in' expression. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " return g(x.foo) in {};" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } // TODO(nicksantos): change this to something that makes sense. // public void testComparison1() throws Exception { // testTypes("/**@type null */var a;" + // "/**@type !Date */var b;" + // "if (a==b) {}", // "condition always evaluates to false\n" + // "left : null\n" + // "right: Date"); // } public void testComparison2() throws Exception { testTypes("/**@type number*/var a;" + "/**@type !Date */var b;" + "if (a!==b) {}", "condition always evaluates to the same value\n" + "left : number\n" + "right: Date"); } public void testComparison3() throws Exception { // Since null == undefined in JavaScript, this code is reasonable. testTypes("/** @type {(Object,undefined)} */var a;" + "var b = a == null"); } public void testComparison4() throws Exception { testTypes("/** @type {(!Object,undefined)} */var a;" + "/** @type {!Object} */var b;" + "var c = a == b"); } public void testComparison5() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a == b", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testComparison6() throws Exception { testTypes("/** @type null */var a;" + "/** @type null */var b;" + "a != b", "condition always evaluates to false\n" + "left : null\n" + "right: null"); } public void testComparison7() throws Exception { testTypes("var a;" + "var b;" + "a == b", "condition always evaluates to true\n" + "left : undefined\n" + "right: undefined"); } public void testComparison8() throws Exception { testTypes("/** @type {Array.<string>} */ var a = [];" + "a[0] == null || a[1] == undefined"); } public void testComparison9() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] == null", "condition always evaluates to true\n" + "left : undefined\n" + "right: null"); } public void testComparison10() throws Exception { testTypes("/** @type {Array.<undefined>} */ var a = [];" + "a[0] === null"); } public void testEnumStaticMethod1() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "Foo.method(true);", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnumStaticMethod2() throws Exception { testTypes( "/** @enum */ var Foo = {AAA: 1};" + "/** @param {number} x */ Foo.method = function(x) {};" + "function f() { Foo.method(true); }", "actual parameter 1 of Foo.method does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testEnum1() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n" + "/**@type {a}*/var d;d=a.BB;"); } public void testEnum2() throws Exception { testTypes("/**@enum*/var a={b:1}", "enum key b must be a syntactic constant"); } public void testEnum3() throws Exception { testTypes("/**@enum*/var a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum4() throws Exception { testTypes("/**@enum*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum5() throws Exception { testTypes("/**@enum {String}*/var a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: (String|null)"); } public void testEnum6() throws Exception { testTypes("/**@enum*/var a={BB:1,CC:2};\n/**@type {!Array}*/var d;d=a.BB;", "assignment\n" + "found : a.<number>\n" + "required: Array"); } public void testEnum7() throws Exception { testTypes("/** @enum */var a={AA:1,BB:2,CC:3};" + "/** @type a */var b=a.D;", "element D does not exist on this enum"); } public void testEnum8() throws Exception { testTypes("/** @enum */var a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum9() throws Exception { testTypes( "var goog = {};" + "/** @enum */goog.a=8;", "enum initializer must be an object literal or an enum"); } public void testEnum10() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { A : 3 };"); } public void testEnum11() throws Exception { testTypes( "/** @enum {number} */" + "goog.K = { 502 : 3 };"); } public void testEnum12() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum */ var b = a;"); } public void testEnum13() throws Exception { testTypes( "/** @enum {number} */ var a = {};" + "/** @enum {string} */ var b = a;", "incompatible enum element types\n" + "found : number\n" + "required: string"); } public void testEnum14() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.FOO;"); } public void testEnum15() throws Exception { testTypes( "/** @enum {number} */ var a = {FOO:5};" + "/** @enum */ var b = a;" + "var c = b.BAR;", "element BAR does not exist on this enum"); } public void testEnum16() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:1,BB:2}", "enum element BB already defined", true); } public void testEnum17() throws Exception { testTypes("var goog = {};" + "/**@enum*/goog.a={BB:'string'}", "element type must match enum's type\n" + "found : string\n" + "required: number"); } public void testEnum18() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {!E} x\n@return {number} */\n" + "var f = function(x) { return x; };"); } public void testEnum19() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {number} x\n@return {!E} */\n" + "var f = function(x) { return x; };", "inconsistent return type\n" + "found : number\n" + "required: E.<number>"); } public void testEnum20() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2}; var x = []; x[E.A] = 0;"); } public void testEnum21() throws Exception { Node n = parseAndTypeCheck( "/** @enum {string} */ var E = {A : 'a', B : 'b'};\n" + "/** @param {!E} x\n@return {!E} */ function f(x) { return x; }"); Node nodeX = n.getLastChild().getLastChild().getLastChild().getLastChild(); JSType typeE = nodeX.getJSType(); assertFalse(typeE.isObject()); assertFalse(typeE.isNullable()); } public void testEnum22() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum23() throws Exception { testTypes("/**@enum*/ var E = {A: 1, B: 2};" + "/** @param {E} x \n* @return {string} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<number>\n" + "required: string"); } public void testEnum24() throws Exception { testTypes("/**@enum {Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}", "inconsistent return type\n" + "found : E.<(Object|null)>\n" + "required: Object"); } public void testEnum25() throws Exception { testTypes("/**@enum {!Object} */ var E = {A: {}};" + "/** @param {E} x \n* @return {!Object} */ function f(x) {return x}"); } public void testEnum26() throws Exception { testTypes("var a = {}; /**@enum*/ a.B = {A: 1, B: 2};" + "/** @param {a.B} x \n* @return {number} */ function f(x) {return x}"); } public void testEnum27() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A == x; }"); } public void testEnum28() throws Exception { // x is unknown testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "function f(x) { return A.B == x; }"); } public void testEnum29() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: number"); } public void testEnum30() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {number} */ function f() { return A.B; }"); } public void testEnum31() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A; }", "inconsistent return type\n" + "found : enum{A}\n" + "required: A.<number>"); } public void testEnum32() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @return {A} */ function f() { return A.B; }"); } public void testEnum34() throws Exception { testTypes("/** @enum */ var A = {B: 1, C: 2}; " + "/** @param {number} x */ function f(x) { return x == A.B; }"); } public void testEnum35() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {a.b} */ function f() { return a.b.C; }"); } public void testEnum36() throws Exception { testTypes("var a = a || {}; /** @enum */ a.b = {C: 1, D: 2};" + "/** @return {!a.b} */ function f() { return 1; }", "inconsistent return type\n" + "found : number\n" + "required: a.b.<number>"); } public void testEnum37() throws Exception { testTypes( "var goog = goog || {};" + "/** @enum {number} */ goog.a = {};" + "/** @enum */ var b = goog.a;"); } public void testEnum38() throws Exception { testTypes( "/** @enum {MyEnum} */ var MyEnum = {};" + "/** @param {MyEnum} x */ function f(x) {}", "Parse error. Cycle detected in inheritance chain " + "of type MyEnum"); } public void testEnum39() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {MyEnum} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testEnum40() throws Exception { testTypes( "/** @enum {Number} */ var MyEnum = {FOO: new Number(1)};" + "/** @param {number} x \n * @return {number} */" + "function f(x) { return x == MyEnum.FOO && MyEnum.FOO == x; }", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testAliasedEnum1() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum2() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(MyEnum.FOO);"); } public void testAliasedEnum3() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {MyEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum4() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {YourEnum} x */ function f(x) {} f(YourEnum.FOO);"); } public void testAliasedEnum5() throws Exception { testTypes( "/** @enum */ var YourEnum = {FOO: 3};" + "/** @enum */ var MyEnum = YourEnum;" + "/** @param {string} x */ function f(x) {} f(MyEnum.FOO);", "actual parameter 1 of f does not match formal parameter\n" + "found : YourEnum.<number>\n" + "required: string"); } public void testBackwardsEnumUse1() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};"); } public void testBackwardsEnumUse2() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var MyEnum = {FOO: 'x'};", "inconsistent return type\n" + "found : MyEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse3() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;"); } public void testBackwardsEnumUse4() throws Exception { testTypes( "/** @return {number} */ function f() { return MyEnum.FOO; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "inconsistent return type\n" + "found : YourEnum.<string>\n" + "required: number"); } public void testBackwardsEnumUse5() throws Exception { testTypes( "/** @return {string} */ function f() { return MyEnum.BAR; }" + "/** @enum {string} */ var YourEnum = {FOO: 'x'};" + "/** @enum {string} */ var MyEnum = YourEnum;", "element BAR does not exist on this enum"); } public void testBackwardsConstructor1() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = function(x) {};", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testBackwardsConstructor2() throws Exception { testTypes( "function f() { (new Foo(true)); }" + "/** \n * @constructor \n * @param {number} x */" + "var YourFoo = function(x) {};" + "/** \n * @constructor \n * @param {number} x */" + "var Foo = YourFoo;", "actual parameter 1 of Foo does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testMinimalConstructorAnnotation() throws Exception { testTypes("/** @constructor */function Foo(){}"); } public void testGoodExtends1() throws Exception { // A minimal @extends example testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends2() throws Exception { testTypes("/** @constructor\n * @extends base */function derived() {}\n" + "/** @constructor */function base() {}\n"); } public void testGoodExtends3() throws Exception { testTypes("/** @constructor\n * @extends {Object} */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n"); } public void testGoodExtends4() throws Exception { // Ensure that @extends actually sets the base type of a constructor // correctly. Because this isn't part of the human-readable Function // definition, we need to crawl the prototype chain (eww). Node n = parseAndTypeCheck( "var goog = {};\n" + "/** @constructor */goog.Base = function(){};\n" + "/** @constructor\n" + " * @extends {goog.Base} */goog.Derived = function(){};\n"); Node subTypeName = n.getLastChild().getLastChild().getFirstChild(); assertEquals("goog.Derived", subTypeName.getQualifiedName()); FunctionType subCtorType = (FunctionType) subTypeName.getNext().getJSType(); assertEquals("goog.Derived", subCtorType.getInstanceType().toString()); JSType superType = subCtorType.getPrototype().getImplicitPrototype(); assertEquals("goog.Base", superType.toString()); } public void testGoodExtends5() throws Exception { // we allow for the extends annotation to be placed first testTypes("/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n"); } public void testGoodExtends6() throws Exception { testFunctionType( CLOSURE_DEFS + "/** @constructor */function base() {}\n" + "/** @return {number} */ " + " base.prototype.foo = function() { return 1; };\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "goog.inherits(derived, base);", "derived.superClass_.foo", "function (this:base): number"); } public void testGoodExtends7() throws Exception { testFunctionType( "Function.prototype.inherits = function(x) {};" + "/** @constructor */function base() {}\n" + "/** @extends {base}\n * @constructor */function derived() {}\n" + "derived.inherits(base);", "(new derived).constructor", "function (this:derived): undefined"); } public void testGoodExtends8() throws Exception { testTypes("/** @constructor \n @extends {Base} */ function Sub() {}" + "/** @return {number} */ function f() { return (new Sub()).foo; }" + "/** @constructor */ function Base() {}" + "/** @type {boolean} */ Base.prototype.foo = true;", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testGoodExtends9() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "Super.prototype.foo = function() {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @override */ Sub.prototype.foo = function() {};"); } public void testGoodExtends10() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "/** @return {Super} */ function foo() { return new Sub(); }"); } public void testGoodExtends11() throws Exception { testTypes( "/** @constructor */ function Super() {}" + "/** @param {boolean} x */ Super.prototype.foo = function(x) {};" + "/** @constructor \n * @extends {Super} */ function Sub() {}" + "Sub.prototype = new Super();" + "(new Sub()).foo(0);", "actual parameter 1 of Super.prototype.foo " + "does not match formal parameter\n" + "found : number\n" + "required: boolean"); } public void testBadExtends1() throws Exception { testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {not_base} */function derived() {}\n", "Parse error. Unknown type not_base"); } public void testBadExtends2() throws Exception { testTypes("/** @constructor */function base() {\n" + "/** @type {!Number}*/\n" + "this.baseMember = new Number(4);\n" + "}\n" + "/** @constructor\n" + " * @extends {base} */function derived() {}\n" + "/** @param {!String} x*/\n" + "function foo(x){ }\n" + "/** @type {!derived}*/var y;\n" + "foo(y.baseMember);\n", "actual parameter 1 of foo does not match formal parameter\n" + "found : Number\n" + "required: String"); } public void testBadExtends3() throws Exception { testTypes("/** @extends {Object} */function base() {}", "@extends used without @constructor or @interface for base"); } public void testLateExtends() throws Exception { testTypes( CLOSURE_DEFS + "/** @constructor */ function Foo() {}\n" + "Foo.prototype.foo = function() {};\n" + "/** @constructor */function Bar() {}\n" + "goog.inherits(Foo, Bar);\n", "Missing @extends tag on type Foo"); } public void testSuperclassMatch() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n"); } public void testSuperclassMatchWithMixin() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor */ var Baz = function() {};\n" + "/** @constructor \n @extends Foo */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.mixin = function(y){};" + "Bar.inherits(Foo);\n" + "Bar.mixin(Baz);\n"); } public void testSuperclassMismatch1() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function() {};\n" + "/** @constructor \n @extends Object */ var Bar = function() {};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);\n", "Missing @extends tag on type Bar"); } public void testSuperclassMismatch2() throws Exception { compiler.getOptions().setCodingConvention(new GoogleCodingConvention()); testTypes("/** @constructor */ var Foo = function(){};\n" + "/** @constructor */ var Bar = function(){};\n" + "Bar.inherits = function(x){};" + "Bar.inherits(Foo);", "Missing @extends tag on type Bar"); } public void testSuperClassDefinedAfterSubClass1() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @constructor */ function Base() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }"); } public void testSuperClassDefinedAfterSubClass2() throws Exception { testTypes( "/** @constructor \n * @extends {Base} */ function A() {}" + "/** @constructor \n * @extends {Base} */ function B() {}" + "/** @param {A|B} x \n * @return {B|A} */ " + "function foo(x) { return x; }" + "/** @constructor */ function Base() {}"); } public void testDirectPrototypeAssignment1() throws Exception { testTypes( "/** @constructor */ function Base() {}" + "Base.prototype.foo = 3;" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "/** @return {string} */ function foo() { return (new A).foo; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testDirectPrototypeAssignment2() throws Exception { // This ensures that we don't attach property 'foo' onto the Base // instance object. testTypes( "/** @constructor */ function Base() {}" + "/** @constructor \n * @extends {Base} */ function A() {}" + "A.prototype = new Base();" + "A.prototype.foo = 3;" + "/** @return {string} */ function foo() { return (new Base).foo; }"); } public void testGoodImplements1() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @constructor */function f() {}"); } public void testGoodImplements2() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {Base1}\n" + " * @implements {Base2}\n" + " */ function derived() {}"); } public void testGoodImplements3() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n * @interface */function f() {}"); } public void testBadImplements1() throws Exception { testTypes("/** @interface */function Base1() {}\n" + "/** @interface */function Base2() {}\n" + "/** @constructor\n" + " * @implements {nonExistent}\n" + " * @implements {Base2}\n" + " */ function derived() {}", "Parse error. Unknown type nonExistent"); } public void testBadImplements2() throws Exception { testTypes("/** @interface */function Disposable() {}\n" + "/** @implements {Disposable}\n */function f() {}", "@implements used without @constructor or @interface for f"); } public void testInterfaceExtends() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}\n" + "/** @constructor\n" + " * @implements {B}\n" + " */ function derived() {}"); } public void testBadInterfaceExtends1() throws Exception { testTypes("/** @interface \n * @extends {nonExistent} */function A() {}", "Parse error. Unknown type nonExistent"); } public void testBadInterfaceExtends2() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @interface \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends3() throws Exception { testTypes("/** @interface */function A() {}\n" + "/** @constructor \n * @extends {A} */function B() {}", "B cannot extend this type; a constructor can only extend objects " + "and an interface can only extend interfaces"); } public void testBadInterfaceExtends4() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @interface */function A() {}\n" + "/** @constructor */function B() {}\n" + "B.prototype = A;"); } public void testBadInterfaceExtends5() throws Exception { // TODO(user): This should be detected as an error. Even if we enforce // that A cannot be used in the assignment, we should still detect the // inheritance chain as invalid. testTypes("/** @constructor */function A() {}\n" + "/** @interface */function B() {}\n" + "B.prototype = A;"); } public void testBadImplementsAConstructor() throws Exception { testTypes("/** @constructor */function A() {}\n" + "/** @constructor \n * @implements {A} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonInterfaceType() throws Exception { testTypes("/** @constructor \n * @implements {Boolean} */function B() {}", "can only implement interfaces"); } public void testBadImplementsNonObjectType() throws Exception { testTypes("/** @constructor \n * @implements {string} */function S() {}", "can only implement interfaces"); } public void testInterfaceAssignment1() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;"); } public void testInterfaceAssignment2() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor */var T = function() {};\n" + "var t = new T();\n" + "/** @type {!I} */var i = t;", "initializing variable\n" + "found : T\n" + "required: I"); } public void testInterfaceAssignment3() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I|number} */var i = t;"); } public void testInterfaceAssignment4() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1|I2} */var i = t;"); } public void testInterfaceAssignment5() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1}\n@implements {I2}*/" + "var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n"); } public void testInterfaceAssignment6() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I1} */var T = function() {};\n" + "/** @type {!I1} */var i1 = new T();\n" + "/** @type {!I2} */var i2 = i1;\n", "initializing variable\n" + "found : I1\n" + "required: I2"); } public void testInterfaceAssignment7() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface\n@extends {I1}*/var I2 = function() {};\n" + "/** @constructor\n@implements {I2}*/var T = function() {};\n" + "var t = new T();\n" + "/** @type {I1} */var i1 = t;\n" + "/** @type {I2} */var i2 = t;\n" + "i1 = i2;\n"); } public void testInterfaceAssignment8() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @type {I} */var i;\n" + "/** @type {Object} */var o = i;"); } public void testInterfaceAssignment9() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @return {I?} */function f() { return null; }\n" + "/** @type {!I} */var i = f();\n", "initializing variable\n" + "found : (I|null)\n" + "required: I"); } public void testInterfaceAssignment10() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor\n@implements {I2} */var T = function() {};\n" + "/** @return {!I1|!I2} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2)\n" + "required: I1"); } public void testInterfaceAssignment11() throws Exception { testTypes("/** @interface */var I1 = function() {};\n" + "/** @interface */var I2 = function() {};\n" + "/** @constructor */var T = function() {};\n" + "/** @return {!I1|!I2|!T} */function f() { return new T(); }\n" + "/** @type {!I1} */var i1 = f();\n", "initializing variable\n" + "found : (I1|I2|T)\n" + "required: I1"); } public void testInterfaceAssignment12() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements{I}*/var T1 = function() {};\n" + "/** @constructor\n@extends {T1}*/var T2 = function() {};\n" + "/** @return {I} */function f() { return new T2(); }"); } public void testInterfaceAssignment13() throws Exception { testTypes("/** @interface */var I = function() {};\n" + "/** @constructor\n@implements {I}*/var T = function() {};\n" + "/** @constructor */function Super() {};\n" + "/** @return {I} */Super.prototype.foo = " + "function() { return new T(); };\n" + "/** @constructor\n@extends {Super} */function Sub() {}\n" + "/** @override\n@return {T} */Sub.prototype.foo = " + "function() { return new T(); };\n"); } public void testGetprop1() throws Exception { testTypes("/** @return {void}*/function foo(){foo().bar;}", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess1() throws Exception { testTypes("var a = []; var b = a['hi'];"); } public void testArrayAccess2() throws Exception { testTypes("var a = []; var b = a[[1,2]];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess3() throws Exception { testTypes("var bar = [];" + "/** @return {void} */function baz(){};" + "var foo = bar[baz()];", "array access\n" + "found : undefined\n" + "required: number"); } public void testArrayAccess4() throws Exception { testTypes("/**@return {!Array}*/function foo(){};var bar = foo()[foo()];", "array access\n" + "found : Array\n" + "required: number"); } public void testArrayAccess6() throws Exception { testTypes("var bar = null[1];", "only arrays or objects can be accessed\n" + "found : null\n" + "required: Object"); } public void testArrayAccess7() throws Exception { testTypes("var bar = void 0; bar[0];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testArrayAccess8() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar[0]; bar[1];", "only arrays or objects can be accessed\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess() throws Exception { testTypes("/** @param {*} x */var f = function(x) {\n" + "var o = String(x);\n" + "if (typeof o['a'] != 'undefined') { return o['a']; }\n" + "return null;\n" + "};"); } public void testPropAccess2() throws Exception { testTypes("var bar = void 0; bar.baz;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess3() throws Exception { // Verifies that we don't emit two warnings, because // the var has been dereferenced after the first one. testTypes("var bar = void 0; bar.baz; bar.bax;", "undefined has no properties\n" + "found : undefined\n" + "required: Object"); } public void testPropAccess4() throws Exception { testTypes("/** @param {*} x */ function f(x) { return x['hi']; }"); } public void testSwitchCase1() throws Exception { testTypes("/**@type number*/var a;" + "/**@type string*/var b;" + "switch(a){case b:;}", "case expression doesn't match switch\n" + "found : string\n" + "required: number"); } public void testSwitchCase2() throws Exception { testTypes("var a = null; switch (typeof a) { case 'foo': }"); } public void testVar1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @type {(string,null)} */var a = null"); assertEquals(createUnionType(STRING_TYPE, NULL_TYPE), p.scope.getVar("a").getType()); } public void testVar2() throws Exception { testTypes("/** @type {Function} */ var a = function(){}"); } public void testVar3() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = 3;"); assertEquals(NUMBER_TYPE, p.scope.getVar("a").getType()); } public void testVar4() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var a = 3; a = 'string';"); assertEquals(createUnionType(STRING_TYPE, NUMBER_TYPE), p.scope.getVar("a").getType()); } public void testVar5() throws Exception { testTypes("var goog = {};" + "/** @type string */goog.foo = 'hello';" + "/** @type number */var a = goog.foo;", "initializing variable\n" + "found : string\n" + "required: number"); } public void testVar6() throws Exception { testTypes( "function f() {" + " return function() {" + " /** @type {!Date} */" + " var a = 7;" + " };" + "}", "initializing variable\n" + "found : number\n" + "required: Date"); } public void testVar7() throws Exception { testTypes("/** @type number */var a, b;", "declaration of multiple variables with shared type information"); } public void testVar8() throws Exception { testTypes("var a, b;"); } public void testVar9() throws Exception { testTypes("/** @enum */var a;", "enum initializer must be an object literal or an enum"); } public void testVar10() throws Exception { testTypes("/** @type !Number */var foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Number"); } public void testVar11() throws Exception { testTypes("var /** @type !Date */foo = 'abc';", "initializing variable\n" + "found : string\n" + "required: Date"); } public void testVar12() throws Exception { testTypes("var /** @type !Date */foo = 'abc', " + "/** @type !RegExp */bar = 5;", new String[] { "initializing variable\n" + "found : string\n" + "required: Date", "initializing variable\n" + "found : number\n" + "required: RegExp"}); } public void testVar13() throws Exception { // this caused an NPE testTypes("var /** @type number */a,a;"); } public void testVar14() throws Exception { testTypes("/** @return {number} */ function f() { var x; return x; }", "inconsistent return type\n" + "found : undefined\n" + "required: number"); } public void testVar15() throws Exception { testTypes("/** @return {number} */" + "function f() { var x = x || {}; return x; }", "inconsistent return type\n" + "found : {}\n" + "required: number"); } public void testAssign1() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign2() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 'hello';", "assignment to property foo of goog\n" + "found : string\n" + "required: number"); } public void testAssign3() throws Exception { testTypes("var goog = {};" + "/** @type number */goog.foo = 3;" + "goog.foo = 4;"); } public void testAssign4() throws Exception { testTypes("var goog = {};" + "goog.foo = 3;" + "goog.foo = 'hello';"); } public void testAssignInference() throws Exception { testTypes( "/**" + " * @param {Array} x" + " * @return {number}" + " */" + "function f(x) {" + " var y = null;" + " y = x[0];" + " if (y == null) { return 4; } else { return 6; }" + "}"); } public void testOr1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b || undefined;"); } public void testOr2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b || undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testOr3() throws Exception { testTypes("/** @type {(number, undefined)} */var a;" + "/** @type number */var c = a || 3;"); } /** * Test that type inference continues with the right side, * when no short-circuiting is possible. * See bugid 1205387 for more details. */ public void testOr4() throws Exception { testTypes("/**@type {number} */var x;x=null || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } /** * @see #testOr4() */ public void testOr5() throws Exception { testTypes("/**@type {number} */var x;x=undefined || \"a\";", "assignment\n" + "found : string\n" + "required: number"); } public void testAnd1() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "a + b && undefined;"); } public void testAnd2() throws Exception { testTypes("/** @type number */var a;" + "/** @type number */var b;" + "/** @type number */var c = a + b && undefined;", "initializing variable\n" + "found : (number|undefined)\n" + "required: number"); } public void testAnd3() throws Exception { testTypes("/** @type {(!Array, undefined)} */var a;" + "/** @type number */var c = a && undefined;", "initializing variable\n" + "found : undefined\n" + "required: number"); } public void testAnd4() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type null */var x; /** @type {number?} */var y;\n" + "if (x && y) { f(y) }"); } public void testAnd5() throws Exception { testTypes("/** @param {number} x\n@param {string} y*/function f(x,y){};\n" + "/** @type {number?} */var x; /** @type {string?} */var y;\n" + "if (x && y) { f(x, y) }"); } public void testAnd6() throws Exception { testTypes("/** @param {number} x */function f(x){};\n" + "/** @type {number|undefined} */var x;\n" + "if (x && f(x)) { f(x) }"); } public void testAnd7() throws Exception { // TODO(user): a deterministic warning should be generated for this // case since x && x is always false. The implementation of this requires // a more precise handling of a null value within a variable's type. // Currently, a null value defaults to ? which passes every check. testTypes("/** @type null */var x; if (x && x) {}"); } public void testHook() throws Exception { testTypes("/**@return {void}*/function foo(){ var x=foo()?a:b; }"); } public void testHookRestrictsType1() throws Exception { testTypes("/** @return {(string,null)} */" + "function f() { return null;}" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */" + "var b = a ? a : 'default';"); } public void testHookRestrictsType2() throws Exception { testTypes("/** @type {String} */" + "var a = null;" + "/** @type null */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type null */" + "var b = (!a) ? a : null;"); } public void testHookRestrictsType4() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type boolean */" + "var b = a != null ? a : true;"); } public void testHookRestrictsType5() throws Exception { testTypes("/** @type {(boolean,undefined)} */" + "var a;" + "/** @type {(undefined)} */" + "var b = a == null ? a : undefined;"); } public void testHookRestrictsType6() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == null ? 5 : a;"); } public void testHookRestrictsType7() throws Exception { testTypes("/** @type {(number,null,undefined)} */" + "var a;" + "/** @type {number} */" + "var b = a == undefined ? 5 : a;"); } public void testWhileRestrictsType1() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {number?} x */\n" + "function f(x) {\n" + "while (x) {\n" + "if (g(x)) { x = 1; }\n" + "x = x-1;\n}\n}", "actual parameter 1 of g does not match formal parameter\n" + "found : number\n" + "required: null"); } public void testWhileRestrictsType2() throws Exception { testTypes("/** @param {number?} x\n@return {number}*/\n" + "function f(x) {\n/** @type {number} */var y = 0;" + "while (x) {\n" + "y = x;\n" + "x = x-1;\n}\n" + "return y;}"); } public void testHigherOrderFunctions1() throws Exception { testTypes( "/** @type {function(number)} */var f;" + "f(true);", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testHigherOrderFunctions2() throws Exception { testTypes( "/** @type {function():!Date} */var f;" + "/** @type boolean */var a = f();", "initializing variable\n" + "found : Date\n" + "required: boolean"); } public void testHigherOrderFunctions3() throws Exception { testTypes( "/** @type {function(this:Error):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testHigherOrderFunctions4() throws Exception { testTypes( "/** @type {function(this:Error,...[number]):Date} */var f; new f", "cannot instantiate non-constructor"); } public void testConstructorAlias1() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias2() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias3() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @type {number} */ Foo.prototype.bar = 3;" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {string} */ function foo() { " + " return (new FooAlias()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias4() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "var FooAlias = Foo;" + "/** @type {number} */ FooAlias.prototype.bar = 3;" + "/** @return {string} */ function foo() { " + " return (new Foo()).bar; }", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testConstructorAlias5() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {FooAlias} */ function foo() { " + " return new Foo(); }"); } public void testConstructorAlias6() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {Foo} */ function foo() { " + " return new FooAlias(); }"); } public void testConstructorAlias7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias8() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/**\n * @param {number} x \n * @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias9() throws Exception { testTypes( "var goog = {};" + "/**\n * @param {number} x \n * @constructor */ goog.Foo = function(x) {};" + "/** @constructor */ goog.FooAlias = goog.Foo;" + "/** @return {number} */ function foo() { " + " return new goog.FooAlias(1); }", "inconsistent return type\n" + "found : goog.Foo\n" + "required: number"); } public void testConstructorAlias10() throws Exception { testTypes( "/**\n * @param {number} x \n * @constructor */ var Foo = function(x) {};" + "/** @constructor */ var FooAlias = Foo;" + "/** @return {number} */ function foo() { " + " return new FooAlias(1); }", "inconsistent return type\n" + "found : Foo\n" + "required: number"); } public void testClosure1() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = goog.isDef(a) ? a : 'default';", null); } public void testClosure2() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = goog.isNull(a) ? 'default' : a;", null); } public void testClosure3() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = goog.isDefAndNotNull(a) ? a : 'default';", null); } public void testClosure4() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDef(a) ? 'default' : a;", null); } public void testClosure5() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string?} */var a;" + "/** @type string */" + "var b = !goog.isNull(a) ? a : 'default';", null); } public void testClosure6() throws Exception { testClosureTypes( CLOSURE_DEFS + "/** @type {string|null|undefined} */var a;" + "/** @type string */" + "var b = !goog.isDefAndNotNull(a) ? 'default' : a;", null); } public void testClosure7() throws Exception { testClosureTypes( CLOSURE_DEFS + "goog.asserts = {};" + "/** @return {*} */ goog.asserts.assert = function(x) { return x; };" + "/** @type {string|null|undefined} */ var a = foo();" + "/** @type {number} */" + "var b = goog.asserts.assert(a);", "initializing variable\n" + "found : string\n" + "required: number"); } public void testReturn1() throws Exception { testTypes("/**@return {void}*/function foo(){ return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testReturn2() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return; }", "inconsistent return type\n" + "found : undefined\n" + "required: Number"); } public void testReturn3() throws Exception { testTypes("/**@return {!Number}*/function foo(){ return 'abc'; }", "inconsistent return type\n" + "found : string\n" + "required: Number"); } public void testReturn4() throws Exception { testTypes("/**@return {!Number}\n*/\n function a(){return new Array();}", "inconsistent return type\n" + "found : Array\n" + "required: Number"); } public void testReturn5() throws Exception { testTypes("/** @param {number} n\n" + "@constructor */function n(n){return};"); } public void testReturn6() throws Exception { testTypes( "/** @param {number} opt_a\n@return string */" + "function a(opt_a) { return opt_a }", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testReturn7() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testReturn8() throws Exception { testTypes("/** @constructor */var A = function() {};\n" + "/** @constructor */var B = function() {};\n" + "/** @return {!B} */A.prototype.f = function() { return 1; };", "inconsistent return type\n" + "found : number\n" + "required: B"); } public void testInferredReturn1() throws Exception { testTypes( "function f() {} /** @param {number} x */ function g(x) {}" + "g(f());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @param {number} x */ function g(x) {}" + "g((new Foo()).bar());", "actual parameter 1 of g does not match formal parameter\n" + "found : undefined\n" + "required: number"); } public void testInferredReturn3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() {}; " + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {number} \n * @override */ " + "SubFoo.prototype.bar = function() { return 3; }; ", "mismatch of the bar property type and the type of the property " + "it overrides from superclass Foo\n" + "original: function (this:Foo): undefined\n" + "override: function (this:SubFoo): number"); } public void testInferredReturn4() throws Exception { // By design, this throws a warning. if you want global x to be // defined to some other type of function, then you need to declare it // as a greater type. testTypes( "var x = function() {};" + "x = /** @type {function(): number} */ (function() { return 3; });", "assignment\n" + "found : function (): number\n" + "required: function (): undefined"); } public void testInferredReturn5() throws Exception { // If x is local, then the function type is not declared. testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " x = /** @type {function(): number} */ (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testInferredReturn6() throws Exception { testTypes( "/** @return {string} */" + "function f() {" + " var x = function() {};" + " if (f()) " + " x = /** @type {function(): number} */ " + " (function() { return 3; });" + " return x();" + "}", "inconsistent return type\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredReturn7() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "Foo.prototype.bar = function(x) { return 3; };", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredReturn8() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number} x */ SubFoo.prototype.bar = " + " function(x) { return 3; }", "inconsistent return type\n" + "found : number\n" + "required: undefined"); } public void testInferredParam1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @param {string} x */ function f(x) {}" + "Foo.prototype.bar = function(y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam2() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testInferredParam3() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam4() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {void} */ SubFoo.prototype.bar = " + " function(x) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam5() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {...number} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {...number} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(x); }; (new SubFoo()).bar();", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testInferredParam6() throws Exception { reportMissingOverrides = CheckLevel.OFF; testTypes( "/** @param {string} x */ function f(x) {}" + "/** @constructor */ function Foo() {}" + "/** @param {number=} x */ Foo.prototype.bar = function(x) {};" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @param {number=} x \n * @param {number=} y */ " + "SubFoo.prototype.bar = " + " function(x, y) { f(y); };", "actual parameter 1 of f does not match formal parameter\n" + "found : (number|undefined)\n" + "required: string"); } public void testOverriddenReturn1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {Object} */ Foo.prototype.bar = " + " function() { return {}; };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {SubFoo}\n * @override */ SubFoo.prototype.bar = " + " function() { return new Foo(); }", "inconsistent return type\n" + "found : Foo\n" + "required: (SubFoo|null)"); } public void testOverriddenReturn2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @return {SubFoo} */ Foo.prototype.bar = " + " function() { return new SubFoo(); };" + "/** @constructor \n * @extends {Foo} */ function SubFoo() {}" + "/** @return {Foo} x\n * @override */ SubFoo.prototype.bar = " + " function() { return new SubFoo(); }", "mismatch of the bar property type and the type of the " + "property it overrides from superclass Foo\n" + "original: function (this:Foo): (SubFoo|null)\n" + "override: function (this:SubFoo): (Foo|null)"); } public void testThis1() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){};" + "/** @return number */goog.A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: number"); } public void testThis2() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + "};" + "/** @return number */" + "goog.A.prototype.n = function() { return this.foo };", "inconsistent return type\n" + "found : null\n" + "required: number"); } public void testThis3() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " this.foo = null;" + " this.foo = 5;" + "};"); } public void testThis4() throws Exception { testTypes("var goog = {};" + "/** @constructor */goog.A = function(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */goog.A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis5() throws Exception { testTypes("/** @this Date\n@return number*/function h() { return this }", "inconsistent return type\n" + "found : Date\n" + "required: number"); } public void testThis6() throws Exception { testTypes("var goog = {};" + "/** @constructor\n@return !Date */" + "goog.A = function(){ return this };", "inconsistent return type\n" + "found : goog.A\n" + "required: Date"); } public void testThis7() throws Exception { testTypes("/** @constructor */function A(){};" + "/** @return number */A.prototype.n = function() { return this };", "inconsistent return type\n" + "found : A\n" + "required: number"); } public void testThis8() throws Exception { testTypes("/** @constructor */function A(){" + " /** @type {string?} */this.foo = null;" + "};" + "/** @return number */A.prototype.n = function() {" + " return this.foo };", "inconsistent return type\n" + "found : (null|string)\n" + "required: number"); } public void testThis9() throws Exception { // In A.bar, the type of {@code this} is unknown. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @return {string} */ A.bar = function() { return this.foo; };"); } public void testThis10() throws Exception { // In A.bar, the type of {@code this} is inferred from the @this tag. testTypes("/** @constructor */function A(){};" + "A.prototype.foo = 3;" + "/** @this {A}\n@return {string} */" + "A.bar = function() { return this.foo; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testGlobalThis1() throws Exception { testTypes("/** @constructor */ function Window() {}" + "/** @param {string} msg */ " + "Window.prototype.alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of Window.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis2() throws Exception { testTypes("/** @constructor */ function Bindow() {}" + "/** @param {string} msg */ " + "Bindow.prototype.alert = function(msg) {};" + "this.alert = 3;" + "(new Bindow()).alert(this.alert)", "actual parameter 1 of Bindow.prototype.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis3() throws Exception { testTypes( "/** @param {string} msg */ " + "function alert(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis4() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "this.alert(3);", "actual parameter 1 of this.alert " + "does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testGlobalThis5() throws Exception { testTypes( "function f() {" + " /** @param {string} msg */ " + " var alert = function(msg) {};" + "}" + "this.alert(3);", "Property alert never defined on this"); } public void testGlobalThis6() throws Exception { testTypes( "/** @param {string} msg */ " + "var alert = function(msg) {};" + "var x = 3;" + "x = 'msg';" + "this.alert(this.x);"); } public void testControlFlowRestrictsType1() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }" + "/** @type {String?} */ var a = f();" + "/** @type String */ var b = new String('foo');" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}"); } public void testControlFlowRestrictsType2() throws Exception { testTypes("/** @return {(string,null)} */ function f() { return null; }" + "/** @type {(string,null)} */ var a = f();" + "/** @type string */ var b = 'foo';" + "/** @type null */ var c = null;" + "if (a) {" + " b = a;" + "} else {" + " c = a;" + "}", "assignment\n" + "found : (null|string)\n" + "required: null"); } public void testControlFlowRestrictsType3() throws Exception { testTypes("/** @type {(string,void)} */" + "var a;" + "/** @type string */" + "var b = 'foo';" + "if (a) {" + " b = a;" + "}"); } public void testControlFlowRestrictsType4() throws Exception { testTypes("/** @param {string} a */ function f(a){}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);"); } public void testControlFlowRestrictsType5() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "a || f(a);"); } public void testControlFlowRestrictsType6() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType7() throws Exception { testTypes("/** @param {undefined} x */ function f(x) {}" + "/** @type {(string,undefined)} */ var a;" + "a && f(a);", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: undefined"); } public void testControlFlowRestrictsType8() throws Exception { testTypes("/** @param {undefined} a */ function f(a){}" + "/** @type {(!Array,undefined)} */ var a;" + "if (a || f(a)) {}"); } public void testControlFlowRestrictsType9() throws Exception { testTypes("/** @param {number?} x\n * @return {number}*/\n" + "var f = function(x) {\n" + "if (!x || x == 1) { return 1; } else { return x; }\n" + "};"); } public void testSwitchCase3() throws Exception { testTypes("/** @type String */" + "var a = new String('foo');" + "switch (a) { case 'A': }"); } public void testSwitchCase4() throws Exception { testTypes("/** @type {(string,Null)} */" + "var a = 'foo';" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase5() throws Exception { testTypes("/** @type {(String,Null)} */" + "var a = new String('foo');" + "switch (a) { case 'A':break; case null:break; }"); } public void testSwitchCase6() throws Exception { testTypes("/** @type {(Number,Null)} */" + "var a = new Number(5);" + "switch (a) { case 5:break; case null:break; }"); } public void testSwitchCase7() throws Exception { // This really tests the inference inside the case. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (3) { case g(x.foo): return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testSwitchCase8() throws Exception { // This really tests the inference inside the switch clause. testTypes( "/**\n" + " * @param {number} x\n" + " * @return {number}\n" + " */\n" + "function g(x) { return 5; }" + "function f() {" + " var x = {};" + " x.foo = '3';" + " switch (g(x.foo)) { case 3: return 3; }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNoTypeCheck1() throws Exception { testTypes("/** @notypecheck */function foo() { new 4 }"); } public void testNoTypeCheck2() throws Exception { testTypes("/** @notypecheck */var foo = function() { new 4 }"); } public void testNoTypeCheck3() throws Exception { testTypes("/** @notypecheck */var foo = function bar() { new 4 }"); } public void testNoTypeCheck4() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function() { new 4 }"); } public void testNoTypeCheck5() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function() { new 4 }"); } public void testNoTypeCheck6() throws Exception { testTypes("var foo;" + "/** @notypecheck */foo = function bar() { new 4 }"); } public void testNoTypeCheck7() throws Exception { testTypes("var foo;" + "foo = /** @notypecheck */function bar() { new 4 }"); } public void testNoTypeCheck8() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ var foo;" + "var bar = 3; /** @param {string} x */ function f(x) {} f(bar);"); } public void testNoTypeCheck9() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " /** @type {string} */ var a = 1", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck10() throws Exception { testTypes("/** @notypecheck */ function g() { }" + " function h() {/** @type {string} */ var a = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck11() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "/** @notypecheck */ function h() {/** @type {string} */ var a = 1}" ); } public void testNoTypeCheck12() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1}" ); } public void testNoTypeCheck13() throws Exception { testTypes("/** @notypecheck */ function g() { }" + "function h() {/** @type {string}\n * @notypecheck\n*/ var a = 1;" + "/** @type {string}*/ var b = 1}", "initializing variable\n" + "found : number\n" + "required: string" ); } public void testNoTypeCheck14() throws Exception { testTypes("/** @fileoverview \n * @notypecheck */ function g() { }" + "g(1,2,3)"); } public void testImplicitCast() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;", "(new Element).innerHTML = new Array();", null, false); } public void testImplicitCastSubclassAccess() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "/** @constructor \n @extends Element */" + "function DIVElement() {};", "(new DIVElement).innerHTML = new Array();", null, false); } public void testImplicitCastNotInExterns() throws Exception { testTypes("/** @constructor */ function Element() {};\n" + "/** @type {string}\n" + " * @implicitCast */" + "Element.prototype.innerHTML;" + "(new Element).innerHTML = new Array();", new String[] { "Illegal annotation on innerHTML. @implicitCast may only be " + "used in externs.", "assignment to property innerHTML of Element\n" + "found : Array\n" + "required: string"}); } public void testNumberNode() throws Exception { Node n = typeCheck(Node.newNumber(0)); assertEquals(NUMBER_TYPE, n.getJSType()); } public void testStringNode() throws Exception { Node n = typeCheck(Node.newString("hello")); assertEquals(STRING_TYPE, n.getJSType()); } public void testBooleanNodeTrue() throws Exception { Node trueNode = typeCheck(new Node(Token.TRUE)); assertEquals(BOOLEAN_TYPE, trueNode.getJSType()); } public void testBooleanNodeFalse() throws Exception { Node falseNode = typeCheck(new Node(Token.FALSE)); assertEquals(BOOLEAN_TYPE, falseNode.getJSType()); } public void testUndefinedNode() throws Exception { Node p = new Node(Token.ADD); Node n = Node.newString(Token.NAME, "undefined"); p.addChildToBack(n); p.addChildToBack(Node.newNumber(5)); typeCheck(p); assertEquals(VOID_TYPE, n.getJSType()); } public void testNumberAutoboxing() throws Exception { testTypes("/** @type Number */var a = 4;", "initializing variable\n" + "found : number\n" + "required: (Number|null)"); } public void testNumberUnboxing() throws Exception { testTypes("/** @type number */var a = new Number(4);", "initializing variable\n" + "found : Number\n" + "required: number"); } public void testStringAutoboxing() throws Exception { testTypes("/** @type String */var a = 'hello';", "initializing variable\n" + "found : string\n" + "required: (String|null)"); } public void testStringUnboxing() throws Exception { testTypes("/** @type string */var a = new String('hello');", "initializing variable\n" + "found : String\n" + "required: string"); } public void testBooleanAutoboxing() throws Exception { testTypes("/** @type Boolean */var a = true;", "initializing variable\n" + "found : boolean\n" + "required: (Boolean|null)"); } public void testBooleanUnboxing() throws Exception { testTypes("/** @type boolean */var a = new Boolean(false);", "initializing variable\n" + "found : Boolean\n" + "required: boolean"); } public void testIssue86() throws Exception { testTypes( "/** @interface */ function I() {}" + "/** @return {number} */ I.prototype.get = function(){};" + "/** @constructor \n * @implements {I} */ function F() {}" + "/** @override */ F.prototype.get = function() { return true; };", "inconsistent return type\n" + "found : boolean\n" + "required: number"); } public void testIssue124() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = 1;" + "}"); } public void testIssue124b() throws Exception { testTypes( "var t = null;" + "function test() {" + " if (t != null) { t = null; }" + " t = undefined;" + "}", "condition always evaluates to false\n" + "left : (null|undefined)\n" + "right: null"); } /** * Tests that the || operator is type checked correctly, that is of * the type of the first argument or of the second argument. See * bugid 592170 for more details. */ public void testBug592170() throws Exception { testTypes( "/** @param {Function} opt_f ... */" + "function foo(opt_f) {" + " /** @type {Function} */" + " return opt_f || function () {};" + "}"); } /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */ public void testBug901455() throws Exception { testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = undefined === a()"); testTypes("/** @return {(number,undefined)} */ function a() { return 3; }" + "var b = a() === undefined"); } /** * Tests that the match method of strings returns nullable arrays. */ public void testBug908701() throws Exception { testTypes("/** @type {String} */var s = new String('foo');" + "var b = s.match(/a/) != null;"); } /** * Tests that named types play nicely with subtyping. */ public void testBug908625() throws Exception { testTypes("/** @constructor */function A(){}" + "/** @constructor\n * @extends A */function B(){}" + "/** @param {B} b" + "\n @return {(A,undefined)} */function foo(b){return b}"); } /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception { // verifying the type assigned to function expressions assigned variables Scope s = parseAndTypeCheckWithScope("var a = function(){};").scope; JSType type = s.getVar("a").getType(); assertEquals("function (): undefined", type.toString()); // verifying the bug example testTypes("function nullFunction() {};" + "var foo = nullFunction;" + "foo = function() {};" + "foo();"); } public void testBug909000() throws Exception { testTypes("/** @constructor */function A(){}\n" + "/** @param {!A} a\n" + "@return boolean*/\n" + "function y(a) { return a }", "inconsistent return type\n" + "found : A\n" + "required: boolean"); } public void testBug930117() throws Exception { testTypes( "/** @param {boolean} x */function f(x){}" + "f(null);", "actual parameter 1 of f does not match formal parameter\n" + "found : null\n" + "required: boolean"); } public void testBug1484445() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (foo.bar == null && foo.baz == null) {" + " foo.bar;" + " }" + " }" + "}"); } public void testBug1859535() throws Exception { testTypes( "/**\n" + " * @param {Function} childCtor Child class.\n" + " * @param {Function} parentCtor Parent class.\n" + " */" + "var inherits = function(childCtor, parentCtor) {" + " /** @constructor */" + " function tempCtor() {};" + " tempCtor.prototype = parentCtor.prototype;" + " childCtor.superClass_ = parentCtor.prototype;" + " childCtor.prototype = new tempCtor();" + " /** @override */ childCtor.prototype.constructor = childCtor;" + "};" + "/**" + " * @param {Function} constructor\n" + " * @param {Object} var_args\n" + " * @return {Object}\n" + " */" + "var factory = function(constructor, var_args) {" + " /** @constructor */" + " var tempCtor = function() {};" + " tempCtor.prototype = constructor.prototype;" + " var obj = new tempCtor();" + " constructor.apply(obj, arguments);" + " return obj;" + "};"); } public void testBug1940591() throws Exception { testTypes( "/** @type {Object} */" + "var a = {};\n" + "/** @type {number} */\n" + "a.name = 0;\n" + "/**\n" + " * @param {Function} x anything.\n" + " */\n" + "a.g = function(x) { x.name = 'a'; }"); } public void testBug1942972() throws Exception { testTypes( "var google = {\n"+ " gears: {\n" + " factory: {},\n" + " workerPool: {}\n" + " }\n" + "};\n" + "\n" + "google.gears = {factory: {}};\n"); } public void testBug1943776() throws Exception { testTypes( "/** @return {{foo: Array}} */" + "function bar() {" + " return {foo: []};" + "}"); } public void testBug1987544() throws Exception { testTypes( "/** @param {string} x */ function foo(x) {}" + "var duration;" + "if (true && !(duration = 3)) {" + " foo(duration);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testBug1940769() throws Exception { testTypes( "/** @return {!Object} */ " + "function proto(obj) { return obj.prototype; }" + "/** @constructor */ function Map() {}" + "/**\n" + " * @constructor\n" + " * @extends {Map}\n" + " */" + "function Map2() { Map.call(this); };" + "Map2.prototype = proto(Map);"); } public void testBug2335992() throws Exception { testTypes( "/** @return {*} */ function f() { return 3; }" + "var x = f();" + "/** @type {string} */" + "x.y = 3;", "assignment to property y of x\n" + "found : number\n" + "required: string"); } public void testBug2341812() throws Exception { testTypes( "/** @interface */" + "function EventTarget() {}" + "/** @constructor \n * @implements {EventTarget} */" + "function Node() {}" + "/** @type {number} */ Node.prototype.index;" + "/** @param {EventTarget} x \n * @return {string} */" + "function foo(x) { return x.index; }"); } public void testScopedConstructors() throws Exception { testTypes( "function foo1() { " + " /** @constructor */ function Bar() { " + " /** @type {number} */ this.x = 3;" + " }" + "}" + "function foo2() { " + " /** @constructor */ function Bar() { " + " /** @type {string} */ this.x = 'y';" + " }" + " /** " + " * @param {Bar} b\n" + " * @return {number}\n" + " */" + " function baz(b) { return b.x; }" + "}", "inconsistent return type\n" + "found : string\n" + "required: number"); } public void testQualifiedNameInference1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @type {number?} */ Foo.prototype.bar = null;" + "/** @type {number?} */ Foo.prototype.baz = null;" + "/** @param {Foo} foo */" + "function f(foo) {" + " while (true) {" + " if (!foo.baz) break; " + " foo.bar = null;" + " }" + // Tests a bug where this condition always evaluated to true. " return foo.bar == null;" + "}"); } public void testQualifiedNameInference2() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "}"); } public void testQualifiedNameInference3() throws Exception { testTypes( "var x = {};" + "x.y = c;" + "function f(a, b) {" + " if (a) {" + " if (b) " + " x.y = 2;" + " else " + " x.y = 1;" + " }" + " return x.y == null;" + "} function g() { x.y = null; }"); } public void testQualifiedNameInference4() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}\n" + "/**\n" + " * @param {?string} x \n" + " * @constructor\n" + " */" + "function Foo(x) { this.x_ = x; }\n" + "Foo.prototype.bar = function() {" + " if (this.x_) { f(this.x_); }" + "};"); } public void testSheqRefinedScope() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */function A() {}\n" + "/** @constructor \n @extends A */ function B() {}\n" + "/** @return number */\n" + "B.prototype.p = function() { return 1; }\n" + "/** @param {A} a\n @param {B} b */\n" + "function f(a, b) {\n" + " b.p();\n" + " if (a === b) {\n" + " b.p();\n" + " }\n" + "}"); Node nodeC = n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild(); JSType typeC = nodeC.getJSType(); assertTrue(typeC.isNumber()); Node nodeB = nodeC.getFirstChild().getFirstChild(); JSType typeB = nodeB.getJSType(); assertEquals("B", typeB.toString()); } public void testAssignToUntypedVariable() throws Exception { Node n = parseAndTypeCheck("var z; z = 1;"); Node assign = n.getLastChild().getFirstChild(); Node node = assign.getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertEquals("number", node.getJSType().toString()); } public void testAssignToUntypedProperty() throws Exception { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {}\n" + "Foo.prototype.a = 1;" + "(new Foo).a;"); Node node = n.getLastChild().getFirstChild(); assertFalse(node.getJSType().isUnknownType()); assertTrue(node.getJSType().isNumber()); } public void testNew1() throws Exception { testTypes("new 4", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew2() throws Exception { testTypes("var Math = {}; new Math()", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew3() throws Exception { testTypes("new Date()"); } public void testNew4() throws Exception { testTypes("/** @constructor */function A(){}; new A();"); } public void testNew5() throws Exception { testTypes("function A(){}; new A();", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew6() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};" + "var a = new A();"); JSType aType = p.scope.getVar("a").getType(); assertTrue(aType instanceof ObjectType); ObjectType aObjectType = (ObjectType) aType; assertEquals("A", aObjectType.getConstructor().getReferenceName()); } public void testNew7() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "if (opt_constructor) { new opt_constructor; }" + "}"); } public void testNew8() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new opt_constructor;" + "}"); } public void testNew9() throws Exception { testTypes("/** @param {Function} opt_constructor */" + "function foo(opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew10() throws Exception { testTypes("var goog = {};" + "/** @param {Function} opt_constructor */" + "goog.Foo = function (opt_constructor) {" + "new (opt_constructor || Array);" + "}"); } public void testNew11() throws Exception { testTypes("/** @param {Function} c1 */" + "function f(c1) {" + " var c2 = function(){};" + " c1.prototype = new c2;" + "}", TypeCheck.NOT_A_CONSTRUCTOR); } public void testNew12() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("var a = new Array();"); Var a = p.scope.getVar("a"); assertEquals(ARRAY_TYPE, a.getType()); } public void testNew13() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */function FooBar(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew14() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "/** @constructor */var FooBar = function(){};" + "var a = new FooBar();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("FooBar", a.getType().toString()); } public void testNew15() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function(){};" + "var a = new goog.A();"); Var a = p.scope.getVar("a"); assertTrue(a.getType() instanceof ObjectType); assertEquals("goog.A", a.getType().toString()); } public void testNew16() throws Exception { testTypes( "/** \n" + " * @param {string} x \n" + " * @constructor \n" + " */" + "function Foo(x) {}" + "function g() { new Foo(1); }", "actual parameter 1 of Foo does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testName1() throws Exception { assertEquals(VOID_TYPE, testNameNode("undefined")); } public void testName2() throws Exception { assertEquals(OBJECT_FUNCTION_TYPE, testNameNode("Object")); } public void testName3() throws Exception { assertEquals(ARRAY_FUNCTION_TYPE, testNameNode("Array")); } public void testName4() throws Exception { assertEquals(DATE_FUNCTION_TYPE, testNameNode("Date")); } public void testName5() throws Exception { assertEquals(REGEXP_FUNCTION_TYPE, testNameNode("RegExp")); } /** * Type checks a NAME node and retrieve its type. */ private JSType testNameNode(String name) { Node node = Node.newString(Token.NAME, name); Node parent = new Node(Token.SCRIPT, node); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, parent); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, parent); return node.getJSType(); } public void testBitOperation1() throws Exception { testTypes("/**@return {void}*/function foo(){ ~foo(); }", "operator ~ cannot be applied to undefined"); } public void testBitOperation2() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()<<3;}", "operator << cannot be applied to undefined"); } public void testBitOperation3() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3<<foo();}", "operator << cannot be applied to undefined"); } public void testBitOperation4() throws Exception { testTypes("/**@return {void}*/function foo(){var a = foo()>>>3;}", "operator >>> cannot be applied to undefined"); } public void testBitOperation5() throws Exception { testTypes("/**@return {void}*/function foo(){var a = 3>>>foo();}", "operator >>> cannot be applied to undefined"); } public void testBitOperation6() throws Exception { testTypes("/**@return {!Object}*/function foo(){var a = foo()&3;}", "bad left operand to bitwise operator\n" + "found : Object\n" + "required: (boolean|null|number|string|undefined)"); } public void testBitOperation7() throws Exception { testTypes("var x = null; x |= undefined; x &= 3; x ^= '3'; x |= true;"); } public void testBitOperation8() throws Exception { testTypes("var x = void 0; x |= new Number(3);"); } public void testBitOperation9() throws Exception { testTypes("var x = void 0; x |= {};", "bad right operand to bitwise operator\n" + "found : {}\n" + "required: (boolean|null|number|string|undefined)"); } public void testCall1() throws Exception { testTypes("3();", "number expressions are not callable"); } public void testCall2() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall3() throws Exception { // We are checking that an unresolved named type can successfully // meet with a functional type to produce a callable type. testTypes("/** @type {Function|undefined} */var opt_f;" + "/** @type {some.unknown.type} */var f1;" + "var f2 = opt_f || f1;" + "f2();", "Parse error. Unknown type some.unknown.type"); } public void testCall4() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ bar('abc'); }", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall5() throws Exception { testTypes("/**@param {!RegExp} a*/var foo = function bar(a){ foo('abc'); }", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall6() throws Exception { testTypes("/** @param {!Number} foo*/function bar(foo){}" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: Number"); } public void testCall7() throws Exception { testTypes("/** @param {!RegExp} a*/var foo = function bar(a){};" + "foo('abc');", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: RegExp"); } public void testCall8() throws Exception { testTypes("/** @type {Function|number} */var f;f();", "(Function|number) expressions are " + "not callable"); } public void testCall9() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Foo = function() {};" + "/** @param {!goog.Foo} a */ var bar = function(a){};" + "bar('abc');", "actual parameter 1 of bar does not match formal parameter\n" + "found : string\n" + "required: goog.Foo"); } public void testCall10() throws Exception { testTypes("/** @type {Function} */var f;f();"); } public void testCall11() throws Exception { testTypes("var f = new Function(); f();"); } public void testFunctionCall1() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 3);"); } public void testFunctionCall2() throws Exception { testTypes( "/** @param {number} x */ var foo = function(x) {};" + "foo.call(null, 'bar');", "actual parameter 2 of foo.call does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall3() throws Exception { testTypes( "/** @param {number} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;"); } public void testFunctionCall4() throws Exception { testTypes( "/** @param {string} x \n * @constructor */ " + "var Foo = function(x) { this.bar.call(null, x); };" + "/** @type {function(number)} */ Foo.prototype.bar;", "actual parameter 2 of this.bar.call " + "does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testFunctionCall5() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.call(this, x); };"); } public void testFunctionCall6() throws Exception { testTypes( "/** @param {Function} handler \n * @constructor */ " + "var Foo = function(handler) { handler.apply(this, x); };"); } public void testFunctionCall7() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.call(opt_context, x);" + "};"); } public void testFunctionCall8() throws Exception { testTypes( "/** @param {Function} handler \n * @param {Object} opt_context */ " + "var Foo = function(handler, opt_context) { " + " handler.apply(opt_context, x);" + "};"); } public void testCast2() throws Exception { // can upcast to a base type. testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n @extends {base} */function derived() {}\n" + "/** @type {base} */ var baz = new derived();\n"); } public void testCast3() throws Exception { // cannot downcast testTypes("/** @constructor */function base() {}\n" + "/** @constructor @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = new base();\n", "initializing variable\n" + "found : base\n" + "required: derived"); } public void testCast4() throws Exception { // downcast must be explicit testTypes("/** @constructor */function base() {}\n" + "/** @constructor\n * @extends {base} */function derived() {}\n" + "/** @type {!derived} */ var baz = " + "/** @type {!derived} */(new base());\n"); } public void testCast5() throws Exception { // cannot explicitly cast to an unrelated type testTypes("/** @constructor */function foo() {}\n" + "/** @constructor */function bar() {}\n" + "var baz = /** @type {!foo} */(new bar);\n", "invalid cast - must be a subtype or supertype\n" + "from: bar\n" + "to : foo"); } public void testCast6() throws Exception { // can explicitly cast to a subtype or supertype testTypes("/** @constructor */function foo() {}\n" + "/** @constructor \n @extends foo */function bar() {}\n" + "var baz = /** @type {!bar} */(new bar);\n" + "var baz = /** @type {!foo} */(new foo);\n" + "var baz = /** @type {bar} */(new bar);\n" + "var baz = /** @type {foo} */(new foo);\n" + "var baz = /** @type {!foo} */(new bar);\n" + "var baz = /** @type {!bar} */(new foo);\n" + "var baz = /** @type {foo} */(new bar);\n" + "var baz = /** @type {bar} */(new foo);\n"); } public void testCast7() throws Exception { testTypes("var x = /** @type {foo} */ (new Object());", "Parse error. Unknown type foo"); } public void testCast8() throws Exception { testTypes("function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast9() throws Exception { testTypes("var foo = {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast10() throws Exception { testTypes("var foo = function() {};" + "function f() { return /** @type {foo} */ (new Object()); }", "Parse error. Unknown type foo"); } public void testCast11() throws Exception { testTypes("var goog = {}; goog.foo = {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast12() throws Exception { testTypes("var goog = {}; goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast13() throws Exception { // Test to make sure that the forward-declaration still allows for // a warning. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.foo'], []);" + "goog.foo = function() {};" + "function f() { return /** @type {goog.foo} */ (new Object()); }", "Parse error. Unknown type goog.foo"); } public void testCast14() throws Exception { // Test to make sure that the forward-declaration still prevents // some warnings. testClosureTypes("var goog = {}; " + "goog.addDependency('zzz.js', ['goog.bar'], []);" + "function f() { return /** @type {goog.bar} */ (new Object()); }", null); } public void testNestedCasts() throws Exception { testTypes("/** @constructor */var T = function() {};\n" + "/** @constructor */var V = function() {};\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {T|V}\n" + "*/\n" + "function f(b) { return b ? new T() : new V(); }\n" + "/**\n" + "* @param {boolean} b\n" + "* @return {boolean|undefined}\n" + "*/\n" + "function g(b) { return b ? true : undefined; }\n" + "/* @return {T} */\n" + "function h() {\n" + "return /** @type {T} */ (f(/** @type {boolean} */ (g(true))));\n" + "}"); } public void testNativeCast1() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(String(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testNativeCast2() throws Exception { testTypes( "/** @param {string} x */ function f(x) {}" + "f(Number(true));", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: string"); } public void testNativeCast3() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Boolean(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : boolean\n" + "required: number"); } public void testNativeCast4() throws Exception { testTypes( "/** @param {number} x */ function f(x) {}" + "f(Error(''));", "actual parameter 1 of f does not match formal parameter\n" + "found : Error\n" + "required: number"); } public void testBadConstructorCall() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo();", "Constructor function (this:Foo): undefined should be called " + "with the \"new\" keyword"); } public void testTypeof() throws Exception { testTypes("/**@return {void}*/function foo(){ var a = typeof foo(); }"); } public void testConstructorType1() throws Exception { testTypes("/**@constructor*/function Foo(){}" + "/**@type{!Foo}*/var f = new Date();", "initializing variable\n" + "found : Date\n" + "required: Foo"); } public void testConstructorType2() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;"); } public void testConstructorType3() throws Exception { // Reverse the declaration order so that we know that Foo is getting set // even on an out-of-order declaration sequence. testTypes("/**@type{Foo}*/var f = new Foo();\n" + "/**@type{Number}*/var n = f.bar;" + "/**@constructor*/function Foo(){\n" + "/**@type{Number}*/this.bar = new Number(5);\n" + "}\n"); } public void testConstructorType4() throws Exception { testTypes("/**@constructor*/function Foo(){\n" + "/**@type{!Number}*/this.bar = new Number(5);\n" + "}\n" + "/**@type{!Foo}*/var f = new Foo();\n" + "/**@type{!String}*/var n = f.bar;", "initializing variable\n" + "found : Number\n" + "required: String"); } public void testConstructorType5() throws Exception { testTypes("/**@constructor*/function Foo(){}\n" + "if (Foo){}\n"); } public void testConstructorType6() throws Exception { testTypes("/** @constructor */\n" + "function bar() {}\n" + "function _foo() {\n" + " /** @param {bar} x */\n" + " function f(x) {}\n" + "}"); } public void testConstructorType7() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("/** @constructor */function A(){};"); JSType type = p.scope.getVar("A").getType(); assertTrue(type instanceof FunctionType); FunctionType fType = (FunctionType) type; assertEquals("A", fType.getReferenceName()); } public void testAnonymousType1() throws Exception { testTypes("function f() {}" + "/** @constructor */\n" + "f().bar = function() {};"); } public void testAnonymousType2() throws Exception { testTypes("function f() {}" + "/** @interface */\n" + "f().bar = function() {};"); } public void testAnonymousType3() throws Exception { testTypes("function f() {}" + "/** @enum */\n" + "f().bar = {FOO: 1};"); } public void testBang1() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x; }", "inconsistent return type\n" + "found : (Object|null)\n" + "required: Object"); } public void testBang2() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return x ? x : new Object(); }"); } public void testBang3() throws Exception { testTypes("/** @param {Object} x\n@return {!Object} */\n" + "function f(x) { return /** @type {!Object} */ (x); }"); } public void testBang4() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) {\n" + "if (typeof x != 'undefined') { return x == y; }\n" + "else { return x != y; }\n}"); } public void testBang5() throws Exception { testTypes("/**@param {Object} x\n@param {Object} y\n@return {boolean}*/\n" + "function f(x, y) { return !!x && x == y; }"); } public void testBang6() throws Exception { testTypes("/** @param {Object?} x\n@return {Object} */\n" + "function f(x) { return x; }"); } public void testBang7() throws Exception { testTypes("/**@param {(Object,string,null)} x\n" + "@return {(Object,string)}*/function f(x) { return x; }"); } public void testDefinePropertyOnNullableObject1() throws Exception { testTypes("/** @type {Object} */ var n = {};\n" + "/** @type {number} */ n.x = 1;\n" + "/** @return {boolean} */function f() { return n.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testDefinePropertyOnNullableObject2() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @param {T} t\n@return {boolean} */function f(t) {\n" + "t.x = 1; return t.x; }", "inconsistent return type\n" + "found : number\n" + "required: boolean"); } public void testUnknownConstructorInstanceType1() throws Exception { testTypes("/** @return Array */ function g(f) { return new f(); }"); } public void testUnknownConstructorInstanceType2() throws Exception { testTypes("function g(f) { return /** @type Array */ new f(); }"); } public void testUnknownConstructorInstanceType3() throws Exception { testTypes("function g(f) { var x = new f(); x.a = 1; return x; }"); } public void testUnknownPrototypeChain() throws Exception { testTypes("/**\n" + "* @param {Object} co\n" + " * @return {Object}\n" + " */\n" + "function inst(co) {\n" + " /** @constructor */\n" + " var c = function() {};\n" + " c.prototype = co.prototype;\n" + " return new c;\n" + "}"); } public void testNamespacedConstructor() throws Exception { Node root = parseAndTypeCheck( "var goog = {};" + "/** @constructor */ goog.MyClass = function() {};" + "/** @return {!goog.MyClass} */ " + "function foo() { return new goog.MyClass(); }"); JSType typeOfFoo = root.getLastChild().getJSType(); assert(typeOfFoo instanceof FunctionType); JSType retType = ((FunctionType) typeOfFoo).getReturnType(); assert(retType instanceof ObjectType); assertEquals("goog.MyClass", ((ObjectType) retType).getReferenceName()); } public void testComplexNamespace() throws Exception { String js = "var goog = {};" + "goog.foo = {};" + "goog.foo.bar = 5;"; TypeCheckResult p = parseAndTypeCheckWithScope(js); // goog type in the scope JSType googScopeType = p.scope.getVar("goog").getType(); assertTrue(googScopeType instanceof ObjectType); assertTrue("foo property not present on goog type", ((ObjectType) googScopeType).hasProperty("foo")); assertFalse("bar property present on goog type", ((ObjectType) googScopeType).hasProperty("bar")); // goog type on the VAR node Node varNode = p.root.getFirstChild(); assertEquals(Token.VAR, varNode.getType()); JSType googNodeType = varNode.getFirstChild().getJSType(); assertTrue(googNodeType instanceof ObjectType); // goog scope type and goog type on VAR node must be the same assertTrue(googScopeType == googNodeType); // goog type on the left of the GETPROP node (under fist ASSIGN) Node getpropFoo1 = varNode.getNext().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo1.getType()); assertEquals("goog", getpropFoo1.getFirstChild().getString()); JSType googGetpropFoo1Type = getpropFoo1.getFirstChild().getJSType(); assertTrue(googGetpropFoo1Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo1Type == googScopeType); // the foo property should be defined on goog JSType googFooType = ((ObjectType) googScopeType).getPropertyType("foo"); assertTrue(googFooType instanceof ObjectType); // goog type on the left of the GETPROP lower level node // (under second ASSIGN) Node getpropFoo2 = varNode.getNext().getNext() .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getpropFoo2.getType()); assertEquals("goog", getpropFoo2.getFirstChild().getString()); JSType googGetpropFoo2Type = getpropFoo2.getFirstChild().getJSType(); assertTrue(googGetpropFoo2Type instanceof ObjectType); // still the same type as the one on the variable assertTrue(googGetpropFoo2Type == googScopeType); // goog.foo type on the left of the top level GETPROP node // (under second ASSIGN) JSType googFooGetprop2Type = getpropFoo2.getJSType(); assertTrue("goog.foo incorrectly annotated in goog.foo.bar selection", googFooGetprop2Type instanceof ObjectType); ObjectType googFooGetprop2ObjectType = (ObjectType) googFooGetprop2Type; assertFalse("foo property present on goog.foo type", googFooGetprop2ObjectType.hasProperty("foo")); assertTrue("bar property not present on goog.foo type", googFooGetprop2ObjectType.hasProperty("bar")); assertEquals("bar property on goog.foo type incorrectly inferred", NUMBER_TYPE, googFooGetprop2ObjectType.getPropertyType("bar")); } public void testAddingMethodsUsingPrototypeIdiomSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype.m1 = 5"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace1() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "goog.A = /** @constructor */function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } public void testAddingMethodsUsingPrototypeIdiomComplexNamespace2() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope( "var goog = {};" + "/** @constructor */goog.A = function() {};" + "/** @type number */goog.A.prototype.m1 = 5"); testAddingMethodsUsingPrototypeIdiomComplexNamespace(p); } private void testAddingMethodsUsingPrototypeIdiomComplexNamespace( TypeCheckResult p) { ObjectType goog = (ObjectType) p.scope.getVar("goog").getType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, goog.getPropertiesCount()); JSType googA = goog.getPropertyType("A"); assertNotNull(googA); assertTrue(googA instanceof FunctionType); FunctionType googAFunction = (FunctionType) googA; ObjectType classA = googAFunction.getInstanceType(); assertEquals(NATIVE_PROPERTIES_COUNT + 1, classA.getPropertiesCount()); checkObjectType(classA, "m1", NUMBER_TYPE); } public void testAddingMethodsPrototypeIdiomAndObjectLiteralSimpleNamespace() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true}"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 2, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); } public void testDontAddMethodsIfNoConstructor() throws Exception { Node js1Node = parseAndTypeCheck( "function A() {}" + "A.prototype = {m1: 5, m2: true}"); JSType functionAType = js1Node.getFirstChild().getJSType(); assertEquals("function (): undefined", functionAType.toString()); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m1")); assertEquals(UNKNOWN_TYPE, U2U_FUNCTION_TYPE.getPropertyType("m2")); } public void testFunctionAssignement() throws Exception { testTypes("/**" + "* @param {string} ph0" + "* @param {string} ph1" + "* @return {string}" + "*/" + "function MSG_CALENDAR_ACCESS_ERROR(ph0, ph1) {return ''}" + "/** @type {Function} */" + "var MSG_CALENDAR_ADD_ERROR = MSG_CALENDAR_ACCESS_ERROR;"); } public void testAddMethodsPrototypeTwoWays() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {}" + "A.prototype = {m1: 5, m2: true};" + "A.prototype.m3 = 'third property!';"); ObjectType instanceType = getInstanceType(js1Node); assertEquals("A", instanceType.toString()); assertEquals(NATIVE_PROPERTIES_COUNT + 3, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", NUMBER_TYPE); checkObjectType(instanceType, "m2", BOOLEAN_TYPE); checkObjectType(instanceType, "m3", STRING_TYPE); } public void testPrototypePropertyTypes() throws Exception { Node js1Node = parseAndTypeCheck( "/** @constructor */function A() {\n" + " /** @type string */ this.m1;\n" + " /** @type Object? */ this.m2 = {};\n" + " /** @type boolean */ this.m3;\n" + "}\n" + "/** @type string */ A.prototype.m4;\n" + "/** @type number */ A.prototype.m5 = 0;\n" + "/** @type boolean */ A.prototype.m6;\n"); ObjectType instanceType = getInstanceType(js1Node); assertEquals(NATIVE_PROPERTIES_COUNT + 6, instanceType.getPropertiesCount()); checkObjectType(instanceType, "m1", STRING_TYPE); checkObjectType(instanceType, "m2", createUnionType(OBJECT_TYPE, NULL_TYPE)); checkObjectType(instanceType, "m3", BOOLEAN_TYPE); checkObjectType(instanceType, "m4", STRING_TYPE); checkObjectType(instanceType, "m5", NUMBER_TYPE); checkObjectType(instanceType, "m6", BOOLEAN_TYPE); } public void testValueTypeBuiltInPrototypePropertyType() throws Exception { Node node = parseAndTypeCheck("\"x\".charAt(0)"); assertEquals(STRING_TYPE, node.getFirstChild().getFirstChild().getJSType()); } public void testDeclareBuiltInConstructor() throws Exception { // Built-in prototype properties should be accessible // even if the built-in constructor is declared. Node node = parseAndTypeCheck( "/** @constructor */ var String = function(opt_str) {};\n" + "(new String(\"x\")).charAt(0)"); assertEquals(STRING_TYPE, node.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType1() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n1 = parseAndTypeCheck(externs + "(new String(\"x\")).substr(0,1);"); assertEquals(STRING_TYPE, n1.getLastChild().getFirstChild().getJSType()); } public void testExtendBuiltInType2() throws Exception { String externs = "/** @constructor */ var String = function(opt_str) {};\n" + "/**\n" + "* @param {number} start\n" + "* @param {number} opt_length\n" + "* @return {string}\n" + "*/\n" + "String.prototype.substr = function(start, opt_length) {};\n"; Node n2 = parseAndTypeCheck(externs + "\"x\".substr(0,1);"); assertEquals(STRING_TYPE, n2.getLastChild().getFirstChild().getJSType()); } public void testExtendFunction1() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(new Function()).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testExtendFunction2() throws Exception { Node n = parseAndTypeCheck("/**@return {number}*/Function.prototype.f = " + "function() { return 1; };\n" + "(function() {}).f();"); JSType type = n.getLastChild().getLastChild().getJSType(); assertEquals(NUMBER_TYPE, type); } public void testInheritanceCheck1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};"); } public void testInheritanceCheck2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "property foo not defined on any superclass of Sub"); } public void testInheritanceCheck3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Super; " + "use @override to override it"); } public void testInheritanceCheck4() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck5() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on superclass Root; " + "use @override to override it"); } public void testInheritanceCheck6() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() {};" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInheritanceCheck7() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "goog.Sub.prototype.foo = 5;", "property foo already defined on superclass goog.Super; " + "use @override to override it"); } public void testInheritanceCheck8() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = 5;"); } public void testInheritanceCheck9_1() throws Exception { testTypes( "/** @constructor */function Super() {};" + "Super.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck9_2() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck9_3() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @return number */Super.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super): number\n" + "override: function (this:Sub): string"); } public void testInheritanceCheck10_1() throws Exception { testTypes( "/** @constructor */function Root() {};" + "Root.prototype.foo = function() { return 3; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };"); } public void testInheritanceCheck10_2() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo =\n" + "function() {};"); } public void testInheritanceCheck10_3() throws Exception { testTypes( "/** @constructor */function Root() {};" + "/** @return number */Root.prototype.foo = function() { return 1; };" + "/** @constructor\n @extends {Root} */function Super() {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @return string */Sub.prototype.foo =\n" + "function() { return \"some string\" };", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Root\n" + "original: function (this:Root): number\n" + "override: function (this:Sub): string"); } public void testInterfaceInheritanceCheck11() throws Exception { testTypes( "/** @constructor */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @extends {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from superclass Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInheritanceCheck12() throws Exception { testTypes( "var goog = {};" + "/** @constructor */goog.Super = function() {};" + "goog.Super.prototype.foo = 3;" + "/** @constructor\n @extends {goog.Super} */goog.Sub = function() {};" + "/** @override */goog.Sub.prototype.foo = \"some string\";", "mismatch of the foo property type and the type of the property it " + "overrides from superclass goog.Super\n" + "original: number\n" + "override: string"); } public void testInheritanceCheck13() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } public void testInheritanceCheck14() throws Exception { testTypes( "var goog = {};\n" + "/** @constructor\n @extends {goog.Missing} */\n" + "goog.Super = function() {};\n" + "/** @constructor\n @extends {goog.Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", "Parse error. Unknown type goog.Missing"); } // TODO(user): We should support this way of declaring properties as it is // widely used. //public void testInheritanceCheck15() throws Exception { // testTypes( // "/** @constructor */function Super() {};" + // "/** @param {number} bar */Super.prototype.foo;" + // "/** @constructor\n @extends {Super} */function Sub() {};" + // "/** @override\n @param {number} bar */Sub.prototype.foo =\n" + // "function(bar) {};"); //} // public void testInterfacePropertyOverride1() throws Exception { // testTypes( // "/** @interface */function Super() {};" + // "/** @desc description */Super.prototype.foo = function() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Super extended interface"); // } // public void testInterfacePropertyOverride2() throws Exception { // testTypes( // "/** @interface */function Root() {};" + // "/** @desc description */Root.prototype.foo = function() {};" + // "/** @interface\n @extends {Root} */function Super() {};" + // "/** @interface\n @extends {Super} */function Sub() {};" + // "/** @desc description */Sub.prototype.foo = function() {};", // "property foo is already defined by the Root extended interface"); // } public void testInterfaceInheritanceCheck1() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "Sub.prototype.foo = function() {};", "property foo already defined on interface Super; use @override to " + "override it"); } public void testInterfaceInheritanceCheck2() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @desc description */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};"); } public void testInterfaceInheritanceCheck3() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @return {number} */Sub.prototype.foo = function() { return 1;};", "property foo already defined on interface Root; use @override to " + "override it"); } public void testInterfaceInheritanceCheck4() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return {number} */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n * @return {number} */Sub.prototype.foo =\n" + "function() { return 1;};"); } public void testInterfaceInheritanceCheck5() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @return string */Super.prototype.foo = function() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck6() throws Exception { testTypes( "/** @interface */function Root() {};" + "/** @return string */Root.prototype.foo = function() {};" + "/** @interface\n @extends {Root} */function Super() {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @return number */Sub.prototype.foo =\n" + "function() { return 1; };", "mismatch of the foo property type and the type of the property it " + "overrides from interface Root\n" + "original: function (this:Root): string\n" + "override: function (this:Sub): number"); } public void testInterfaceInheritanceCheck7() throws Exception { testTypes( "/** @interface */function Super() {};" + "/** @param {number} bar */Super.prototype.foo = function(bar) {};" + "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override\n @param {string} bar */Sub.prototype.foo =\n" + "function(bar) {};", "mismatch of the foo property type and the type of the property it " + "overrides from interface Super\n" + "original: function (this:Super, number): undefined\n" + "override: function (this:Sub, string): undefined"); } public void testInterfaceInheritanceCheck8() throws Exception { testTypes( "/** @constructor\n @implements {Super} */function Sub() {};" + "/** @override */Sub.prototype.foo = function() {};", new String[] { "Parse error. Unknown type Super", "property foo not defined on any superclass of Sub" }); } public void testInterfacePropertyNotImplemented() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor\n @implements {Int} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testInterfacePropertyNotImplemented2() throws Exception { testTypes( "/** @interface */function Int() {};" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @interface \n @extends {Int} */function Int2() {};" + "/** @constructor\n @implements {Int2} */function Foo() {};", "property foo on interface Int is not implemented by type Foo"); } public void testStubConstructorImplementingInterface() throws Exception { // This does not throw a warning for unimplemented property because Foo is // just a stub. testTypes("/** @interface */ function Int() {}\n" + "/** @desc description */Int.prototype.foo = function() {};" + "/** @constructor \n @implements {Int} */ var Foo;\n"); } public void testObjectLiteral() throws Exception { Node n = parseAndTypeCheck("var a = {m1: 7, m2: 'hello'}"); Node nameNode = n.getFirstChild().getFirstChild(); Node objectNode = nameNode.getFirstChild(); // node extraction assertEquals(Token.NAME, nameNode.getType()); assertEquals(Token.OBJECTLIT, objectNode.getType()); // value's type ObjectType objectType = (ObjectType) objectNode.getJSType(); assertEquals(NUMBER_TYPE, objectType.getPropertyType("m1")); assertEquals(STRING_TYPE, objectType.getPropertyType("m2")); // variable's type assertEquals(objectType, nameNode.getJSType()); } public void testObjectLiteralDeclaration1() throws Exception { testTypes( "var x = {" + "/** @type {boolean} */ abc: true," + "/** @type {number} */ 'def': 0," + "/** @type {string} */ 3: 'fgh'" + "};"); } public void testCallDateConstructorAsFunction() throws Exception { // ECMA-262 15.9.2: When Date is called as a function rather than as a // constructor, it returns a string. Node n = parseAndTypeCheck("Date()"); assertEquals(STRING_TYPE, n.getFirstChild().getFirstChild().getJSType()); } // According to ECMA-262, Error & Array function calls are equivalent to // constructor calls. public void testCallErrorConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Error('x')"); assertEquals(ERROR_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testCallArrayConstructorAsFunction() throws Exception { Node n = parseAndTypeCheck("Array()"); assertEquals(ARRAY_TYPE, n.getFirstChild().getFirstChild().getJSType()); } public void testPropertyTypeOfUnionType() throws Exception { testTypes("var a = {};" + "/** @constructor */ a.N = function() {};\n" + "a.N.prototype.p = 1;\n" + "/** @constructor */ a.S = function() {};\n" + "a.S.prototype.p = 'a';\n" + "/** @param {!a.N|!a.S} x\n@return {string} */\n" + "var f = function(x) { return x.p; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } // TODO(user): We should flag these as invalid. This will probably happen // when we make sure the interface is never referenced outside of its // definition. We might want more specific and helpful error messages. //public void testWarningOnInterfacePrototype() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.prototype = function() { };", // "e of its definition"); //} // //public void testBadPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function() {};\n" + // "/** @return {number} */ u.T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */ T.f = function() { return 1;};", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function() {}; u.T.x", // "cannot reference an interface ouside of its definition"); //} // //public void testBadPropertyOnInterface4() throws Exception { // testTypes("/** @interface */ function T() {}; T.x;", // "cannot reference an interface ouside of its definition"); //} public void testAnnotatedPropertyOnInterface1() throws Exception { // For interfaces we must allow function definitions that don't have a // return statement, even though they declare a returned type. testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() {};"); } public void testAnnotatedPropertyOnInterface2() throws Exception { testTypes("/** @interface */ u.T = function() {};\n" + "/** @return {number} */ u.T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface3() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = function() { };"); } public void testAnnotatedPropertyOnInterface4() throws Exception { testTypes( CLOSURE_DEFS + "/** @interface */ function T() {};\n" + "/** @return {number} */ T.prototype.f = goog.abstractMethod;"); } // TODO(user): If we want to support this syntax we have to warn about // missing annotations. //public void testWarnUnannotatedPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {}; u.T.prototype.x;", // "interface property x is not annotated"); //} // //public void testWarnUnannotatedPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {}; T.prototype.x;", // "interface property x is not annotated"); //} public void testWarnUnannotatedPropertyOnInterface5() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @desc x does something */u.T.prototype.x = function() {};"); } public void testWarnUnannotatedPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @desc x does something */T.prototype.x = function() {};"); } // TODO(user): If we want to support this syntax we have to warn about // the invalid type of the interface member. //public void testWarnDataPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @type {number} */u.T.prototype.x;", // "interface members can only be plain functions"); //} public void testDataPropertyOnInterface2() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x;"); } public void testWarnDataPropertyOnInterface3() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @type {number} */u.T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } public void testWarnDataPropertyOnInterface4() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = 1;", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod"); } // TODO(user): If we want to support this syntax we should warn about the // mismatching types in the two tests below. //public void testErrorMismatchingPropertyOnInterface1() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "/** @param {String} foo */function(foo) {};", // "found : \n" + // "required: "); //} // //public void testErrorMismatchingPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @return {number} */T.prototype.x =\n" + // "/** @return {string} */function() {};", // "found : \n" + // "required: "); //} // TODO(user): We should warn about this (bar is missing an annotation). We // probably don't want to warn about all missing parameter annotations, but // we should be as strict as possible regarding interfaces. //public void testErrorMismatchingPropertyOnInterface3() throws Exception { // testTypes("/** @interface */ u.T = function () {};\n" + // "/** @param {Number} foo */u.T.prototype.x =\n" + // "function(foo, bar) {};", // "found : \n" + // "required: "); //} public void testErrorMismatchingPropertyOnInterface4() throws Exception { testTypes("/** @interface */ u.T = function () {};\n" + "/** @param {Number} foo */u.T.prototype.x =\n" + "function() {};", "parameter foo does not appear in u.T.prototype.x's parameter list"); } public void testErrorMismatchingPropertyOnInterface5() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @type {number} */T.prototype.x = function() { };", "assignment to property x of T.prototype\n" + "found : function (): undefined\n" + "required: number"); } public void testErrorMismatchingPropertyOnInterface6() throws Exception { testTypes("/** @interface */ function T() {};\n" + "/** @return {number} */T.prototype.x = 1", "interface members can only be empty property declarations, " + "empty functions, or goog.abstractMethod" ); } public void testInterfaceNonEmptyFunction() throws Exception { testTypes("/** @interface */ function T() {};\n" + "T.prototype.x = function() { return 'foo'; }", "interface member functions must have an empty body" ); } public void testDoubleNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @interface */ I1.I2.I3 = function() {};\n"); } public void testStaticDataPropertyOnNestedInterface() throws Exception { testTypes("/** @interface */ var I1 = function() {};\n" + "/** @interface */ I1.I2 = function() {};\n" + "/** @type {number} */ I1.I2.x = 1;\n"); } public void testInterfaceInstantiation() throws Exception { testTypes("/** @interface */var f; new f", "cannot instantiate non-constructor"); } public void testPrototypeLoop() throws Exception { testTypes( suppressMissingProperty("foo") + "/** @constructor \n * @extends {T} */var T = function() {};" + "alert((new T).foo);", "Parse error. Cycle detected in inheritance chain of type T"); } public void testDirectPrototypeAssign() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "/** @constructor */ function Bar() {}" + "/** @type {Array} */ Bar.prototype = new Foo()", "assignment to property prototype of Bar\n" + "found : Foo\n" + "required: (Array|null)"); } // In all testResolutionViaRegistry* tests, since u is unknown, u.T can only // be resolved via the registry and not via properties. public void testResolutionViaRegistry1() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry2() throws Exception { testTypes( "/** @constructor */ u.T = function() {" + " this.a = 0; };\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testResolutionViaRegistry3() throws Exception { testTypes("/** @constructor */ u.T = function() {};\n" + "/** @type {(number|string)} */ u.T.prototype.a = 0;\n" + "/**\n" + "* @param {u.T} t\n" + "* @return {string}\n" + "*/\n" + "var f = function(t) { return t.a; };", "inconsistent return type\n" + "found : (number|string)\n" + "required: string"); } public void testResolutionViaRegistry4() throws Exception { testTypes("/** @constructor */ u.A = function() {};\n" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.A = function() {}\n;" + "/**\n* @constructor\n* @extends {u.A}\n*/\nu.A.B = function() {};\n" + "var ab = new u.A.B();\n" + "/** @type {!u.A} */ var a = ab;\n" + "/** @type {!u.A.A} */ var aa = ab;\n", "initializing variable\n" + "found : u.A.B\n" + "required: u.A.A"); } public void testResolutionViaRegistry5() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ u.T = function() {}; u.T"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof FunctionType); assertEquals("u.T", ((FunctionType) type).getInstanceType().getReferenceName()); } public void testGatherProperyWithoutAnnotation1() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ var T = function() {};" + "/** @type {!T} */var t; t.x; t;"); JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(objectType), registry.getTypesWithProperty("x")); } public void testGatherProperyWithoutAnnotation2() throws Exception { TypeCheckResult ns = parseAndTypeCheckWithScope("/** @type {!Object} */var t; t.x; t;"); Node n = ns.root; Scope s = ns.scope; JSType type = n.getLastChild().getLastChild().getJSType(); assertFalse(type.isUnknownType()); assertEquals(type, OBJECT_TYPE); assertTrue(type instanceof ObjectType); ObjectType objectType = (ObjectType) type; assertFalse(objectType.hasProperty("x")); assertEquals( Sets.newHashSet(OBJECT_TYPE), registry.getTypesWithProperty("x")); } public void testFunctionMasksVariableBug() throws Exception { testTypes("var x = 4; var f = function x(b) { return b ? 1 : x(true); };", "function x masks variable (IE bug)"); } public void testDfa1() throws Exception { testTypes("var x = null;\n x = 1;\n /** @type number */ var y = x;"); } public void testDfa2() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\nvar x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa3() throws Exception { testTypes("function u() {}\n" + "/** @return {number} */ function f() {\n" + "/** @type {number|string} */ var x = 'todo';\n" + "if (u()) { x = 1; } else { x = 2; } return x;\n}"); } public void testDfa4() throws Exception { testTypes("/** @param {Date?} d */ function f(d) {\n" + "if (!d) { return; }\n" + "/** @type {!Date} */ var e = d;\n}"); } public void testDfa5() throws Exception { testTypes("/** @return {string?} */ function u() {return 'a';}\n" + "/** @param {string?} x\n@return {string} */ function f(x) {\n" + "while (!x) { x = u(); }\nreturn x;\n}"); } public void testDfa6() throws Exception { testTypes("/** @return {Object?} */ function u() {return {};}\n" + "/** @param {Object?} x */ function f(x) {\n" + "while (x) { x = u(); if (!x) { x = u(); } }\n}"); } public void testDfa7() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {Date?} */ T.prototype.x = null;\n" + "/** @param {!T} t */ function f(t) {\n" + "if (!t.x) { return; }\n" + "/** @type {!Date} */ var e = t.x;\n}"); } public void testDfa8() throws Exception { testTypes("/** @constructor */ var T = function() {};\n" + "/** @type {number|string} */ T.prototype.x = '';\n" + "function u() {}\n" + "/** @param {!T} t\n@return {number} */ function f(t) {\n" + "if (u()) { t.x = 1; } else { t.x = 2; } return t.x;\n}"); } public void testDfa9() throws Exception { testTypes("function f() {\n/** @type {string?} */var x;\nx = null;\n" + "if (x == null) { return 0; } else { return 1; } }", "condition always evaluates to true\n" + "left : null\n" + "right: null"); } public void testDfa10() throws Exception { testTypes("/** @param {null} x */ function g(x) {}" + "/** @param {string?} x */function f(x) {\n" + "if (!x) { x = ''; }\n" + "if (g(x)) { return 0; } else { return 1; } }", "actual parameter 1 of g does not match formal parameter\n" + "found : string\n" + "required: null"); } public void testDfa11() throws Exception { testTypes("/** @param {string} opt_x\n@return {string} */\n" + "function f(opt_x) { if (!opt_x) { " + "throw new Error('x cannot be empty'); } return opt_x; }"); } public void testDfa12() throws Exception { testTypes("/** @param {string} x \n * @constructor \n */" + "var Bar = function(x) {};" + "/** @param {string} x */ function g(x) { return true; }" + "/** @param {string|number} opt_x */ " + "function f(opt_x) { " + " if (opt_x) { new Bar(g(opt_x) && 'x'); }" + "}", "actual parameter 1 of g does not match formal parameter\n" + "found : (number|string)\n" + "required: string"); } public void testDfa13() throws Exception { testTypes( "/**\n" + " * @param {string} x \n" + " * @param {number} y \n" + " * @param {number} z \n" + " */" + "function g(x, y, z) {}" + "function f() { " + " var x = 'a'; g(x, x = 3, x);" + "}"); } public void testTypeInferenceWithCast1() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast2() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return null;}" + "/**@param {number?} x\n@return {number?}*/function f(x) {return x;}" + "/**@return {number?}*/function g(x) {" + "var y; y = /**@type {number?}*/(u(x)); return f(y);}"); } public void testTypeInferenceWithCast3() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x));}"); } public void testTypeInferenceWithCast4() throws Exception { testTypes( "/**@return {(number,null,undefined)}*/function u(x) {return 1;}" + "/**@return {number}*/function g(x) {" + "return /**@type {number}*/(u(x)) && 1;}"); } public void testTypeInferenceWithCast5() throws Exception { testTypes( "/** @param {number} x */ function foo(x) {}" + "/** @param {{length:*}} y */ function bar(y) {" + " /** @type {string} */ y.length;" + " foo(y.length);" + "}", "actual parameter 1 of foo does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeInferenceWithClosure1() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x == null;" + "}"); } public void testTypeInferenceWithClosure2() throws Exception { testTypes( "/** @return {boolean} */" + "function f() {" + " /** @type {?string} */ var x = null;" + " function g() { x = 'y'; } g(); " + " return x === 3;" + "}", "condition always evaluates to the same value\n" + "left : (null|string)\n" + "right: number"); } public void testForwardPropertyReference() throws Exception { testTypes("/** @constructor */ var Foo = function() { this.init(); };" + "/** @return {string} */" + "Foo.prototype.getString = function() {" + " return this.number_;" + "};" + "Foo.prototype.init = function() {" + " /** @type {number} */" + " this.number_ = 3;" + "};", "inconsistent return type\n" + "found : number\n" + "required: string"); } public void testNoForwardTypeDeclaration() throws Exception { testTypes( "/** @param {MyType} x */ function f(x) {}", "Parse error. Unknown type MyType"); } public void testNoForwardTypeDeclarationAndNoBraces() throws Exception { // To better support third-party code, we do not warn when // there are no braces around an unknown type name. testTypes("/** @return The result. */ function f() {}"); } public void testForwardTypeDeclaration1() throws Exception { testClosureTypes( // malformed addDependency calls shouldn't cause a crash "goog.addDependency();" + "goog.addDependency('y', [goog]);" + "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x \n * @return {number} */" + "function f(x) { return x; }", null); } public void testForwardTypeDeclaration2() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { }" + "f(3);", null); } public void testForwardTypeDeclaration3() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MyType'], []);" + "/** @param {MyType} x */ function f(x) { return x; }" + "/** @constructor */ var MyType = function() {};" + "f(3);", "actual parameter 1 of f does not match formal parameter\n" + "found : number\n" + "required: (MyType|null)"); } public void testMalformedOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testMalformedOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @typedef {boolean} */ goog.Bar = goog.typedef", "Typedef for goog.Bar does not have any type information"); } public void testDuplicateOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @constructor */ goog.Bar = function() {};" + "/** @type {number} */ goog.Bar = goog.typedef", "variable goog.Bar redefined with type number, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testOldTypeDef1() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testOldTypeDef2() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testOldTypeDef3() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number} */ var Bar = goog.typedef;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularOldTypeDef() throws Exception { testTypes( "var goog = {}; goog.typedef = true;" + "/** @type {number|Array.<goog.Bar>} */ goog.Bar = goog.typedef;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testDuplicateTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @constructor */ goog.Bar = function() {};" + "/** @typedef {number} */ goog.Bar;", "variable goog.Bar redefined with type None, " + "original definition at [testcode]:1 " + "with type function (this:goog.Bar): undefined"); } public void testTypeDef1() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3);"); } public void testTypeDef2() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testTypeDef3() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number} */ var Bar;" + "/** @param {Bar} x */ function f(x) {}" + "f('3');", "actual parameter 1 of f does not match formal parameter\n" + "found : string\n" + "required: number"); } public void testCircularTypeDef() throws Exception { testTypes( "var goog = {};" + "/** @typedef {number|Array.<goog.Bar>} */ goog.Bar;" + "/** @param {goog.Bar} x */ function f(x) {}" + "f(3); f([3]); f([[3]]);"); } public void testGetTypedPercent1() throws Exception { String js = "var id = function(x) { return x; }\n" + "var id2 = function(x) { return id(x); }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent2() throws Exception { String js = "var x = {}; x.y = 1;"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent3() throws Exception { String js = "var f = function(x) { x.a = x.b; }"; assertEquals(50.0, getTypedPercent(js), 0.1); } public void testGetTypedPercent4() throws Exception { String js = "var n = {};\n /** @constructor */ n.T = function() {};\n" + "/** @type n.T */ var x = new n.T();"; assertEquals(100.0, getTypedPercent(js), 0.1); } private double getTypedPercent(String js) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); TypeCheck t = makeTypeCheck(); t.processForTesting(null, n); return t.getTypedPercent(); } private ObjectType getInstanceType(Node js1Node) { JSType type = js1Node.getFirstChild().getJSType(); assertNotNull(type); assertTrue(type instanceof FunctionType); FunctionType functionType = (FunctionType) type; assertTrue(functionType.isConstructor()); return functionType.getInstanceType(); } public void testPrototypePropertyReference() throws Exception { TypeCheckResult p = parseAndTypeCheckWithScope("" + "/** @constructor */\n" + "function Foo() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.bar = function(a){};\n" + "/** @param {Foo} f */\n" + "function baz(f) {\n" + " Foo.prototype.bar.call(f, 3);\n" + "}"); assertEquals(0, compiler.getErrorCount()); assertEquals(0, compiler.getWarningCount()); assertTrue(p.scope.getVar("Foo").getType() instanceof FunctionType); FunctionType fooType = (FunctionType) p.scope.getVar("Foo").getType(); assertEquals("function (this:Foo, number): undefined", fooType.getPrototype().getPropertyType("bar").toString()); } public void testResolvingNamedTypes() throws Exception { String js = "" + "/** @constructor */\n" + "var Foo = function() {}\n" + "/** @param {number} a */\n" + "Foo.prototype.foo = function(a) {\n" + " return this.baz().toString();\n" + "};\n" + "/** @return {Baz} */\n" + "Foo.prototype.baz = function() { return new Baz(); };\n" + "/** @constructor\n" + " * @extends Foo */\n" + "var Bar = function() {};" + "/** @constructor */\n" + "var Baz = function() {};"; assertEquals(100.0, getTypedPercent(js), 0.1); } public void testMissingProperty1() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.a = 3; };"); } public void testMissingProperty2() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };", "Property a never defined on Foo"); } public void testMissingProperty3() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).a = 3;"); } public void testMissingProperty4() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "(new Foo).b = 3;", "Property a never defined on Foo"); } public void testMissingProperty5() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor */ function Bar() { this.a = 3; };", "Property a never defined on Foo"); } public void testMissingProperty6() throws Exception { testTypes( "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "/** @constructor \n * @extends {Foo} */ " + "function Bar() { this.a = 3; };"); } public void testMissingProperty7() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return obj.impossible; }", "Property impossible never defined on Object"); } public void testMissingProperty8() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { return typeof obj.impossible; }"); } public void testMissingProperty9() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { if (obj.impossible) { return true; } }"); } public void testMissingProperty10() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { while (obj.impossible) { return true; } }"); } public void testMissingProperty11() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { for (;obj.impossible;) { return true; } }"); } public void testMissingProperty12() throws Exception { testTypes( "/** @param {Object} obj */" + "function foo(obj) { do { } while (obj.impossible); }"); } public void testMissingProperty13() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isDef(obj.impossible); }"); } public void testMissingProperty14() throws Exception { testTypes( "var goog = {}; goog.isDef = function(x) { return false; };" + "/** @param {Object} obj */" + "function foo(obj) { return goog.isNull(obj.impossible); }", "Property isNull never defined on goog"); } public void testMissingProperty15() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { x.foo(); } }"); } public void testMissingProperty16() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo(); if (x.foo) {} }", "Property foo never defined on Object"); } public void testMissingProperty17() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (typeof x.foo == 'function') { x.foo(); } }"); } public void testMissingProperty18() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo instanceof Function) { x.foo(); } }"); } public void testMissingProperty19() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { if (x.bar) { if (x.foo) {} } else { x.foo(); } }", "Property foo never defined on Object"); } public void testMissingProperty20() throws Exception { // NOTE(nicksantos): In the else branch, we know that x.foo is a // CHECKED_UNKNOWN (UNKNOWN restricted to a falsey value). We could // do some more sophisticated analysis here. Obviously, if x.foo is false, // then x.foo cannot possibly be called. For example, you could imagine a // VagueType that was like UnknownType, but had some constraints on it // so that we knew it could never be a function. // // For now, we just punt on this issue. testTypes( "/** @param {Object} x */" + "function f(x) { if (x.foo) { } else { x.foo(); } }"); } public void testMissingProperty21() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { x.foo && x.foo(); }"); } public void testMissingProperty22() throws Exception { testTypes( "/** @param {Object} x \n * @return {boolean} */" + "function f(x) { return x.foo ? x.foo() : true; }"); } public void testMissingProperty23() throws Exception { testTypes( "function f(x) { x.impossible(); }", "Property impossible never defined on x"); } public void testMissingProperty24() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {MissingType} x */" + "function f(x) { x.impossible(); }", null); } public void testMissingProperty25() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "Foo.prototype.bar = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "(new FooAlias()).bar();"); } public void testMissingProperty26() throws Exception { testTypes( "/** @constructor */ var Foo = function() {};" + "/** @constructor */ var FooAlias = Foo;" + "FooAlias.prototype.bar = function() {};" + "(new Foo()).bar();"); } public void testMissingProperty27() throws Exception { testClosureTypes( "goog.addDependency('zzz.js', ['MissingType'], []);" + "/** @param {?MissingType} x */" + "function f(x) {" + " for (var parent = x; parent; parent = parent.getParent()) {}" + "}", null); } public void testMissingProperty28() throws Exception { testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foo;" + "}"); testTypes( "function f(obj) {" + " /** @type {*} */ obj.foo;" + " return obj.foox;" + "}", "Property foox never defined on obj"); } public void testMissingProperty29() throws Exception { // This used to emit a warning. testTypes( // externs "/** @constructor */ var Foo;" + "Foo.prototype.opera;" + "Foo.prototype.opera.postError;", "", null, false); } public void testMissingProperty30() throws Exception { testTypes( "/** @return {*} */" + "function f() {" + " return {};" + "}" + "f().a = 3;" + "/** @param {Object} y */ function g(y) { return y.a; }"); } public void testMissingProperty31() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Array} y */ function g(y) { return y.a; }"); } public void testMissingProperty32() throws Exception { testTypes( "/** @return {Array|number} */" + "function f() {" + " return [];" + "}" + "f().a = 3;" + "/** @param {Date} y */ function g(y) { return y.a; }", "Property a never defined on Date"); } public void testMissingProperty33() throws Exception { testTypes( "/** @param {Object} x */" + "function f(x) { !x.foo || x.foo(); }"); } public void testMissingProperty34() throws Exception { testTypes( "/** @fileoverview \n * @suppress {missingProperties} */" + "/** @constructor */ function Foo() {}" + "Foo.prototype.bar = function() { return this.a; };" + "Foo.prototype.baz = function() { this.b = 3; };"); } public void testDeclaredNativeTypeEquality() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Object() {};"); assertEquals(registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE), n.getFirstChild().getJSType()); } public void testUndefinedVar() throws Exception { Node n = parseAndTypeCheck("var undefined;"); assertEquals(registry.getNativeType(JSTypeNative.VOID_TYPE), n.getFirstChild().getFirstChild().getJSType()); } public void testFlowScopeBug1() throws Exception { Node n = parseAndTypeCheck("/** @param {number} a \n" + "* @param {number} b */\n" + "function f(a, b) {\n" + "/** @type number */" + "var i = 0;" + "for (; (i + a) < b; ++i) {}}"); // check the type of the add node for i + f assertEquals(registry.getNativeType(JSTypeNative.NUMBER_TYPE), n.getFirstChild().getLastChild().getLastChild().getFirstChild() .getNext().getFirstChild().getJSType()); } public void testFlowScopeBug2() throws Exception { Node n = parseAndTypeCheck("/** @constructor */ function Foo() {};\n" + "Foo.prototype.hi = false;" + "function foo(a, b) {\n" + " /** @type Array */" + " var arr;" + " /** @type number */" + " var iter;" + " for (iter = 0; iter < arr.length; ++ iter) {" + " /** @type Foo */" + " var afoo = arr[iter];" + " afoo;" + " }" + "}"); // check the type of afoo when referenced assertEquals(registry.createNullableType(registry.getType("Foo")), n.getLastChild().getLastChild().getLastChild().getLastChild() .getLastChild().getLastChild().getJSType()); } public void testAddSingletonGetter() { Node n = parseAndTypeCheck( "/** @constructor */ function Foo() {};\n" + "goog.addSingletonGetter(Foo);"); ObjectType o = (ObjectType) n.getFirstChild().getJSType(); assertEquals("function (): Foo", o.getPropertyType("getInstance").toString()); assertEquals("Foo", o.getPropertyType("instance_").toString()); } public void testTypeCheckStandaloneAST() throws Exception { Node n = compiler.parseTestCode("function Foo() { }"); typeCheck(n); TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler); Scope topScope = scopeCreator.createScope(n, null); Node second = compiler.parseTestCode("new Foo"); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, second); externAndJsRoot.setIsSyntheticBlock(true); new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, topScope, scopeCreator, CheckLevel.WARNING, CheckLevel.OFF) .process(null, second); assertEquals(1, compiler.getWarningCount()); assertEquals("cannot instantiate non-constructor", compiler.getWarnings()[0].description); } public void testBadTemplateType1() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {T} y\n" + "* @param {function(this:T, ...)} z\n" + "* @template T\n" + "*/\n" + "function f(x, y, z) {}\n" + "f(this, this, function() {});", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format(), true); } public void testBadTemplateType2() throws Exception { testTypes( "/**\n" + "* @param {T} x\n" + "* @param {function(this:T, ...)} y\n" + "* @template T\n" + "*/\n" + "function f(x, y) {}\n" + "f(0, function() {});", TypeInference.TEMPLATE_TYPE_NOT_OBJECT_TYPE.format(), true); } public void testBadTemplateType3() throws Exception { testTypes( "/**\n" + " * @param {T} x\n" + " * @template T\n" + "*/\n" + "function f(x) {}\n" + "f(this);", TypeInference.TEMPLATE_TYPE_OF_THIS_EXPECTED.format(), true); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format(), true); } public void testActiveXObject() throws Exception { testTypes( "/** @type {Object} */ var x = new ActiveXObject();" + "/** @type { {impossibleProperty} } */ var y = new ActiveXObject();"); } private void checkObjectType(ObjectType objectType, String propertyName, JSType expectedType) { assertTrue("Expected " + objectType.getReferenceName() + " to have property " + propertyName, objectType.hasProperty(propertyName)); assertEquals("Expected " + objectType.getReferenceName() + "'s property " + propertyName + " to have type " + expectedType, expectedType, objectType.getPropertyType(propertyName)); } private void testTypes(String js) throws Exception { testTypes(js, (String) null); } private void testTypes(String js, String description) throws Exception { testTypes(js, description, false); } private void testTypes(String js, DiagnosticType type) throws Exception { testTypes(js, type.format(), false); } private void testClosureTypes(String js, String description) throws Exception { Node n = compiler.parseTestCode(js); Node externs = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); // For processing goog.addDependency for forward typedefs. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(null, n); CodingConvention convention = compiler.getCodingConvention(); new TypeCheck(compiler, new ClosureReverseAbstractInterpreter( convention, registry).append( new SemanticReverseAbstractInterpreter( convention, registry)) .getFirst(), registry) .processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (description == null) { assertEquals( "unexpected warning(s) : " + Joiner.on(", ").join(compiler.getWarnings()), 0, compiler.getWarningCount()); } else { assertEquals(1, compiler.getWarningCount()); assertEquals(description, compiler.getWarnings()[0].description); } } void testTypes(String js, String description, boolean isError) throws Exception { testTypes(DEFAULT_EXTERNS, js, description, isError); } void testTypes(String externs, String js, String description, boolean isError) throws Exception { Node n = parseAndTypeCheck(externs, js); JSError[] errors = compiler.getErrors(); if (description != null && isError) { assertTrue("expected an error", errors.length > 0); assertEquals(description, errors[0].description); errors = Arrays.asList(errors).subList(1, errors.length).toArray( new JSError[errors.length - 1]); } if (errors.length > 0) { fail("unexpected error(s):\n" + Joiner.on("\n").join(errors)); } JSError[] warnings = compiler.getWarnings(); if (description != null && !isError) { assertTrue("expected a warning", warnings.length > 0); assertEquals(description, warnings[0].description); warnings = Arrays.asList(warnings).subList(1, warnings.length).toArray( new JSError[warnings.length - 1]); } if (warnings.length > 0) { fail("unexpected warnings(s):\n" + Joiner.on("\n").join(warnings)); } } /** * Parses and type checks the JavaScript code. */ private Node parseAndTypeCheck(String js) { return parseAndTypeCheck(DEFAULT_EXTERNS, js); } private Node parseAndTypeCheck(String externs, String js) { return parseAndTypeCheckWithScope(externs, js).root; } /** * Parses and type checks the JavaScript code and returns the Scope used * whilst type checking. */ private TypeCheckResult parseAndTypeCheckWithScope(String js) { return parseAndTypeCheckWithScope(DEFAULT_EXTERNS, js); } private TypeCheckResult parseAndTypeCheckWithScope( String externs, String js) { compiler.init( Lists.newArrayList(JSSourceFile.fromCode("[externs]", externs)), Lists.newArrayList(JSSourceFile.fromCode("[testcode]", js)), compiler.getOptions()); Node n = compiler.getInput("[testcode]").getAstRoot(compiler); Node externsNode = compiler.getInput("[externs]").getAstRoot(compiler); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); assertEquals("parsing error: " + Joiner.on(", ").join(compiler.getErrors()), 0, compiler.getErrorCount()); Scope s = makeTypeCheck().processForTesting(externsNode, n); return new TypeCheckResult(n, s); } private Node typeCheck(Node n) { Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); externAndJsRoot.setIsSyntheticBlock(true); makeTypeCheck().processForTesting(null, n); return n; } private TypeCheck makeTypeCheck() { return new TypeCheck( compiler, new SemanticReverseAbstractInterpreter( compiler.getCodingConvention(), registry), registry, reportMissingOverrides, CheckLevel.OFF); } void testTypes(String js, String[] warnings) throws Exception { Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); Node externsNode = new Node(Token.BLOCK); Node externAndJsRoot = new Node(Token.BLOCK, externsNode, n); makeTypeCheck().processForTesting(null, n); assertEquals(0, compiler.getErrorCount()); if (warnings != null) { assertEquals(warnings.length, compiler.getWarningCount()); JSError[] messages = compiler.getWarnings(); for (int i = 0; i < warnings.length && i < compiler.getWarningCount(); i++) { assertEquals(warnings[i], messages[i].description); } } else { assertEquals(0, compiler.getWarningCount()); } } String suppressMissingProperty(String ... props) { String result = "function dummy(x) { "; for (String prop : props) { result += "x." + prop + " = 3;"; } return result + "}"; } private static class TypeCheckResult { private final Node root; private final Scope scope; private TypeCheckResult(Node root, Scope scope) { this.root = root; this.scope = scope; } } }
public void testMinusNegativeZero() { // Negative zero is weird, because we have to be able to distinguish // it from positive zero (there are some subtle differences in behavior). assertPrint("x- -0", "x- -0.0"); }
com.google.javascript.jscomp.CodePrinterTest::testMinusNegativeZero
test/com/google/javascript/jscomp/CodePrinterTest.java
1,374
test/com/google/javascript/jscomp/CodePrinterTest.java
testMinusNegativeZero
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; import java.util.List; public class CodePrinterTest extends TestCase { static Node parse(String js) { return parse(js, false); } static Node parse(String js, boolean checkTypes) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); // Allow getters and setters. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.initOptions(options); Node n = compiler.parseTestCode(js); if (checkTypes) { DefaultPassConfig passConfig = new DefaultPassConfig(null); CompilerPass typeResolver = passConfig.resolveTypes.create(compiler); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); externs.setIsSyntheticBlock(true); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); typeResolver.process(externs, n); CompilerPass inferTypes = passConfig.inferTypes.create(compiler); inferTypes.process(externs, n); } checkUnexpectedErrorsOrWarnings(compiler, 0); return n; } private static void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } String parsePrint(String js, boolean prettyprint, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, boolean preferLineBreakAtEof, int lineThreshold) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .setPreferLineBreakAtEndOfFile(preferLineBreakAtEof) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes, boolean tagAsStrict) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .setTagAsStrict(tagAsStrict) .build(); } String printNode(Node n) { return new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build(); } void assertPrintNode(String expectedJs, Node ast) { assertEquals(expectedJs, printNode(ast)); } public void testPrint() { assertPrint("10 + a + b", "10+a+b"); assertPrint("10 + (30*50)", "10+30*50"); assertPrint("with(x) { x + 3; }", "with(x)x+3"); assertPrint("\"aa'a\"", "\"aa'a\""); assertPrint("\"aa\\\"a\"", "'aa\"a'"); assertPrint("function foo()\n{return 10;}", "function foo(){return 10}"); assertPrint("a instanceof b", "a instanceof b"); assertPrint("typeof(a)", "typeof a"); assertPrint( "var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}", "var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}"); // Safari: needs ';' at the end of a throw statement assertPrint("function foo(){throw 'error';}", "function foo(){throw\"error\";}"); // Safari 3 needs a "{" around a single function assertPrint("if (true) function foo(){return}", "if(true){function foo(){return}}"); assertPrint("var x = 10; { var y = 20; }", "var x=10;var y=20"); assertPrint("while (x-- > 0);", "while(x-- >0);"); assertPrint("x-- >> 1", "x-- >>1"); assertPrint("(function () {})(); ", "(function(){})()"); // Associativity assertPrint("var a,b,c,d;a || (b&& c) && (a || d)", "var a,b,c,d;a||b&&c&&(a||d)"); assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)", "var a,b,c;a||b||c;a*b*c;a|b|c"); assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);", "var a,b,c;a/b/c;a/(b/c);a-(b-c)"); assertPrint("var a,b; a = b = 3;", "var a,b;a=b=3"); assertPrint("var a,b,c,d; a = (b = c = (d = 3));", "var a,b,c,d;a=b=c=d=3"); assertPrint("var a,b,c; a += (b = c += 3);", "var a,b,c;a+=b=c+=3"); assertPrint("var a,b,c; a *= (b -= c);", "var a,b,c;a*=b-=c"); // Break scripts assertPrint("'<script>'", "\"<script>\""); assertPrint("'</script>'", "\"<\\/script>\""); assertPrint("\"</script> </SCRIPT>\"", "\"<\\/script> <\\/SCRIPT>\""); assertPrint("'-->'", "\"--\\>\""); assertPrint("']]>'", "\"]]\\>\""); assertPrint("' --></script>'", "\" --\\><\\/script>\""); assertPrint("/--> <\\/script>/g", "/--\\> <\\/script>/g"); // Break HTML start comments. Certain versions of Webkit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"<\\!-- I am a string --\\>\""); // Precedence assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3"); assertPrint("(delete a[0])/10", "delete a[0]/10"); // optional '()' for new // simple new assertPrint("new A", "new A"); assertPrint("new A()", "new A"); assertPrint("new A('x')", "new A(\"x\")"); // calling instance method directly after new assertPrint("new A().a()", "(new A).a()"); assertPrint("(new A).a()", "(new A).a()"); // this case should be fixed assertPrint("new A('y').a()", "(new A(\"y\")).a()"); // internal class assertPrint("new A.B", "new A.B"); assertPrint("new A.B()", "new A.B"); assertPrint("new A.B('z')", "new A.B(\"z\")"); // calling instance method directly after new internal class assertPrint("(new A.B).a()", "(new A.B).a()"); assertPrint("new A.B().a()", "(new A.B).a()"); // this case should be fixed assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()"); // Operators: make sure we don't convert binary + and unary + into ++ assertPrint("x + +y", "x+ +y"); assertPrint("x - (-y)", "x- -y"); assertPrint("x++ +y", "x++ +y"); assertPrint("x-- -y", "x-- -y"); assertPrint("x++ -y", "x++-y"); // Label assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo"); assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo"); // Object literals. assertPrint("({})", "({})"); assertPrint("var x = {};", "var x={}"); assertPrint("({}).x", "({}).x"); assertPrint("({})['x']", "({})[\"x\"]"); assertPrint("({}) instanceof Object", "({})instanceof Object"); assertPrint("({}) || 1", "({})||1"); assertPrint("1 || ({})", "1||{}"); assertPrint("({}) ? 1 : 2", "({})?1:2"); assertPrint("0 ? ({}) : 2", "0?{}:2"); assertPrint("0 ? 1 : ({})", "0?1:{}"); assertPrint("typeof ({})", "typeof{}"); assertPrint("f({})", "f({})"); // Anonymous function expressions. assertPrint("(function(){})", "(function(){})"); assertPrint("(function(){})()", "(function(){})()"); assertPrint("(function(){})instanceof Object", "(function(){})instanceof Object"); assertPrint("(function(){}).bind().call()", "(function(){}).bind().call()"); assertPrint("var x = function() { };", "var x=function(){}"); assertPrint("var x = function() { }();", "var x=function(){}()"); assertPrint("(function() {}), 2", "(function(){}),2"); // Name functions expression. assertPrint("(function f(){})", "(function f(){})"); // Function declaration. assertPrint("function f(){}", "function f(){}"); // Make sure we don't treat non-latin character escapes as raw strings. assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})"); assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})"); // Test if statement and for statements with single statements in body. assertPrint("if (true) { alert();}", "if(true)alert()"); assertPrint("if (false) {} else {alert(\"a\");}", "if(false);else alert(\"a\")"); assertPrint("for(;;) { alert();};", "for(;;)alert()"); assertPrint("do { alert(); } while(true);", "do alert();while(true)"); assertPrint("myLabel: { alert();}", "myLabel:alert()"); assertPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;)continue myLabel"); // Test nested var statement assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4"); // Non-latin identifier. Make sure we keep them escaped. assertPrint("\\u00fb", "\\u00fb"); assertPrint("\\u00fa=1", "\\u00fa=1"); assertPrint("function \\u00f9(){}", "function \\u00f9(){}"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl"); // Test the right-associative unary operators for spurious parens assertPrint("! ! true", "!!true"); assertPrint("!(!(true))", "!!true"); assertPrint("typeof(void(0))", "typeof void 0"); assertPrint("typeof(void(!0))", "typeof void!0"); assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus assertPrint("+(--x)", "+--x"); assertPrint("-(++x)", "-++x"); // needs a space to prevent an ambiguous parse assertPrint("-(--x)", "- --x"); assertPrint("!(~~5)", "!~~5"); assertPrint("~(a/b)", "~(a/b)"); // Preserve parens to overcome greedy binding of NEW assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)"); assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)"); assertPrint("new (new foobar(x)).factory(baz)", "new (new foobar(x)).factory(baz)"); // Make sure that HOOK is right associative assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e"); assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e"); assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e"); // Test nested ifs assertPrint("if (x) if (y); else;", "if(x)if(y);else;"); // Test comma. assertPrint("a,b,c", "a,b,c"); assertPrint("(a,b),c", "a,b,c"); assertPrint("a,(b,c)", "a,b,c"); assertPrint("x=a,b,c", "x=a,b,c"); assertPrint("x=(a,b),c", "x=(a,b),c"); assertPrint("x=a,(b,c)", "x=a,b,c"); assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c"); assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)"); assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]"); assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]"); assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]"); assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]"); assertPrint("var x=(a,b)", "var x=(a,b)"); assertPrint("var x=a,b,c", "var x=a,b,c"); assertPrint("var x=(a,b),c", "var x=(a,b),c"); assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)"); assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)"); assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)"); assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)"); assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))"); assertPrint("({}) , 1 , 2", "({}),1,2"); assertPrint("({}) , {} , {}", "({}),{},{}"); // EMPTY nodes assertPrint("if (x){}", "if(x);"); assertPrint("if(x);", "if(x);"); assertPrint("if(x)if(y);", "if(x)if(y);"); assertPrint("if(x){if(y);}", "if(x)if(y);"); assertPrint("if(x){if(y){};;;}", "if(x)if(y);"); assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}"); } public void testPrintArray() { assertPrint("[void 0, void 0]", "[void 0,void 0]"); assertPrint("[undefined, undefined]", "[undefined,undefined]"); assertPrint("[ , , , undefined]", "[,,,undefined]"); assertPrint("[ , , , 0]", "[,,,0]"); } public void testHook() { assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2"); assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2"); assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2"); assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2"); assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2"); assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2"); assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2"); assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)"); assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x"); assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x"); assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x"); assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3"); } public void testPrintInOperatorInForLoop() { // Check for in expression in for's init expression. // Check alone, with + (higher precedence), with ?: (lower precedence), // and with conditional. assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}", "var a={};for(var i=(\"length\"in a);i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}", "var a={};for(var i=(\"length\"in a)?0:1;i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}", "var a={};for(var i=(\"length\"in a)+1;i;);"); assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);", "var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);"); assertPrint("var a={};for (var i = a || a || (\"size\" in a);;);", "var a={};for(var i=a||a||(\"size\"in a);;);"); // Test works with unary operators and calls. assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}", "var a={};for(var i=-(\"length\"in a);i;);"); assertPrint("var a={};function b_(p){ return p;};" + "for(var i=1,j=b_(\"length\" in a);;) {}", "var a={};function b_(p){return p}" + "for(var i=1,j=b_(\"length\"in a);;);"); // Test we correctly handle an in operator in the test clause. assertPrint("var a={}; for (;(\"length\" in a);) {}", "var a={};for(;\"length\"in a;);"); } public void testLiteralProperty() { assertPrint("(64).toString()", "(64).toString()"); } private void assertPrint(String js, String expected) { parse(expected); // validate the expected string is valid js assertEquals(expected, parsePrint(js, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } // Make sure that the code generator doesn't associate an // else clause with the wrong if clause. public void testAmbiguousElseClauses() { assertPrintNode("if(x)if(y);else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), // ELSE clause for the inner if new Node(Token.BLOCK))))); assertPrintNode("if(x){if(y);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK))), // ELSE clause for the outer if new Node(Token.BLOCK))); assertPrintNode("if(x)if(y);else{if(z);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "z"), new Node(Token.BLOCK))))), // ELSE clause for the outermost if new Node(Token.BLOCK))); } public void testLineBreak() { // line break after function if in a statement context assertLineBreak("function a() {}\n" + "function b() {}", "function a(){}\n" + "function b(){}\n"); // line break after ; after a function assertLineBreak("var a = {};\n" + "a.foo = function () {}\n" + "function b() {}", "var a={};a.foo=function(){};\n" + "function b(){}\n"); // break after comma after a function assertLineBreak("var a = {\n" + " b: function() {},\n" + " c: function() {}\n" + "};\n" + "alert(a);", "var a={b:function(){},\n" + "c:function(){}};\n" + "alert(a)"); } private void assertLineBreak(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } public void testPreferLineBreakAtEndOfFile() { // short final line, no previous break, do nothing assertLineBreakAtEndOfFile( "\"1234567890\";", "\"1234567890\"", "\"1234567890\""); // short final line, shift previous break to end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"1234567890\"", "\"123456789012345678901234567890\";\n\"1234567890\"", "\"123456789012345678901234567890\";\"1234567890\";\n"); // long final line, no previous break, add a break at end assertLineBreakAtEndOfFile( "\"1234567890\";\"12345678901234567890\";", "\"1234567890\";\"12345678901234567890\"", "\"1234567890\";\"12345678901234567890\";\n"); // long final line, previous break, add a break at end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"12345678901234567890\";", "\"123456789012345678901234567890\";\n\"12345678901234567890\"", "\"123456789012345678901234567890\";\n\"12345678901234567890\";\n"); } private void assertLineBreakAtEndOfFile(String js, String expectedWithoutBreakAtEnd, String expectedWithBreakAtEnd) { assertEquals(expectedWithoutBreakAtEnd, parsePrint(js, false, false, false, 30)); assertEquals(expectedWithBreakAtEnd, parsePrint(js, false, false, true, 30)); } public void testPrettyPrinter() { // Ensure that the pretty printer inserts line breaks at appropriate // places. assertPrettyPrint("(function(){})();","(function() {\n})();\n"); assertPrettyPrint("var a = (function() {});alert(a);", "var a = function() {\n};\nalert(a);\n"); // Check we correctly handle putting brackets around all if clauses so // we can put breakpoints inside statements. assertPrettyPrint("if (1) {}", "if(1) {\n" + "}\n"); assertPrettyPrint("if (1) {alert(\"\");}", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1)alert(\"\");", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1) {alert();alert();}", "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); // Don't add blocks if they weren't there already. assertPrettyPrint("label: alert();", "label:alert();\n"); // But if statements and loops get blocks automagically. assertPrettyPrint("if (1) alert();", "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for (;;) alert();", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("while (1) alert();", "while(1) {\n" + " alert()\n" + "}\n"); // Do we put else clauses in blocks? assertPrettyPrint("if (1) {} else {alert(a);}", "if(1) {\n" + "}else {\n alert(a)\n}\n"); // Do we add blocks to else clauses? assertPrettyPrint("if (1) alert(a); else alert(b);", "if(1) {\n" + " alert(a)\n" + "}else {\n" + " alert(b)\n" + "}\n"); // Do we put for bodies in blocks? assertPrettyPrint("for(;;) { alert();}", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for(;;) {}", "for(;;) {\n" + "}\n"); assertPrettyPrint("for(;;) { alert(); alert(); }", "for(;;) {\n" + " alert();\n" + " alert()\n" + "}\n"); // How about do loops? assertPrettyPrint("do { alert(); } while(true);", "do {\n" + " alert()\n" + "}while(true);\n"); // label? assertPrettyPrint("myLabel: { alert();}", "myLabel: {\n" + " alert()\n" + "}\n"); // Don't move the label on a loop, because then break {label} and // continue {label} won't work. assertPrettyPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;) {\n" + " continue myLabel\n" + "}\n"); assertPrettyPrint("var a;", "var a;\n"); } public void testPrettyPrinter2() { assertPrettyPrint( "if(true) f();", "if(true) {\n" + " f()\n" + "}\n"); assertPrettyPrint( "if (true) { f() } else { g() }", "if(true) {\n" + " f()\n" + "}else {\n" + " g()\n" + "}\n"); assertPrettyPrint( "if(true) f(); for(;;) g();", "if(true) {\n" + " f()\n" + "}\n" + "for(;;) {\n" + " g()\n" + "}\n"); } public void testPrettyPrinter3() { assertPrettyPrint( "try {} catch(e) {}if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} finally {}if (1) {alert();alert();}", "try {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} catch(e) {} finally {} if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); } public void testPrettyPrinter4() { assertPrettyPrint( "function f() {}if (1) {alert();}", "function f() {\n" + "}\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "var f = function() {};if (1) {alert();}", "var f = function() {\n" + "};\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {})();if (1) {alert();}", "(function() {\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {alert();alert();})();if (1) {alert();}", "(function() {\n" + " alert();\n" + " alert()\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); } public void testTypeAnnotations() { assertTypeAnnotations( "/** @constructor */ function Foo(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "function Foo() {\n}\n"); } public void testTypeAnnotationsTypeDef() { // TODO(johnlenz): It would be nice if there were some way to preserve // typedefs but currently they are resolved into the basic types in the // type registry. assertTypeAnnotations( "/** @typedef {Array.<number>} */ goog.java.Long;\n" + "/** @param {!goog.java.Long} a*/\n" + "function f(a){};\n", "goog.java.Long;\n" + "/**\n" + " * @param {(Array.<number>|null)} a\n" + " * @return {undefined}\n" + " */\n" + "function f(a) {\n}\n"); } public void testTypeAnnotationsAssign() { assertTypeAnnotations("/** @constructor */ var Foo = function(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "var Foo = function() {\n};\n"); } public void testTypeAnnotationsNamespace() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n"); } public void testTypeAnnotationsMemberSubclass() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};" + "/** @constructor \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo = function(){};" + "/** @interface \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @extends {a.Foo}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMultipleInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo1 = function(){};" + "/** @interface */ a.Foo2 = function(){};" + "/** @interface \n @extends {a.Foo1} \n @extends {a.Foo2} */" + "a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo1 = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.Foo2 = function() {\n};\n" + "/**\n * @extends {a.Foo1}\n" + " * @extends {a.Foo2}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMember() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}" + "/** @param {string} foo\n" + " * @return {number} */\n" + "a.Foo.prototype.foo = function(foo) { return 3; };" + "/** @type {string|undefined} */" + "a.Foo.prototype.bar = '';", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n" + " * @param {string} foo\n" + " * @return {number}\n" + " */\n" + "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n" + "/** @type {string} */\n" + "a.Foo.prototype.bar = \"\";\n"); } public void testTypeAnnotationsImplements() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};\n" + "/** @interface */ a.I = function(){};\n" + "/** @interface */ a.I2 = function(){};\n" + "/** @constructor \n @extends {a.Foo}\n" + " * @implements {a.I} \n @implements {a.I2}\n" + "*/ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I2 = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @implements {a.I}\n" + " * @implements {a.I2}\n * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsDispatcher1() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " * @javadispatch \n" + " */\n" + "a.Foo = function(){}", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " * @javadispatch\n" + " */\n" + "a.Foo = function() {\n" + "};\n"); } public void testTypeAnnotationsDispatcher2() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " */\n" + "a.Foo = function(){}\n" + "/**\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {};", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " */\n" + "a.Foo = function() {\n" + "};\n" + "/**\n" + " * @return {undefined}\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {\n" + "};\n"); } public void testU2UFunctionTypeAnnotation() { assertTypeAnnotations( "/** @type {!Function} */ var x = function() {}", "/**\n * @constructor\n */\nvar x = function() {\n};\n"); } public void testEmitUnknownParamTypesAsAllType() { assertTypeAnnotations( "var a = function(x) {}", "/**\n" + " * @param {*} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testOptionalTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {string=} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {string=} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testVariableArgumentsTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {...string} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {...string} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testTempConstructor() { assertTypeAnnotations( "var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" + " /**\n * @constructor\n */\nfunction t2() {}\n" + " t1.prototype = t2.prototype}", "/**\n * @return {undefined}\n */\nvar x = function() {\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t1() {\n }\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t2() {\n }\n" + " t1.prototype = t2.prototype\n};\n" ); } public void testEnumAnnotation1() { assertTypeAnnotations( "/** @enum {string} */ var Enum = {FOO: 'x', BAR: 'y'};", "/** @enum {string} */\nvar Enum = {FOO:\"x\", BAR:\"y\"};\n"); } public void testEnumAnnotation2() { assertTypeAnnotations( "var goog = goog || {};" + "/** @enum {string} */ goog.Enum = {FOO: 'x', BAR: 'y'};" + "/** @const */ goog.Enum2 = goog.x ? {} : goog.Enum;", "var goog = goog || {};\n" + "/** @enum {string} */\ngoog.Enum = {FOO:\"x\", BAR:\"y\"};\n" + "/** @type {(Object|{})} */\ngoog.Enum2 = goog.x ? {} : goog.Enum;\n"); } private void assertPrettyPrint(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertTypeAnnotations(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true)); } public void testSubtraction() { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("x - -4"); assertEquals(0, compiler.getErrorCount()); assertEquals( "x- -4", new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build()); } public void testFunctionWithCall() { assertPrint( "var user = new function() {" + "alert(\"foo\")}", "var user=new function(){" + "alert(\"foo\")}"); assertPrint( "var user = new function() {" + "this.name = \"foo\";" + "this.local = function(){alert(this.name)};}", "var user=new function(){" + "this.name=\"foo\";" + "this.local=function(){alert(this.name)}}"); } public void testLineLength() { // list assertLineLength("var aba,bcb,cdc", "var aba,bcb," + "\ncdc"); // operators, and two breaks assertLineLength( "\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"", "\"foo\"+\"bar,baz,bomb\"+" + "\n\"whee\"+\";long-string\"+" + "\n\"aaa\""); // assignment assertLineLength("var abazaba=1234", "var abazaba=" + "\n1234"); // statements assertLineLength("var abab=1;var bab=2", "var abab=1;" + "\nvar bab=2"); // don't break regexes assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a", "var a=/some[reg](ex),with.*we?rd|chars/i;" + "\nvar b=a"); // don't break strings assertLineLength("var a=\"foo,{bar};baz\";var b=a", "var a=\"foo,{bar};baz\";" + "\nvar b=a"); // don't break before post inc/dec assertLineLength("var a=\"a\";a++;var b=\"bbb\";", "var a=\"a\";a++;\n" + "var b=\"bbb\""); } private void assertLineLength(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, 10)); } public void testParsePrintParse() { testReparse("3;"); testReparse("var a = b;"); testReparse("var x, y, z;"); testReparse("try { foo() } catch(e) { bar() }"); testReparse("try { foo() } catch(e) { bar() } finally { stuff() }"); testReparse("try { foo() } finally { stuff() }"); testReparse("throw 'me'"); testReparse("function foo(a) { return a + 4; }"); testReparse("function foo() { return; }"); testReparse("var a = function(a, b) { foo(); return a + b; }"); testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];"); testReparse("v = (5, 6, 7, 8)"); testReparse("d = 34.0; x = 0; y = .3; z = -22"); testReparse("d = -x; t = !x + ~y;"); testReparse("'hi'; /* just a test */ stuff(a,b) \n" + " foo(); // and another \n" + " bar();"); testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;"); testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5"); testReparse("a = (2 + 3) * 4;"); testReparse("a = 1 + (2 + 3) + 4;"); testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());"); testReparse("a = b | c || d ^ e " + "&& f & !g != h << i <= j < k >>> l > m * n % !o"); testReparse("a == b; a != b; a === b; a == b == a;" + " (a == b) == a; a == (b == a);"); testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;"); testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }"); testReparse("for (var i in a) b += i;"); testReparse("for (var i = 0; i < 10; i++){ b /= 2;" + " if (b == 2)break;else continue;}"); testReparse("for (x = 0; x < 10; x++) a /= 2;"); testReparse("for (;;) a++;"); testReparse("while(true) { blah(); }while(true) blah();"); testReparse("do stuff(); while(a>b);"); testReparse("[0, null, , true, false, this];"); testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');"); testReparse("new Foo; new Bar(a, b,c);"); testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;"); testReparse("delete foo['bar']; delete foo;"); testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };"); testReparse("switch(a) { case 2: case 3: stuff(); break;" + "case 4: morestuff(); break; default: done();}"); testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;"); testReparse("a.v = b.v; x['foo'] = y['zoo'];"); testReparse("'test' in x; 3 in x; a in x;"); testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'"); testReparse("x.__proto__;"); } private void testReparse(String code) { Compiler compiler = new Compiler(); Node parse1 = parse(code); Node parse2 = parse(new CodePrinter.Builder(parse1).build()); String explanation = parse1.checkTreeEquals(parse2); assertNull("\nExpected: " + compiler.toSource(parse1) + "\nResult: " + compiler.toSource(parse2) + "\n" + explanation, explanation); } public void testDoLoopIECompatiblity() { // Do loops within IFs cause syntax errors in IE6 and IE7. assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("function f(){if(e1)do foo();while(e2)else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x)do{foo()}while(y);else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x){do{foo()}while(y)}", "if(x){do foo();while(y)}"); assertPrint("if(x)do{foo()}while(y);", "if(x){do foo();while(y)}"); assertPrint("if(x)A:do{foo()}while(y);", "if(x){A:do foo();while(y)}"); assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);", "var i=0;a:do{b:do{i++;break b}while(0)}while(0)"); } public void testFunctionSafariCompatiblity() { // Functions within IFs cause syntax errors on Safari. assertPrint("function f(){if(e1){function goo(){return true}}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("function f(){if(e1)function goo(){return true}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("if(e1){function goo(){return true}}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)function goo(){return true}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)A:function goo(){return true}", "if(e1){A:function goo(){return true}}"); } public void testExponents() { assertPrintNumber("1", 1); assertPrintNumber("10", 10); assertPrintNumber("100", 100); assertPrintNumber("1E3", 1000); assertPrintNumber("1E4", 10000); assertPrintNumber("1E5", 100000); assertPrintNumber("-1", -1); assertPrintNumber("-10", -10); assertPrintNumber("-100", -100); assertPrintNumber("-1E3", -1000); assertPrintNumber("-12341234E4", -123412340000L); assertPrintNumber("1E18", 1000000000000000000L); assertPrintNumber("1E5", 100000.0); assertPrintNumber("100000.1", 100000.1); assertPrintNumber("1.0E-6", 0.000001); } // Make sure to test as both a String and a Node, because // negative numbers do not parse consistently from strings. private void assertPrintNumber(String expected, double number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } private void assertPrintNumber(String expected, int number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } public void testDirectEval() { assertPrint("eval('1');", "eval(\"1\")"); } public void testIndirectEval() { Node n = parse("eval('1');"); assertPrintNode("eval(\"1\")", n); n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp( Node.DIRECT_EVAL, false); assertPrintNode("(0,eval)(\"1\")", n); } public void testFreeCall1() { assertPrint("foo(a);", "foo(a)"); assertPrint("x.foo(a);", "x.foo(a)"); } public void testFreeCall2() { Node n = parse("foo(a);"); assertPrintNode("foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("foo(a)", n); } public void testFreeCall3() { Node n = parse("x.foo(a);"); assertPrintNode("x.foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("(0,x.foo)(a)", n); } public void testPrintScript() { // Verify that SCRIPT nodes not marked as synthetic are printed as // blocks. Node ast = new Node(Token.SCRIPT, new Node(Token.EXPR_RESULT, Node.newString("f")), new Node(Token.EXPR_RESULT, Node.newString("g"))); String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build(); assertEquals("\"f\";\n\"g\";\n", result); } public void testObjectLit() { assertPrint("({x:1})", "({x:1})"); assertPrint("var x=({x:1})", "var x={x:1}"); assertPrint("var x={'x':1}", "var x={\"x\":1}"); assertPrint("var x={1:1}", "var x={1:1}"); } public void testObjectLit2() { assertPrint("var x={1:1}", "var x={1:1}"); assertPrint("var x={'1':1}", "var x={1:1}"); assertPrint("var x={'1.0':1}", "var x={\"1.0\":1}"); assertPrint("var x={1.5:1}", "var x={\"1.5\":1}"); } public void testObjectLit3() { assertPrint("var x={3E9:1}", "var x={3E9:1}"); assertPrint("var x={'3000000000':1}", // More than 31 bits "var x={3E9:1}"); assertPrint("var x={'3000000001':1}", "var x={3000000001:1}"); assertPrint("var x={'6000000001':1}", // More than 32 bits "var x={6000000001:1}"); assertPrint("var x={\"12345678901234567\":1}", // More than 53 bits "var x={\"12345678901234567\":1}"); } public void testObjectLit4() { // More than 128 bits. assertPrint( "var x={\"123456789012345671234567890123456712345678901234567\":1}", "var x={\"123456789012345671234567890123456712345678901234567\":1}"); } public void testGetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {get a() {return 1}}", "var x={get a(){return 1}}"); assertPrint( "var x = {get a() {}, get b(){}}", "var x={get a(){},get b(){}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {get 1() {return 1}}", "var x={get 1(){return 1}}"); assertPrint( "var x = {get \"()\"() {return 1}}", "var x={get \"()\"(){return 1}}"); } public void testSetter() { assertPrint("var x = {}", "var x={}"); assertPrint( "var x = {set a(y) {return 1}}", "var x={set a(y){return 1}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {set 1(y) {return 1}}", "var x={set 1(y){return 1}}"); assertPrint( "var x = {set \"(x)\"(y) {return 1}}", "var x={set \"(x)\"(y){return 1}}"); } public void testNegCollapse() { // Collapse the negative symbol on numbers at generation time, // to match the Rhino behavior. assertPrint("var x = - - 2;", "var x=2"); assertPrint("var x = - (2);", "var x=-2"); } public void testStrict() { String result = parsePrint("var x", false, false, 0, false, true); assertEquals("'use strict';var x", result); } public void testArrayLiteral() { assertPrint("var x = [,];","var x=[,]"); assertPrint("var x = [,,];","var x=[,,]"); assertPrint("var x = [,s,,];","var x=[,s,,]"); assertPrint("var x = [,s];","var x=[,s]"); assertPrint("var x = [s,];","var x=[s]"); } public void testZero() { assertPrint("var x ='\\0';", "var x=\"\\x00\""); assertPrint("var x ='\\x00';", "var x=\"\\x00\""); assertPrint("var x ='\\u0000';", "var x=\"\\x00\""); assertPrint("var x ='\\u00003';", "var x=\"\\x003\""); } public void testUnicode() { assertPrint("var x ='\\x0f';", "var x=\"\\u000f\""); assertPrint("var x ='\\x68';", "var x=\"h\""); assertPrint("var x ='\\x7f';", "var x=\"\\u007f\""); } public void testUnicodeKeyword() { // keyword "if" assertPrint("var \\u0069\\u0066 = 1;", "var i\\u0066=1"); // keyword "var" assertPrint("var v\\u0061\\u0072 = 1;", "var va\\u0072=1"); // all are keyword "while" assertPrint("var w\\u0068\\u0069\\u006C\\u0065 = 1;" + "\\u0077\\u0068il\\u0065 = 2;" + "\\u0077h\\u0069le = 3;", "var whil\\u0065=1;whil\\u0065=2;whil\\u0065=3"); } public void testNumericKeys() { assertPrint("var x = {010: 1};", "var x={8:1}"); assertPrint("var x = {'010': 1};", "var x={\"010\":1}"); assertPrint("var x = {0x10: 1};", "var x={16:1}"); assertPrint("var x = {'0x10': 1};", "var x={\"0x10\":1}"); // I was surprised at this result too. assertPrint("var x = {.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'.2': 1};", "var x={\".2\":1}"); assertPrint("var x = {0.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'0.2': 1};", "var x={\"0.2\":1}"); } public void testIssue582() { assertPrint("var x = -0.0;", "var x=-0.0"); } public void testIssue601() { assertPrint("'\\v' == 'v'", "\"\\v\"==\"v\""); assertPrint("'\\u000B' == '\\v'", "\"\\x0B\"==\"\\v\""); assertPrint("'\\x0B' == '\\v'", "\"\\x0B\"==\"\\v\""); } public void testIssue620() { assertPrint("alert(/ / / / /);", "alert(/ // / /)"); assertPrint("alert(/ // / /);", "alert(/ // / /)"); } public void testIssue5746867() { assertPrint("var a = { '$\\\\' : 5 };", "var a={\"$\\\\\":5}"); } public void testManyCommas() { int numCommas = 10000; List<String> numbers = Lists.newArrayList("0", "1"); Node current = new Node(Token.COMMA, Node.newNumber(0), Node.newNumber(1)); for (int i = 2; i < numCommas; i++) { current = new Node(Token.COMMA, current); // 1000 is printed as 1E3, and screws up our test. int num = i % 1000; numbers.add(String.valueOf(num)); current.addChildToBack(Node.newNumber(num)); } String expected = Joiner.on(",").join(numbers); String actual = printNode(current).replace("\n", ""); assertEquals(expected, actual); } public void testMinusNegativeZero() { // Negative zero is weird, because we have to be able to distinguish // it from positive zero (there are some subtle differences in behavior). assertPrint("x- -0", "x- -0.0"); } }
// You are a professional Java test case writer, please create a test case named `testMinusNegativeZero` for the issue `Closure-657`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-657 // // ## Issue-Title: // Identifier minus a negative number needs a space between the "-"s // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the attached file with java -jar build/compiler.jar --compilation\_level ADVANCED\_OPTIMIZATIONS --js bulletfail.js --js\_output\_file cc.js // 2. Try to run the file in a JS engine, for example node cc.js // // **What is the expected output? What do you see instead?** // // The file does not parse properly, because it contains // // g--0.0 // // This is subtraction of a negative number, but it looks like JS engines interpret it as decrementing g, and then fail to parse the 0.0. (g- -0.0, with a space, would parse ok.) // // **What version of the product are you using? On what operating system?** // // Trunk closure compiler on Ubuntu // // **Please provide any additional information below.** // // public void testMinusNegativeZero() {
1,374
38
1,370
test/com/google/javascript/jscomp/CodePrinterTest.java
test
```markdown ## Issue-ID: Closure-657 ## Issue-Title: Identifier minus a negative number needs a space between the "-"s ## Issue-Description: **What steps will reproduce the problem?** 1. Compile the attached file with java -jar build/compiler.jar --compilation\_level ADVANCED\_OPTIMIZATIONS --js bulletfail.js --js\_output\_file cc.js 2. Try to run the file in a JS engine, for example node cc.js **What is the expected output? What do you see instead?** The file does not parse properly, because it contains g--0.0 This is subtraction of a negative number, but it looks like JS engines interpret it as decrementing g, and then fail to parse the 0.0. (g- -0.0, with a space, would parse ok.) **What version of the product are you using? On what operating system?** Trunk closure compiler on Ubuntu **Please provide any additional information below.** ``` You are a professional Java test case writer, please create a test case named `testMinusNegativeZero` for the issue `Closure-657`, utilizing the provided issue report information and the following function signature. ```java public void testMinusNegativeZero() { ```
1,370
[ "com.google.javascript.jscomp.CodeConsumer" ]
fdc04975ec59f8975fb692fdc1713ee1ea3c0789ae0f0312b462e728cecd89f8
public void testMinusNegativeZero()
// You are a professional Java test case writer, please create a test case named `testMinusNegativeZero` for the issue `Closure-657`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-657 // // ## Issue-Title: // Identifier minus a negative number needs a space between the "-"s // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the attached file with java -jar build/compiler.jar --compilation\_level ADVANCED\_OPTIMIZATIONS --js bulletfail.js --js\_output\_file cc.js // 2. Try to run the file in a JS engine, for example node cc.js // // **What is the expected output? What do you see instead?** // // The file does not parse properly, because it contains // // g--0.0 // // This is subtraction of a negative number, but it looks like JS engines interpret it as decrementing g, and then fail to parse the 0.0. (g- -0.0, with a space, would parse ok.) // // **What version of the product are you using? On what operating system?** // // Trunk closure compiler on Ubuntu // // **Please provide any additional information below.** // //
Closure
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import junit.framework.TestCase; import java.util.List; public class CodePrinterTest extends TestCase { static Node parse(String js) { return parse(js, false); } static Node parse(String js, boolean checkTypes) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); // Allow getters and setters. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.initOptions(options); Node n = compiler.parseTestCode(js); if (checkTypes) { DefaultPassConfig passConfig = new DefaultPassConfig(null); CompilerPass typeResolver = passConfig.resolveTypes.create(compiler); Node externs = new Node(Token.SCRIPT); externs.setInputId(new InputId("externs")); externs.setIsSyntheticBlock(true); Node externAndJsRoot = new Node(Token.BLOCK, externs, n); externAndJsRoot.setIsSyntheticBlock(true); typeResolver.process(externs, n); CompilerPass inferTypes = passConfig.inferTypes.create(compiler); inferTypes.process(externs, n); } checkUnexpectedErrorsOrWarnings(compiler, 0); return n; } private static void checkUnexpectedErrorsOrWarnings( Compiler compiler, int expected) { int actual = compiler.getErrors().length + compiler.getWarnings().length; if (actual != expected) { String msg = ""; for (JSError err : compiler.getErrors()) { msg += "Error:" + err.toString() + "\n"; } for (JSError err : compiler.getWarnings()) { msg += "Warning:" + err.toString() + "\n"; } assertEquals("Unexpected warnings or errors.\n " + msg, expected, actual); } } String parsePrint(String js, boolean prettyprint, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold) { return new CodePrinter.Builder(parse(js)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak).build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, boolean preferLineBreakAtEof, int lineThreshold) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .setPreferLineBreakAtEndOfFile(preferLineBreakAtEof) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .build(); } String parsePrint(String js, boolean prettyprint, boolean lineBreak, int lineThreshold, boolean outputTypes, boolean tagAsStrict) { return new CodePrinter.Builder(parse(js, true)).setPrettyPrint(prettyprint) .setOutputTypes(outputTypes) .setLineLengthThreshold(lineThreshold).setLineBreak(lineBreak) .setTagAsStrict(tagAsStrict) .build(); } String printNode(Node n) { return new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build(); } void assertPrintNode(String expectedJs, Node ast) { assertEquals(expectedJs, printNode(ast)); } public void testPrint() { assertPrint("10 + a + b", "10+a+b"); assertPrint("10 + (30*50)", "10+30*50"); assertPrint("with(x) { x + 3; }", "with(x)x+3"); assertPrint("\"aa'a\"", "\"aa'a\""); assertPrint("\"aa\\\"a\"", "'aa\"a'"); assertPrint("function foo()\n{return 10;}", "function foo(){return 10}"); assertPrint("a instanceof b", "a instanceof b"); assertPrint("typeof(a)", "typeof a"); assertPrint( "var foo = x ? { a : 1 } : {a: 3, b:4, \"default\": 5, \"foo-bar\": 6}", "var foo=x?{a:1}:{a:3,b:4,\"default\":5,\"foo-bar\":6}"); // Safari: needs ';' at the end of a throw statement assertPrint("function foo(){throw 'error';}", "function foo(){throw\"error\";}"); // Safari 3 needs a "{" around a single function assertPrint("if (true) function foo(){return}", "if(true){function foo(){return}}"); assertPrint("var x = 10; { var y = 20; }", "var x=10;var y=20"); assertPrint("while (x-- > 0);", "while(x-- >0);"); assertPrint("x-- >> 1", "x-- >>1"); assertPrint("(function () {})(); ", "(function(){})()"); // Associativity assertPrint("var a,b,c,d;a || (b&& c) && (a || d)", "var a,b,c,d;a||b&&c&&(a||d)"); assertPrint("var a,b,c; a || (b || c); a * (b * c); a | (b | c)", "var a,b,c;a||b||c;a*b*c;a|b|c"); assertPrint("var a,b,c; a / b / c;a / (b / c); a - (b - c);", "var a,b,c;a/b/c;a/(b/c);a-(b-c)"); assertPrint("var a,b; a = b = 3;", "var a,b;a=b=3"); assertPrint("var a,b,c,d; a = (b = c = (d = 3));", "var a,b,c,d;a=b=c=d=3"); assertPrint("var a,b,c; a += (b = c += 3);", "var a,b,c;a+=b=c+=3"); assertPrint("var a,b,c; a *= (b -= c);", "var a,b,c;a*=b-=c"); // Break scripts assertPrint("'<script>'", "\"<script>\""); assertPrint("'</script>'", "\"<\\/script>\""); assertPrint("\"</script> </SCRIPT>\"", "\"<\\/script> <\\/SCRIPT>\""); assertPrint("'-->'", "\"--\\>\""); assertPrint("']]>'", "\"]]\\>\""); assertPrint("' --></script>'", "\" --\\><\\/script>\""); assertPrint("/--> <\\/script>/g", "/--\\> <\\/script>/g"); // Break HTML start comments. Certain versions of Webkit // begin an HTML comment when they see this. assertPrint("'<!-- I am a string -->'", "\"<\\!-- I am a string --\\>\""); // Precedence assertPrint("a ? delete b[0] : 3", "a?delete b[0]:3"); assertPrint("(delete a[0])/10", "delete a[0]/10"); // optional '()' for new // simple new assertPrint("new A", "new A"); assertPrint("new A()", "new A"); assertPrint("new A('x')", "new A(\"x\")"); // calling instance method directly after new assertPrint("new A().a()", "(new A).a()"); assertPrint("(new A).a()", "(new A).a()"); // this case should be fixed assertPrint("new A('y').a()", "(new A(\"y\")).a()"); // internal class assertPrint("new A.B", "new A.B"); assertPrint("new A.B()", "new A.B"); assertPrint("new A.B('z')", "new A.B(\"z\")"); // calling instance method directly after new internal class assertPrint("(new A.B).a()", "(new A.B).a()"); assertPrint("new A.B().a()", "(new A.B).a()"); // this case should be fixed assertPrint("new A.B('w').a()", "(new A.B(\"w\")).a()"); // Operators: make sure we don't convert binary + and unary + into ++ assertPrint("x + +y", "x+ +y"); assertPrint("x - (-y)", "x- -y"); assertPrint("x++ +y", "x++ +y"); assertPrint("x-- -y", "x-- -y"); assertPrint("x++ -y", "x++-y"); // Label assertPrint("foo:for(;;){break foo;}", "foo:for(;;)break foo"); assertPrint("foo:while(1){continue foo;}", "foo:while(1)continue foo"); // Object literals. assertPrint("({})", "({})"); assertPrint("var x = {};", "var x={}"); assertPrint("({}).x", "({}).x"); assertPrint("({})['x']", "({})[\"x\"]"); assertPrint("({}) instanceof Object", "({})instanceof Object"); assertPrint("({}) || 1", "({})||1"); assertPrint("1 || ({})", "1||{}"); assertPrint("({}) ? 1 : 2", "({})?1:2"); assertPrint("0 ? ({}) : 2", "0?{}:2"); assertPrint("0 ? 1 : ({})", "0?1:{}"); assertPrint("typeof ({})", "typeof{}"); assertPrint("f({})", "f({})"); // Anonymous function expressions. assertPrint("(function(){})", "(function(){})"); assertPrint("(function(){})()", "(function(){})()"); assertPrint("(function(){})instanceof Object", "(function(){})instanceof Object"); assertPrint("(function(){}).bind().call()", "(function(){}).bind().call()"); assertPrint("var x = function() { };", "var x=function(){}"); assertPrint("var x = function() { }();", "var x=function(){}()"); assertPrint("(function() {}), 2", "(function(){}),2"); // Name functions expression. assertPrint("(function f(){})", "(function f(){})"); // Function declaration. assertPrint("function f(){}", "function f(){}"); // Make sure we don't treat non-latin character escapes as raw strings. assertPrint("({ 'a': 4, '\\u0100': 4 })", "({\"a\":4,\"\\u0100\":4})"); assertPrint("({ a: 4, '\\u0100': 4 })", "({a:4,\"\\u0100\":4})"); // Test if statement and for statements with single statements in body. assertPrint("if (true) { alert();}", "if(true)alert()"); assertPrint("if (false) {} else {alert(\"a\");}", "if(false);else alert(\"a\")"); assertPrint("for(;;) { alert();};", "for(;;)alert()"); assertPrint("do { alert(); } while(true);", "do alert();while(true)"); assertPrint("myLabel: { alert();}", "myLabel:alert()"); assertPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;)continue myLabel"); // Test nested var statement assertPrint("if (true) var x; x = 4;", "if(true)var x;x=4"); // Non-latin identifier. Make sure we keep them escaped. assertPrint("\\u00fb", "\\u00fb"); assertPrint("\\u00fa=1", "\\u00fa=1"); assertPrint("function \\u00f9(){}", "function \\u00f9(){}"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("x.\\u00f8", "x.\\u00f8"); assertPrint("abc\\u4e00\\u4e01jkl", "abc\\u4e00\\u4e01jkl"); // Test the right-associative unary operators for spurious parens assertPrint("! ! true", "!!true"); assertPrint("!(!(true))", "!!true"); assertPrint("typeof(void(0))", "typeof void 0"); assertPrint("typeof(void(!0))", "typeof void!0"); assertPrint("+ - + + - + 3", "+-+ +-+3"); // chained unary plus/minus assertPrint("+(--x)", "+--x"); assertPrint("-(++x)", "-++x"); // needs a space to prevent an ambiguous parse assertPrint("-(--x)", "- --x"); assertPrint("!(~~5)", "!~~5"); assertPrint("~(a/b)", "~(a/b)"); // Preserve parens to overcome greedy binding of NEW assertPrint("new (foo.bar()).factory(baz)", "new (foo.bar().factory)(baz)"); assertPrint("new (bar()).factory(baz)", "new (bar().factory)(baz)"); assertPrint("new (new foobar(x)).factory(baz)", "new (new foobar(x)).factory(baz)"); // Make sure that HOOK is right associative assertPrint("a ? b : (c ? d : e)", "a?b:c?d:e"); assertPrint("a ? (b ? c : d) : e", "a?b?c:d:e"); assertPrint("(a ? b : c) ? d : e", "(a?b:c)?d:e"); // Test nested ifs assertPrint("if (x) if (y); else;", "if(x)if(y);else;"); // Test comma. assertPrint("a,b,c", "a,b,c"); assertPrint("(a,b),c", "a,b,c"); assertPrint("a,(b,c)", "a,b,c"); assertPrint("x=a,b,c", "x=a,b,c"); assertPrint("x=(a,b),c", "x=(a,b),c"); assertPrint("x=a,(b,c)", "x=a,b,c"); assertPrint("x=a,y=b,z=c", "x=a,y=b,z=c"); assertPrint("x=(a,y=b,z=c)", "x=(a,y=b,z=c)"); assertPrint("x=[a,b,c,d]", "x=[a,b,c,d]"); assertPrint("x=[(a,b,c),d]", "x=[(a,b,c),d]"); assertPrint("x=[(a,(b,c)),d]", "x=[(a,b,c),d]"); assertPrint("x=[a,(b,c,d)]", "x=[a,(b,c,d)]"); assertPrint("var x=(a,b)", "var x=(a,b)"); assertPrint("var x=a,b,c", "var x=a,b,c"); assertPrint("var x=(a,b),c", "var x=(a,b),c"); assertPrint("var x=a,b=(c,d)", "var x=a,b=(c,d)"); assertPrint("foo(a,b,c,d)", "foo(a,b,c,d)"); assertPrint("foo((a,b,c),d)", "foo((a,b,c),d)"); assertPrint("foo((a,(b,c)),d)", "foo((a,b,c),d)"); assertPrint("f(a+b,(c,d,(e,f,g)))", "f(a+b,(c,d,e,f,g))"); assertPrint("({}) , 1 , 2", "({}),1,2"); assertPrint("({}) , {} , {}", "({}),{},{}"); // EMPTY nodes assertPrint("if (x){}", "if(x);"); assertPrint("if(x);", "if(x);"); assertPrint("if(x)if(y);", "if(x)if(y);"); assertPrint("if(x){if(y);}", "if(x)if(y);"); assertPrint("if(x){if(y){};;;}", "if(x)if(y);"); assertPrint("if(x){;;function y(){};;}", "if(x){function y(){}}"); } public void testPrintArray() { assertPrint("[void 0, void 0]", "[void 0,void 0]"); assertPrint("[undefined, undefined]", "[undefined,undefined]"); assertPrint("[ , , , undefined]", "[,,,undefined]"); assertPrint("[ , , , 0]", "[,,,0]"); } public void testHook() { assertPrint("a ? b = 1 : c = 2", "a?b=1:c=2"); assertPrint("x = a ? b = 1 : c = 2", "x=a?b=1:c=2"); assertPrint("(x = a) ? b = 1 : c = 2", "(x=a)?b=1:c=2"); assertPrint("x, a ? b = 1 : c = 2", "x,a?b=1:c=2"); assertPrint("x, (a ? b = 1 : c = 2)", "x,a?b=1:c=2"); assertPrint("(x, a) ? b = 1 : c = 2", "(x,a)?b=1:c=2"); assertPrint("a ? (x, b) : c = 2", "a?(x,b):c=2"); assertPrint("a ? b = 1 : (x,c)", "a?b=1:(x,c)"); assertPrint("a ? b = 1 : c = 2 + x", "a?b=1:c=2+x"); assertPrint("(a ? b = 1 : c = 2) + x", "(a?b=1:c=2)+x"); assertPrint("a ? b = 1 : (c = 2) + x", "a?b=1:(c=2)+x"); assertPrint("a ? (b?1:2) : 3", "a?b?1:2:3"); } public void testPrintInOperatorInForLoop() { // Check for in expression in for's init expression. // Check alone, with + (higher precedence), with ?: (lower precedence), // and with conditional. assertPrint("var a={}; for (var i = (\"length\" in a); i;) {}", "var a={};for(var i=(\"length\"in a);i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) ? 0 : 1; i;) {}", "var a={};for(var i=(\"length\"in a)?0:1;i;);"); assertPrint("var a={}; for (var i = (\"length\" in a) + 1; i;) {}", "var a={};for(var i=(\"length\"in a)+1;i;);"); assertPrint("var a={};for (var i = (\"length\" in a|| \"size\" in a);;);", "var a={};for(var i=(\"length\"in a)||(\"size\"in a);;);"); assertPrint("var a={};for (var i = a || a || (\"size\" in a);;);", "var a={};for(var i=a||a||(\"size\"in a);;);"); // Test works with unary operators and calls. assertPrint("var a={}; for (var i = -(\"length\" in a); i;) {}", "var a={};for(var i=-(\"length\"in a);i;);"); assertPrint("var a={};function b_(p){ return p;};" + "for(var i=1,j=b_(\"length\" in a);;) {}", "var a={};function b_(p){return p}" + "for(var i=1,j=b_(\"length\"in a);;);"); // Test we correctly handle an in operator in the test clause. assertPrint("var a={}; for (;(\"length\" in a);) {}", "var a={};for(;\"length\"in a;);"); } public void testLiteralProperty() { assertPrint("(64).toString()", "(64).toString()"); } private void assertPrint(String js, String expected) { parse(expected); // validate the expected string is valid js assertEquals(expected, parsePrint(js, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } // Make sure that the code generator doesn't associate an // else clause with the wrong if clause. public void testAmbiguousElseClauses() { assertPrintNode("if(x)if(y);else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), // ELSE clause for the inner if new Node(Token.BLOCK))))); assertPrintNode("if(x){if(y);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK))), // ELSE clause for the outer if new Node(Token.BLOCK))); assertPrintNode("if(x)if(y);else{if(z);}else;", new Node(Token.IF, Node.newString(Token.NAME, "x"), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "y"), new Node(Token.BLOCK), new Node(Token.BLOCK, new Node(Token.IF, Node.newString(Token.NAME, "z"), new Node(Token.BLOCK))))), // ELSE clause for the outermost if new Node(Token.BLOCK))); } public void testLineBreak() { // line break after function if in a statement context assertLineBreak("function a() {}\n" + "function b() {}", "function a(){}\n" + "function b(){}\n"); // line break after ; after a function assertLineBreak("var a = {};\n" + "a.foo = function () {}\n" + "function b() {}", "var a={};a.foo=function(){};\n" + "function b(){}\n"); // break after comma after a function assertLineBreak("var a = {\n" + " b: function() {},\n" + " c: function() {}\n" + "};\n" + "alert(a);", "var a={b:function(){},\n" + "c:function(){}};\n" + "alert(a)"); } private void assertLineBreak(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } public void testPreferLineBreakAtEndOfFile() { // short final line, no previous break, do nothing assertLineBreakAtEndOfFile( "\"1234567890\";", "\"1234567890\"", "\"1234567890\""); // short final line, shift previous break to end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"1234567890\"", "\"123456789012345678901234567890\";\n\"1234567890\"", "\"123456789012345678901234567890\";\"1234567890\";\n"); // long final line, no previous break, add a break at end assertLineBreakAtEndOfFile( "\"1234567890\";\"12345678901234567890\";", "\"1234567890\";\"12345678901234567890\"", "\"1234567890\";\"12345678901234567890\";\n"); // long final line, previous break, add a break at end assertLineBreakAtEndOfFile( "\"123456789012345678901234567890\";\"12345678901234567890\";", "\"123456789012345678901234567890\";\n\"12345678901234567890\"", "\"123456789012345678901234567890\";\n\"12345678901234567890\";\n"); } private void assertLineBreakAtEndOfFile(String js, String expectedWithoutBreakAtEnd, String expectedWithBreakAtEnd) { assertEquals(expectedWithoutBreakAtEnd, parsePrint(js, false, false, false, 30)); assertEquals(expectedWithBreakAtEnd, parsePrint(js, false, false, true, 30)); } public void testPrettyPrinter() { // Ensure that the pretty printer inserts line breaks at appropriate // places. assertPrettyPrint("(function(){})();","(function() {\n})();\n"); assertPrettyPrint("var a = (function() {});alert(a);", "var a = function() {\n};\nalert(a);\n"); // Check we correctly handle putting brackets around all if clauses so // we can put breakpoints inside statements. assertPrettyPrint("if (1) {}", "if(1) {\n" + "}\n"); assertPrettyPrint("if (1) {alert(\"\");}", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1)alert(\"\");", "if(1) {\n" + " alert(\"\")\n" + "}\n"); assertPrettyPrint("if (1) {alert();alert();}", "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); // Don't add blocks if they weren't there already. assertPrettyPrint("label: alert();", "label:alert();\n"); // But if statements and loops get blocks automagically. assertPrettyPrint("if (1) alert();", "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for (;;) alert();", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("while (1) alert();", "while(1) {\n" + " alert()\n" + "}\n"); // Do we put else clauses in blocks? assertPrettyPrint("if (1) {} else {alert(a);}", "if(1) {\n" + "}else {\n alert(a)\n}\n"); // Do we add blocks to else clauses? assertPrettyPrint("if (1) alert(a); else alert(b);", "if(1) {\n" + " alert(a)\n" + "}else {\n" + " alert(b)\n" + "}\n"); // Do we put for bodies in blocks? assertPrettyPrint("for(;;) { alert();}", "for(;;) {\n" + " alert()\n" + "}\n"); assertPrettyPrint("for(;;) {}", "for(;;) {\n" + "}\n"); assertPrettyPrint("for(;;) { alert(); alert(); }", "for(;;) {\n" + " alert();\n" + " alert()\n" + "}\n"); // How about do loops? assertPrettyPrint("do { alert(); } while(true);", "do {\n" + " alert()\n" + "}while(true);\n"); // label? assertPrettyPrint("myLabel: { alert();}", "myLabel: {\n" + " alert()\n" + "}\n"); // Don't move the label on a loop, because then break {label} and // continue {label} won't work. assertPrettyPrint("myLabel: for(;;) continue myLabel;", "myLabel:for(;;) {\n" + " continue myLabel\n" + "}\n"); assertPrettyPrint("var a;", "var a;\n"); } public void testPrettyPrinter2() { assertPrettyPrint( "if(true) f();", "if(true) {\n" + " f()\n" + "}\n"); assertPrettyPrint( "if (true) { f() } else { g() }", "if(true) {\n" + " f()\n" + "}else {\n" + " g()\n" + "}\n"); assertPrettyPrint( "if(true) f(); for(;;) g();", "if(true) {\n" + " f()\n" + "}\n" + "for(;;) {\n" + " g()\n" + "}\n"); } public void testPrettyPrinter3() { assertPrettyPrint( "try {} catch(e) {}if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} finally {}if (1) {alert();alert();}", "try {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); assertPrettyPrint( "try {} catch(e) {} finally {} if (1) {alert();alert();}", "try {\n" + "}catch(e) {\n" + "}finally {\n" + "}\n" + "if(1) {\n" + " alert();\n" + " alert()\n" + "}\n"); } public void testPrettyPrinter4() { assertPrettyPrint( "function f() {}if (1) {alert();}", "function f() {\n" + "}\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "var f = function() {};if (1) {alert();}", "var f = function() {\n" + "};\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {})();if (1) {alert();}", "(function() {\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); assertPrettyPrint( "(function() {alert();alert();})();if (1) {alert();}", "(function() {\n" + " alert();\n" + " alert()\n" + "})();\n" + "if(1) {\n" + " alert()\n" + "}\n"); } public void testTypeAnnotations() { assertTypeAnnotations( "/** @constructor */ function Foo(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "function Foo() {\n}\n"); } public void testTypeAnnotationsTypeDef() { // TODO(johnlenz): It would be nice if there were some way to preserve // typedefs but currently they are resolved into the basic types in the // type registry. assertTypeAnnotations( "/** @typedef {Array.<number>} */ goog.java.Long;\n" + "/** @param {!goog.java.Long} a*/\n" + "function f(a){};\n", "goog.java.Long;\n" + "/**\n" + " * @param {(Array.<number>|null)} a\n" + " * @return {undefined}\n" + " */\n" + "function f(a) {\n}\n"); } public void testTypeAnnotationsAssign() { assertTypeAnnotations("/** @constructor */ var Foo = function(){}", "/**\n * @return {undefined}\n * @constructor\n */\n" + "var Foo = function() {\n};\n"); } public void testTypeAnnotationsNamespace() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n"); } public void testTypeAnnotationsMemberSubclass() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};" + "/** @constructor \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo = function(){};" + "/** @interface \n @extends {a.Foo} */ a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @extends {a.Foo}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMultipleInterface() { assertTypeAnnotations("var a = {};" + "/** @interface */ a.Foo1 = function(){};" + "/** @interface */ a.Foo2 = function(){};" + "/** @interface \n @extends {a.Foo1} \n @extends {a.Foo2} */" + "a.Bar = function(){}", "var a = {};\n" + "/**\n * @interface\n */\n" + "a.Foo1 = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.Foo2 = function() {\n};\n" + "/**\n * @extends {a.Foo1}\n" + " * @extends {a.Foo2}\n" + " * @interface\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsMember() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){}" + "/** @param {string} foo\n" + " * @return {number} */\n" + "a.Foo.prototype.foo = function(foo) { return 3; };" + "/** @type {string|undefined} */" + "a.Foo.prototype.bar = '';", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n" + " * @param {string} foo\n" + " * @return {number}\n" + " */\n" + "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n" + "/** @type {string} */\n" + "a.Foo.prototype.bar = \"\";\n"); } public void testTypeAnnotationsImplements() { assertTypeAnnotations("var a = {};" + "/** @constructor */ a.Foo = function(){};\n" + "/** @interface */ a.I = function(){};\n" + "/** @interface */ a.I2 = function(){};\n" + "/** @constructor \n @extends {a.Foo}\n" + " * @implements {a.I} \n @implements {a.I2}\n" + "*/ a.Bar = function(){}", "var a = {};\n" + "/**\n * @return {undefined}\n * @constructor\n */\n" + "a.Foo = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I = function() {\n};\n" + "/**\n * @interface\n */\n" + "a.I2 = function() {\n};\n" + "/**\n * @return {undefined}\n * @extends {a.Foo}\n" + " * @implements {a.I}\n" + " * @implements {a.I2}\n * @constructor\n */\n" + "a.Bar = function() {\n};\n"); } public void testTypeAnnotationsDispatcher1() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " * @javadispatch \n" + " */\n" + "a.Foo = function(){}", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " * @javadispatch\n" + " */\n" + "a.Foo = function() {\n" + "};\n"); } public void testTypeAnnotationsDispatcher2() { assertTypeAnnotations( "var a = {};\n" + "/** \n" + " * @constructor \n" + " */\n" + "a.Foo = function(){}\n" + "/**\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {};", "var a = {};\n" + "/**\n" + " * @return {undefined}\n" + " * @constructor\n" + " */\n" + "a.Foo = function() {\n" + "};\n" + "/**\n" + " * @return {undefined}\n" + " * @javadispatch\n" + " */\n" + "a.Foo.prototype.foo = function() {\n" + "};\n"); } public void testU2UFunctionTypeAnnotation() { assertTypeAnnotations( "/** @type {!Function} */ var x = function() {}", "/**\n * @constructor\n */\nvar x = function() {\n};\n"); } public void testEmitUnknownParamTypesAsAllType() { assertTypeAnnotations( "var a = function(x) {}", "/**\n" + " * @param {*} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testOptionalTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {string=} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {string=} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testVariableArgumentsTypesAnnotation() { assertTypeAnnotations( "/**\n" + " * @param {...string} x \n" + " */\n" + "var a = function(x) {}", "/**\n" + " * @param {...string} x\n" + " * @return {undefined}\n" + " */\n" + "var a = function(x) {\n};\n"); } public void testTempConstructor() { assertTypeAnnotations( "var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" + " /**\n * @constructor\n */\nfunction t2() {}\n" + " t1.prototype = t2.prototype}", "/**\n * @return {undefined}\n */\nvar x = function() {\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t1() {\n }\n" + " /**\n * @return {undefined}\n * @constructor\n */\n" + "function t2() {\n }\n" + " t1.prototype = t2.prototype\n};\n" ); } public void testEnumAnnotation1() { assertTypeAnnotations( "/** @enum {string} */ var Enum = {FOO: 'x', BAR: 'y'};", "/** @enum {string} */\nvar Enum = {FOO:\"x\", BAR:\"y\"};\n"); } public void testEnumAnnotation2() { assertTypeAnnotations( "var goog = goog || {};" + "/** @enum {string} */ goog.Enum = {FOO: 'x', BAR: 'y'};" + "/** @const */ goog.Enum2 = goog.x ? {} : goog.Enum;", "var goog = goog || {};\n" + "/** @enum {string} */\ngoog.Enum = {FOO:\"x\", BAR:\"y\"};\n" + "/** @type {(Object|{})} */\ngoog.Enum2 = goog.x ? {} : goog.Enum;\n"); } private void assertPrettyPrint(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD)); } private void assertTypeAnnotations(String js, String expected) { assertEquals(expected, parsePrint(js, true, false, CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true)); } public void testSubtraction() { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("x - -4"); assertEquals(0, compiler.getErrorCount()); assertEquals( "x- -4", new CodePrinter.Builder(n).setLineLengthThreshold( CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build()); } public void testFunctionWithCall() { assertPrint( "var user = new function() {" + "alert(\"foo\")}", "var user=new function(){" + "alert(\"foo\")}"); assertPrint( "var user = new function() {" + "this.name = \"foo\";" + "this.local = function(){alert(this.name)};}", "var user=new function(){" + "this.name=\"foo\";" + "this.local=function(){alert(this.name)}}"); } public void testLineLength() { // list assertLineLength("var aba,bcb,cdc", "var aba,bcb," + "\ncdc"); // operators, and two breaks assertLineLength( "\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"", "\"foo\"+\"bar,baz,bomb\"+" + "\n\"whee\"+\";long-string\"+" + "\n\"aaa\""); // assignment assertLineLength("var abazaba=1234", "var abazaba=" + "\n1234"); // statements assertLineLength("var abab=1;var bab=2", "var abab=1;" + "\nvar bab=2"); // don't break regexes assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a", "var a=/some[reg](ex),with.*we?rd|chars/i;" + "\nvar b=a"); // don't break strings assertLineLength("var a=\"foo,{bar};baz\";var b=a", "var a=\"foo,{bar};baz\";" + "\nvar b=a"); // don't break before post inc/dec assertLineLength("var a=\"a\";a++;var b=\"bbb\";", "var a=\"a\";a++;\n" + "var b=\"bbb\""); } private void assertLineLength(String js, String expected) { assertEquals(expected, parsePrint(js, false, true, 10)); } public void testParsePrintParse() { testReparse("3;"); testReparse("var a = b;"); testReparse("var x, y, z;"); testReparse("try { foo() } catch(e) { bar() }"); testReparse("try { foo() } catch(e) { bar() } finally { stuff() }"); testReparse("try { foo() } finally { stuff() }"); testReparse("throw 'me'"); testReparse("function foo(a) { return a + 4; }"); testReparse("function foo() { return; }"); testReparse("var a = function(a, b) { foo(); return a + b; }"); testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];"); testReparse("v = (5, 6, 7, 8)"); testReparse("d = 34.0; x = 0; y = .3; z = -22"); testReparse("d = -x; t = !x + ~y;"); testReparse("'hi'; /* just a test */ stuff(a,b) \n" + " foo(); // and another \n" + " bar();"); testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;"); testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5"); testReparse("a = (2 + 3) * 4;"); testReparse("a = 1 + (2 + 3) + 4;"); testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());"); testReparse("a = b | c || d ^ e " + "&& f & !g != h << i <= j < k >>> l > m * n % !o"); testReparse("a == b; a != b; a === b; a == b == a;" + " (a == b) == a; a == (b == a);"); testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;"); testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }"); testReparse("for (var i in a) b += i;"); testReparse("for (var i = 0; i < 10; i++){ b /= 2;" + " if (b == 2)break;else continue;}"); testReparse("for (x = 0; x < 10; x++) a /= 2;"); testReparse("for (;;) a++;"); testReparse("while(true) { blah(); }while(true) blah();"); testReparse("do stuff(); while(a>b);"); testReparse("[0, null, , true, false, this];"); testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');"); testReparse("new Foo; new Bar(a, b,c);"); testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;"); testReparse("delete foo['bar']; delete foo;"); testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };"); testReparse("switch(a) { case 2: case 3: stuff(); break;" + "case 4: morestuff(); break; default: done();}"); testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;"); testReparse("a.v = b.v; x['foo'] = y['zoo'];"); testReparse("'test' in x; 3 in x; a in x;"); testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'"); testReparse("x.__proto__;"); } private void testReparse(String code) { Compiler compiler = new Compiler(); Node parse1 = parse(code); Node parse2 = parse(new CodePrinter.Builder(parse1).build()); String explanation = parse1.checkTreeEquals(parse2); assertNull("\nExpected: " + compiler.toSource(parse1) + "\nResult: " + compiler.toSource(parse2) + "\n" + explanation, explanation); } public void testDoLoopIECompatiblity() { // Do loops within IFs cause syntax errors in IE6 and IE7. assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("function f(){if(e1)do foo();while(e2)else foo()}", "function f(){if(e1){do foo();while(e2)}else foo()}"); assertPrint("if(x){do{foo()}while(y)}else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x)do{foo()}while(y);else bar()", "if(x){do foo();while(y)}else bar()"); assertPrint("if(x){do{foo()}while(y)}", "if(x){do foo();while(y)}"); assertPrint("if(x)do{foo()}while(y);", "if(x){do foo();while(y)}"); assertPrint("if(x)A:do{foo()}while(y);", "if(x){A:do foo();while(y)}"); assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);", "var i=0;a:do{b:do{i++;break b}while(0)}while(0)"); } public void testFunctionSafariCompatiblity() { // Functions within IFs cause syntax errors on Safari. assertPrint("function f(){if(e1){function goo(){return true}}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("function f(){if(e1)function goo(){return true}else foo()}", "function f(){if(e1){function goo(){return true}}else foo()}"); assertPrint("if(e1){function goo(){return true}}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)function goo(){return true}", "if(e1){function goo(){return true}}"); assertPrint("if(e1)A:function goo(){return true}", "if(e1){A:function goo(){return true}}"); } public void testExponents() { assertPrintNumber("1", 1); assertPrintNumber("10", 10); assertPrintNumber("100", 100); assertPrintNumber("1E3", 1000); assertPrintNumber("1E4", 10000); assertPrintNumber("1E5", 100000); assertPrintNumber("-1", -1); assertPrintNumber("-10", -10); assertPrintNumber("-100", -100); assertPrintNumber("-1E3", -1000); assertPrintNumber("-12341234E4", -123412340000L); assertPrintNumber("1E18", 1000000000000000000L); assertPrintNumber("1E5", 100000.0); assertPrintNumber("100000.1", 100000.1); assertPrintNumber("1.0E-6", 0.000001); } // Make sure to test as both a String and a Node, because // negative numbers do not parse consistently from strings. private void assertPrintNumber(String expected, double number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } private void assertPrintNumber(String expected, int number) { assertPrint(String.valueOf(number), expected); assertPrintNode(expected, Node.newNumber(number)); } public void testDirectEval() { assertPrint("eval('1');", "eval(\"1\")"); } public void testIndirectEval() { Node n = parse("eval('1');"); assertPrintNode("eval(\"1\")", n); n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp( Node.DIRECT_EVAL, false); assertPrintNode("(0,eval)(\"1\")", n); } public void testFreeCall1() { assertPrint("foo(a);", "foo(a)"); assertPrint("x.foo(a);", "x.foo(a)"); } public void testFreeCall2() { Node n = parse("foo(a);"); assertPrintNode("foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("foo(a)", n); } public void testFreeCall3() { Node n = parse("x.foo(a);"); assertPrintNode("x.foo(a)", n); Node call = n.getFirstChild().getFirstChild(); assertTrue(call.isCall()); call.putBooleanProp(Node.FREE_CALL, true); assertPrintNode("(0,x.foo)(a)", n); } public void testPrintScript() { // Verify that SCRIPT nodes not marked as synthetic are printed as // blocks. Node ast = new Node(Token.SCRIPT, new Node(Token.EXPR_RESULT, Node.newString("f")), new Node(Token.EXPR_RESULT, Node.newString("g"))); String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build(); assertEquals("\"f\";\n\"g\";\n", result); } public void testObjectLit() { assertPrint("({x:1})", "({x:1})"); assertPrint("var x=({x:1})", "var x={x:1}"); assertPrint("var x={'x':1}", "var x={\"x\":1}"); assertPrint("var x={1:1}", "var x={1:1}"); } public void testObjectLit2() { assertPrint("var x={1:1}", "var x={1:1}"); assertPrint("var x={'1':1}", "var x={1:1}"); assertPrint("var x={'1.0':1}", "var x={\"1.0\":1}"); assertPrint("var x={1.5:1}", "var x={\"1.5\":1}"); } public void testObjectLit3() { assertPrint("var x={3E9:1}", "var x={3E9:1}"); assertPrint("var x={'3000000000':1}", // More than 31 bits "var x={3E9:1}"); assertPrint("var x={'3000000001':1}", "var x={3000000001:1}"); assertPrint("var x={'6000000001':1}", // More than 32 bits "var x={6000000001:1}"); assertPrint("var x={\"12345678901234567\":1}", // More than 53 bits "var x={\"12345678901234567\":1}"); } public void testObjectLit4() { // More than 128 bits. assertPrint( "var x={\"123456789012345671234567890123456712345678901234567\":1}", "var x={\"123456789012345671234567890123456712345678901234567\":1}"); } public void testGetter() { assertPrint("var x = {}", "var x={}"); assertPrint("var x = {get a() {return 1}}", "var x={get a(){return 1}}"); assertPrint( "var x = {get a() {}, get b(){}}", "var x={get a(){},get b(){}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {get 1() {return 1}}", "var x={get 1(){return 1}}"); assertPrint( "var x = {get \"()\"() {return 1}}", "var x={get \"()\"(){return 1}}"); } public void testSetter() { assertPrint("var x = {}", "var x={}"); assertPrint( "var x = {set a(y) {return 1}}", "var x={set a(y){return 1}}"); assertPrint( "var x = {get 'a'() {return 1}}", "var x={get \"a\"(){return 1}}"); assertPrint( "var x = {set 1(y) {return 1}}", "var x={set 1(y){return 1}}"); assertPrint( "var x = {set \"(x)\"(y) {return 1}}", "var x={set \"(x)\"(y){return 1}}"); } public void testNegCollapse() { // Collapse the negative symbol on numbers at generation time, // to match the Rhino behavior. assertPrint("var x = - - 2;", "var x=2"); assertPrint("var x = - (2);", "var x=-2"); } public void testStrict() { String result = parsePrint("var x", false, false, 0, false, true); assertEquals("'use strict';var x", result); } public void testArrayLiteral() { assertPrint("var x = [,];","var x=[,]"); assertPrint("var x = [,,];","var x=[,,]"); assertPrint("var x = [,s,,];","var x=[,s,,]"); assertPrint("var x = [,s];","var x=[,s]"); assertPrint("var x = [s,];","var x=[s]"); } public void testZero() { assertPrint("var x ='\\0';", "var x=\"\\x00\""); assertPrint("var x ='\\x00';", "var x=\"\\x00\""); assertPrint("var x ='\\u0000';", "var x=\"\\x00\""); assertPrint("var x ='\\u00003';", "var x=\"\\x003\""); } public void testUnicode() { assertPrint("var x ='\\x0f';", "var x=\"\\u000f\""); assertPrint("var x ='\\x68';", "var x=\"h\""); assertPrint("var x ='\\x7f';", "var x=\"\\u007f\""); } public void testUnicodeKeyword() { // keyword "if" assertPrint("var \\u0069\\u0066 = 1;", "var i\\u0066=1"); // keyword "var" assertPrint("var v\\u0061\\u0072 = 1;", "var va\\u0072=1"); // all are keyword "while" assertPrint("var w\\u0068\\u0069\\u006C\\u0065 = 1;" + "\\u0077\\u0068il\\u0065 = 2;" + "\\u0077h\\u0069le = 3;", "var whil\\u0065=1;whil\\u0065=2;whil\\u0065=3"); } public void testNumericKeys() { assertPrint("var x = {010: 1};", "var x={8:1}"); assertPrint("var x = {'010': 1};", "var x={\"010\":1}"); assertPrint("var x = {0x10: 1};", "var x={16:1}"); assertPrint("var x = {'0x10': 1};", "var x={\"0x10\":1}"); // I was surprised at this result too. assertPrint("var x = {.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'.2': 1};", "var x={\".2\":1}"); assertPrint("var x = {0.2: 1};", "var x={\"0.2\":1}"); assertPrint("var x = {'0.2': 1};", "var x={\"0.2\":1}"); } public void testIssue582() { assertPrint("var x = -0.0;", "var x=-0.0"); } public void testIssue601() { assertPrint("'\\v' == 'v'", "\"\\v\"==\"v\""); assertPrint("'\\u000B' == '\\v'", "\"\\x0B\"==\"\\v\""); assertPrint("'\\x0B' == '\\v'", "\"\\x0B\"==\"\\v\""); } public void testIssue620() { assertPrint("alert(/ / / / /);", "alert(/ // / /)"); assertPrint("alert(/ // / /);", "alert(/ // / /)"); } public void testIssue5746867() { assertPrint("var a = { '$\\\\' : 5 };", "var a={\"$\\\\\":5}"); } public void testManyCommas() { int numCommas = 10000; List<String> numbers = Lists.newArrayList("0", "1"); Node current = new Node(Token.COMMA, Node.newNumber(0), Node.newNumber(1)); for (int i = 2; i < numCommas; i++) { current = new Node(Token.COMMA, current); // 1000 is printed as 1E3, and screws up our test. int num = i % 1000; numbers.add(String.valueOf(num)); current.addChildToBack(Node.newNumber(num)); } String expected = Joiner.on(",").join(numbers); String actual = printNode(current).replace("\n", ""); assertEquals(expected, actual); } public void testMinusNegativeZero() { // Negative zero is weird, because we have to be able to distinguish // it from positive zero (there are some subtle differences in behavior). assertPrint("x- -0", "x- -0.0"); } }
public void testPropertyOfMethod() { testFailure("a.protoype.b = {}; " + "a.prototype.b.c = function() { this.foo = 3; };"); }
com.google.javascript.jscomp.CheckGlobalThisTest::testPropertyOfMethod
test/com/google/javascript/jscomp/CheckGlobalThisTest.java
159
test/com/google/javascript/jscomp/CheckGlobalThisTest.java
testPropertyOfMethod
/* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; /** * Tests {@link CheckGlobalThis}. */ public class CheckGlobalThisTest extends CompilerTestCase { public CheckGlobalThisTest() { this.parseTypeInfo = true; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new CombinedCompilerPass( compiler, new CheckGlobalThis(compiler, CheckLevel.ERROR)); } private void testFailure(String js) { test(js, null, CheckGlobalThis.GLOBAL_THIS); } public void testGlobalThis1() throws Exception { testSame("var a = this;"); } public void testGlobalThis2() { testFailure("this.foo = 5;"); } public void testGlobalThis3() { testFailure("this[foo] = 5;"); } public void testGlobalThis4() { testFailure("this['foo'] = 5;"); } public void testGlobalThis5() { testFailure("(a = this).foo = 4;"); } public void testGlobalThis6() { testSame("a = this;"); } public void testGlobalThis7() { testFailure("var a = this.foo;"); } public void testStaticFunction1() { testSame("function a() { return this; }"); } public void testStaticFunction2() { testFailure("function a() { this.complex = 5; }"); } public void testStaticFunction3() { testSame("var a = function() { return this; }"); } public void testStaticFunction4() { testFailure("var a = function() { this.foo.bar = 6; }"); } public void testStaticFunction5() { testSame("function a() { return function() { return this; } }"); } public void testStaticFunction6() { testSame("function a() { return function() { this = 8; } }"); } public void testStaticFunction7() { testSame("var a = function() { return function() { this = 8; } }"); } public void testStaticFunction8() { testFailure("var a = function() { return this.foo; };"); } public void testConstructor1() { testSame("/** @constructor */function A() { this.m2 = 5; }"); } public void testConstructor2() { testSame("/** @constructor */var A = function() { this.m2 = 5; }"); } public void testConstructor3() { testSame("/** @constructor */a.A = function() { this.m2 = 5; }"); } public void testInterface1() { testSame( "/** @interface */function A() { /** @type {string} */ this.m2; }"); } public void testOverride1() { testSame("/** @constructor */function A() { } var a = new A();" + "/** @override */ a.foo = function() { this.bar = 5; };"); } public void testThisJSDoc1() throws Exception { testSame("/** @this whatever */function h() { this.foo = 56; }"); } public void testThisJSDoc2() throws Exception { testSame("/** @this whatever */var h = function() { this.foo = 56; }"); } public void testThisJSDoc3() throws Exception { testSame("/** @this whatever */foo.bar = function() { this.foo = 56; }"); } public void testThisJSDoc4() throws Exception { testSame("/** @this whatever */function() { this.foo = 56; }"); } public void testThisJSDoc5() throws Exception { testSame("function a() { /** @this x */function() { this.foo = 56; } }"); } public void testMethod1() { testSame("A.prototype.m1 = function() { this.m2 = 5; }"); } public void testMethod2() { testSame("a.B.prototype.m1 = function() { this.m2 = 5; }"); } public void testMethod3() { testSame("a.b.c.D.prototype.m1 = function() { this.m2 = 5; }"); } public void testMethod4() { testSame("a.prototype['x' + 'y'] = function() { this.foo = 3; };"); } public void testPropertyOfMethod() { testFailure("a.protoype.b = {}; " + "a.prototype.b.c = function() { this.foo = 3; };"); } public void testStaticMethod1() { testFailure("a.b = function() { this.m2 = 5; }"); } public void testStaticMethod2() { testSame("a.b = function() { return function() { this.m2 = 5; } }"); } public void testStaticMethod3() { testSame("a.b.c = function() { return function() { this.m2 = 5; } }"); } public void testMethodInStaticFunction() { testSame("function f() { A.prototype.m1 = function() { this.m2 = 5; } }"); } public void testStaticFunctionInMethod1() { testSame("A.prototype.m1 = function() { function me() { this.m2 = 5; } }"); } public void testStaticFunctionInMethod2() { testSame("A.prototype.m1 = function() {" + " function me() {" + " function myself() {" + " function andI() { this.m2 = 5; } } } }"); } public void testInnerFunction1() { testFailure("function f() { function g() { return this.x; } }"); } public void testInnerFunction2() { testFailure("function f() { var g = function() { return this.x; } }"); } public void testInnerFunction3() { testFailure( "function f() { var x = {}; x.y = function() { return this.x; } }"); } public void testInnerFunction4() { testSame( "function f() { var x = {}; x.y(function() { return this.x; }); }"); } }
// You are a professional Java test case writer, please create a test case named `testPropertyOfMethod` for the issue `Closure-125`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-125 // // ## Issue-Title: // Prototypes declared with quotes produce a JSC_USED_GLOBAL_THIS warning. // // ## Issue-Description: // Compiling the following code (in advanced optimizations with VERBOSE // warning levels): // // /\*\* @constructor \*/ // function MyClass() {} // MyClass.prototype["MyMethod"] = function(a) { // this.a = a; // } // window["MyClass"] = MyClass; // // Results in the following warning: "dangerous use of the global this // object." This notation is convenient to declare a prototype that is purely // used for export purposes. The warning can be suppressed by using an @this // notation. // // Given the following externs: // // /\*\*@interface \*/ // function MyParent() {} // /\*\* @param {\*} a \*/ // MyParent.prototype.MyMethod = function(a) {} // // And the following code: // // /\*\* // \* @constructor // \* @implements {MyParent} // \*/ // function MyClass() {} // MyClass.prototype["MyMethod"] = function(a) { // this.a2 = a; // } // window["MyClass"] = MyClass; // // The compiler also produces the waring: "property MyMethod on interface // MyParent is not implemented by type MyClass". // // public void testPropertyOfMethod() {
159
99
156
test/com/google/javascript/jscomp/CheckGlobalThisTest.java
test
```markdown ## Issue-ID: Closure-125 ## Issue-Title: Prototypes declared with quotes produce a JSC_USED_GLOBAL_THIS warning. ## Issue-Description: Compiling the following code (in advanced optimizations with VERBOSE warning levels): /\*\* @constructor \*/ function MyClass() {} MyClass.prototype["MyMethod"] = function(a) { this.a = a; } window["MyClass"] = MyClass; Results in the following warning: "dangerous use of the global this object." This notation is convenient to declare a prototype that is purely used for export purposes. The warning can be suppressed by using an @this notation. Given the following externs: /\*\*@interface \*/ function MyParent() {} /\*\* @param {\*} a \*/ MyParent.prototype.MyMethod = function(a) {} And the following code: /\*\* \* @constructor \* @implements {MyParent} \*/ function MyClass() {} MyClass.prototype["MyMethod"] = function(a) { this.a2 = a; } window["MyClass"] = MyClass; The compiler also produces the waring: "property MyMethod on interface MyParent is not implemented by type MyClass". ``` You are a professional Java test case writer, please create a test case named `testPropertyOfMethod` for the issue `Closure-125`, utilizing the provided issue report information and the following function signature. ```java public void testPropertyOfMethod() { ```
156
[ "com.google.javascript.jscomp.CheckGlobalThis" ]
fe825b7466bc979ab51cc846792f1289edfc95151867605e9af2f15fca2b7622
public void testPropertyOfMethod()
// You are a professional Java test case writer, please create a test case named `testPropertyOfMethod` for the issue `Closure-125`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-125 // // ## Issue-Title: // Prototypes declared with quotes produce a JSC_USED_GLOBAL_THIS warning. // // ## Issue-Description: // Compiling the following code (in advanced optimizations with VERBOSE // warning levels): // // /\*\* @constructor \*/ // function MyClass() {} // MyClass.prototype["MyMethod"] = function(a) { // this.a = a; // } // window["MyClass"] = MyClass; // // Results in the following warning: "dangerous use of the global this // object." This notation is convenient to declare a prototype that is purely // used for export purposes. The warning can be suppressed by using an @this // notation. // // Given the following externs: // // /\*\*@interface \*/ // function MyParent() {} // /\*\* @param {\*} a \*/ // MyParent.prototype.MyMethod = function(a) {} // // And the following code: // // /\*\* // \* @constructor // \* @implements {MyParent} // \*/ // function MyClass() {} // MyClass.prototype["MyMethod"] = function(a) { // this.a2 = a; // } // window["MyClass"] = MyClass; // // The compiler also produces the waring: "property MyMethod on interface // MyParent is not implemented by type MyClass". // //
Closure
/* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; /** * Tests {@link CheckGlobalThis}. */ public class CheckGlobalThisTest extends CompilerTestCase { public CheckGlobalThisTest() { this.parseTypeInfo = true; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new CombinedCompilerPass( compiler, new CheckGlobalThis(compiler, CheckLevel.ERROR)); } private void testFailure(String js) { test(js, null, CheckGlobalThis.GLOBAL_THIS); } public void testGlobalThis1() throws Exception { testSame("var a = this;"); } public void testGlobalThis2() { testFailure("this.foo = 5;"); } public void testGlobalThis3() { testFailure("this[foo] = 5;"); } public void testGlobalThis4() { testFailure("this['foo'] = 5;"); } public void testGlobalThis5() { testFailure("(a = this).foo = 4;"); } public void testGlobalThis6() { testSame("a = this;"); } public void testGlobalThis7() { testFailure("var a = this.foo;"); } public void testStaticFunction1() { testSame("function a() { return this; }"); } public void testStaticFunction2() { testFailure("function a() { this.complex = 5; }"); } public void testStaticFunction3() { testSame("var a = function() { return this; }"); } public void testStaticFunction4() { testFailure("var a = function() { this.foo.bar = 6; }"); } public void testStaticFunction5() { testSame("function a() { return function() { return this; } }"); } public void testStaticFunction6() { testSame("function a() { return function() { this = 8; } }"); } public void testStaticFunction7() { testSame("var a = function() { return function() { this = 8; } }"); } public void testStaticFunction8() { testFailure("var a = function() { return this.foo; };"); } public void testConstructor1() { testSame("/** @constructor */function A() { this.m2 = 5; }"); } public void testConstructor2() { testSame("/** @constructor */var A = function() { this.m2 = 5; }"); } public void testConstructor3() { testSame("/** @constructor */a.A = function() { this.m2 = 5; }"); } public void testInterface1() { testSame( "/** @interface */function A() { /** @type {string} */ this.m2; }"); } public void testOverride1() { testSame("/** @constructor */function A() { } var a = new A();" + "/** @override */ a.foo = function() { this.bar = 5; };"); } public void testThisJSDoc1() throws Exception { testSame("/** @this whatever */function h() { this.foo = 56; }"); } public void testThisJSDoc2() throws Exception { testSame("/** @this whatever */var h = function() { this.foo = 56; }"); } public void testThisJSDoc3() throws Exception { testSame("/** @this whatever */foo.bar = function() { this.foo = 56; }"); } public void testThisJSDoc4() throws Exception { testSame("/** @this whatever */function() { this.foo = 56; }"); } public void testThisJSDoc5() throws Exception { testSame("function a() { /** @this x */function() { this.foo = 56; } }"); } public void testMethod1() { testSame("A.prototype.m1 = function() { this.m2 = 5; }"); } public void testMethod2() { testSame("a.B.prototype.m1 = function() { this.m2 = 5; }"); } public void testMethod3() { testSame("a.b.c.D.prototype.m1 = function() { this.m2 = 5; }"); } public void testMethod4() { testSame("a.prototype['x' + 'y'] = function() { this.foo = 3; };"); } public void testPropertyOfMethod() { testFailure("a.protoype.b = {}; " + "a.prototype.b.c = function() { this.foo = 3; };"); } public void testStaticMethod1() { testFailure("a.b = function() { this.m2 = 5; }"); } public void testStaticMethod2() { testSame("a.b = function() { return function() { this.m2 = 5; } }"); } public void testStaticMethod3() { testSame("a.b.c = function() { return function() { this.m2 = 5; } }"); } public void testMethodInStaticFunction() { testSame("function f() { A.prototype.m1 = function() { this.m2 = 5; } }"); } public void testStaticFunctionInMethod1() { testSame("A.prototype.m1 = function() { function me() { this.m2 = 5; } }"); } public void testStaticFunctionInMethod2() { testSame("A.prototype.m1 = function() {" + " function me() {" + " function myself() {" + " function andI() { this.m2 = 5; } } } }"); } public void testInnerFunction1() { testFailure("function f() { function g() { return this.x; } }"); } public void testInnerFunction2() { testFailure("function f() { var g = function() { return this.x; } }"); } public void testInnerFunction3() { testFailure( "function f() { var x = {}; x.y = function() { return this.x; } }"); } public void testInnerFunction4() { testSame( "function f() { var x = {}; x.y(function() { return this.x; }); }"); } }
public void testBase64EmptyInputStream() throws Exception { byte[] emptyEncoded = new byte[0]; byte[] emptyDecoded = new byte[0]; testByteByByte(emptyEncoded, emptyDecoded, 76, CRLF); testByChunk(emptyEncoded, emptyDecoded, 76, CRLF); }
org.apache.commons.codec.binary.Base64InputStreamTest::testBase64EmptyInputStream
src/test/org/apache/commons/codec/binary/Base64InputStreamTest.java
54
src/test/org/apache/commons/codec/binary/Base64InputStreamTest.java
testBase64EmptyInputStream
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.binary; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Arrays; /** * @author Apache Software Foundation * @version $Id $ */ public class Base64InputStreamTest extends TestCase { private final static byte[] CRLF = {(byte) '\r', (byte) '\n'}; private final static byte[] LF = {(byte) '\n'}; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public Base64InputStreamTest(String name) { super(name); } /** * Test the Base64InputStream implementation against empty input. * * @throws Exception for some failure scenarios. */ public void testBase64EmptyInputStream() throws Exception { byte[] emptyEncoded = new byte[0]; byte[] emptyDecoded = new byte[0]; testByteByByte(emptyEncoded, emptyDecoded, 76, CRLF); testByChunk(emptyEncoded, emptyDecoded, 76, CRLF); } /** * Test the Base64InputStream implementation. * * @throws Exception for some failure scenarios. */ public void testBase64InputStreamByteByByte() throws Exception { // Hello World test. byte[] encoded = "SGVsbG8gV29ybGQ=\r\n".getBytes("UTF-8"); byte[] decoded = "Hello World".getBytes("UTF-8"); testByteByByte(encoded, decoded, 76, CRLF); // Single Byte test. encoded = "AA==\r\n".getBytes("UTF-8"); decoded = new byte[]{(byte) 0}; testByteByByte(encoded, decoded, 76, CRLF); // OpenSSL interop test. encoded = Base64TestData.ENCODED.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByteByByte(encoded, decoded, 64, LF); // Single Line test. String singleLine = Base64TestData.ENCODED.replaceAll("\n", ""); encoded = singleLine.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByteByByte(encoded, decoded, 0, LF); } /** * Test the Base64InputStream implementation. * * @throws Exception for some failure scenarios. */ public void testBase64InputStreamByChunk() throws Exception { // Hello World test. byte[] encoded = "SGVsbG8gV29ybGQ=\r\n".getBytes("UTF-8"); byte[] decoded = "Hello World".getBytes("UTF-8"); testByChunk(encoded, decoded, 76, CRLF); // Single Byte test. encoded = "AA==\r\n".getBytes("UTF-8"); decoded = new byte[]{(byte) 0}; testByChunk(encoded, decoded, 76, CRLF); // OpenSSL interop test. encoded = Base64TestData.ENCODED.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByChunk(encoded, decoded, 64, LF); // Single Line test. String singleLine = Base64TestData.ENCODED.replaceAll("\n", ""); encoded = singleLine.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByChunk(encoded, decoded, 0, LF); } /** * Test method does three tests on the supplied data: * 1. encoded ---[DECODE]--> decoded * 2. decoded ---[ENCODE]--> encoded * 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded * <p/> * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the * Base64InputStream wraps itself in encode and decode mode * over and over again. * * @param encoded base64 encoded data * @param decoded the data from above, but decoded * @param chunkSize chunk size (line-length) of the base64 encoded data. * @param seperator Line separator in the base64 encoded data. * @throws Exception Usually signifies a bug in the Base64 commons-codec implementation. */ private void testByteByByte( byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator ) throws Exception { // Start with encode. InputStream in = new ByteArrayInputStream(decoded); in = new Base64InputStream(in, true, chunkSize, seperator); byte[] output = new byte[encoded.length]; for (int i = 0; i < output.length; i++) { output[i] = (byte) in.read(); } assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 encode", Arrays.equals(output, encoded)); // Now let's try decode. in = new ByteArrayInputStream(encoded); in = new Base64InputStream(in); output = new byte[decoded.length]; for (int i = 0; i < output.length; i++) { output[i] = (byte) in.read(); } assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 decode", Arrays.equals(output, decoded)); // I always wanted to do this! (wrap encoder with decoder etc etc). in = new ByteArrayInputStream(decoded); for (int i = 0; i < 10; i++) { in = new Base64InputStream(in, true, chunkSize, seperator); in = new Base64InputStream(in, false); } output = new byte[decoded.length]; for (int i = 0; i < output.length; i++) { output[i] = (byte) in.read(); } assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded)); } /** * Test method does three tests on the supplied data: * 1. encoded ---[DECODE]--> decoded * 2. decoded ---[ENCODE]--> encoded * 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded * <p/> * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the * Base64InputStream wraps itself in encode and decode mode * over and over again. * * @param encoded base64 encoded data * @param decoded the data from above, but decoded * @param chunkSize chunk size (line-length) of the base64 encoded data. * @param seperator Line separator in the base64 encoded data. * @throws Exception Usually signifies a bug in the Base64 commons-codec implementation. */ private void testByChunk( byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator ) throws Exception { // Start with encode. InputStream in = new ByteArrayInputStream(decoded); in = new Base64InputStream(in, true, chunkSize, seperator); byte[] output = Base64TestData.streamToBytes(in); assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 encode", Arrays.equals(output, encoded)); // Now let's try decode. in = new ByteArrayInputStream(encoded); in = new Base64InputStream(in); output = Base64TestData.streamToBytes(in); assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 decode", Arrays.equals(output, decoded)); // I always wanted to do this! (wrap encoder with decoder etc etc). in = new ByteArrayInputStream(decoded); for (int i = 0; i < 10; i++) { in = new Base64InputStream(in, true, chunkSize, seperator); in = new Base64InputStream(in, false); } output = Base64TestData.streamToBytes(in); assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded)); } }
// You are a professional Java test case writer, please create a test case named `testBase64EmptyInputStream` for the issue `Codec-CODEC-77`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-77 // // ## Issue-Title: // Base64 bug with empty input (new byte[0]) // // ## Issue-Description: // // Base64.encode(new byte[0]) doesn't return an empty byte array back! It returns CRLF. // // // // // public void testBase64EmptyInputStream() throws Exception {
54
/** * Test the Base64InputStream implementation against empty input. * * @throws Exception for some failure scenarios. */
2
49
src/test/org/apache/commons/codec/binary/Base64InputStreamTest.java
src/test
```markdown ## Issue-ID: Codec-CODEC-77 ## Issue-Title: Base64 bug with empty input (new byte[0]) ## Issue-Description: Base64.encode(new byte[0]) doesn't return an empty byte array back! It returns CRLF. ``` You are a professional Java test case writer, please create a test case named `testBase64EmptyInputStream` for the issue `Codec-CODEC-77`, utilizing the provided issue report information and the following function signature. ```java public void testBase64EmptyInputStream() throws Exception { ```
49
[ "org.apache.commons.codec.binary.Base64" ]
fea846f282fd5c507075ba8f7249a7e72856405a9783ab711f46ab3319d3439d
public void testBase64EmptyInputStream() throws Exception
// You are a professional Java test case writer, please create a test case named `testBase64EmptyInputStream` for the issue `Codec-CODEC-77`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-77 // // ## Issue-Title: // Base64 bug with empty input (new byte[0]) // // ## Issue-Description: // // Base64.encode(new byte[0]) doesn't return an empty byte array back! It returns CRLF. // // // // //
Codec
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.codec.binary; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Arrays; /** * @author Apache Software Foundation * @version $Id $ */ public class Base64InputStreamTest extends TestCase { private final static byte[] CRLF = {(byte) '\r', (byte) '\n'}; private final static byte[] LF = {(byte) '\n'}; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public Base64InputStreamTest(String name) { super(name); } /** * Test the Base64InputStream implementation against empty input. * * @throws Exception for some failure scenarios. */ public void testBase64EmptyInputStream() throws Exception { byte[] emptyEncoded = new byte[0]; byte[] emptyDecoded = new byte[0]; testByteByByte(emptyEncoded, emptyDecoded, 76, CRLF); testByChunk(emptyEncoded, emptyDecoded, 76, CRLF); } /** * Test the Base64InputStream implementation. * * @throws Exception for some failure scenarios. */ public void testBase64InputStreamByteByByte() throws Exception { // Hello World test. byte[] encoded = "SGVsbG8gV29ybGQ=\r\n".getBytes("UTF-8"); byte[] decoded = "Hello World".getBytes("UTF-8"); testByteByByte(encoded, decoded, 76, CRLF); // Single Byte test. encoded = "AA==\r\n".getBytes("UTF-8"); decoded = new byte[]{(byte) 0}; testByteByByte(encoded, decoded, 76, CRLF); // OpenSSL interop test. encoded = Base64TestData.ENCODED.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByteByByte(encoded, decoded, 64, LF); // Single Line test. String singleLine = Base64TestData.ENCODED.replaceAll("\n", ""); encoded = singleLine.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByteByByte(encoded, decoded, 0, LF); } /** * Test the Base64InputStream implementation. * * @throws Exception for some failure scenarios. */ public void testBase64InputStreamByChunk() throws Exception { // Hello World test. byte[] encoded = "SGVsbG8gV29ybGQ=\r\n".getBytes("UTF-8"); byte[] decoded = "Hello World".getBytes("UTF-8"); testByChunk(encoded, decoded, 76, CRLF); // Single Byte test. encoded = "AA==\r\n".getBytes("UTF-8"); decoded = new byte[]{(byte) 0}; testByChunk(encoded, decoded, 76, CRLF); // OpenSSL interop test. encoded = Base64TestData.ENCODED.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByChunk(encoded, decoded, 64, LF); // Single Line test. String singleLine = Base64TestData.ENCODED.replaceAll("\n", ""); encoded = singleLine.getBytes("UTF-8"); decoded = Base64TestData.DECODED; testByChunk(encoded, decoded, 0, LF); } /** * Test method does three tests on the supplied data: * 1. encoded ---[DECODE]--> decoded * 2. decoded ---[ENCODE]--> encoded * 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded * <p/> * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the * Base64InputStream wraps itself in encode and decode mode * over and over again. * * @param encoded base64 encoded data * @param decoded the data from above, but decoded * @param chunkSize chunk size (line-length) of the base64 encoded data. * @param seperator Line separator in the base64 encoded data. * @throws Exception Usually signifies a bug in the Base64 commons-codec implementation. */ private void testByteByByte( byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator ) throws Exception { // Start with encode. InputStream in = new ByteArrayInputStream(decoded); in = new Base64InputStream(in, true, chunkSize, seperator); byte[] output = new byte[encoded.length]; for (int i = 0; i < output.length; i++) { output[i] = (byte) in.read(); } assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 encode", Arrays.equals(output, encoded)); // Now let's try decode. in = new ByteArrayInputStream(encoded); in = new Base64InputStream(in); output = new byte[decoded.length]; for (int i = 0; i < output.length; i++) { output[i] = (byte) in.read(); } assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 decode", Arrays.equals(output, decoded)); // I always wanted to do this! (wrap encoder with decoder etc etc). in = new ByteArrayInputStream(decoded); for (int i = 0; i < 10; i++) { in = new Base64InputStream(in, true, chunkSize, seperator); in = new Base64InputStream(in, false); } output = new byte[decoded.length]; for (int i = 0; i < output.length; i++) { output[i] = (byte) in.read(); } assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded)); } /** * Test method does three tests on the supplied data: * 1. encoded ---[DECODE]--> decoded * 2. decoded ---[ENCODE]--> encoded * 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded * <p/> * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the * Base64InputStream wraps itself in encode and decode mode * over and over again. * * @param encoded base64 encoded data * @param decoded the data from above, but decoded * @param chunkSize chunk size (line-length) of the base64 encoded data. * @param seperator Line separator in the base64 encoded data. * @throws Exception Usually signifies a bug in the Base64 commons-codec implementation. */ private void testByChunk( byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator ) throws Exception { // Start with encode. InputStream in = new ByteArrayInputStream(decoded); in = new Base64InputStream(in, true, chunkSize, seperator); byte[] output = Base64TestData.streamToBytes(in); assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 encode", Arrays.equals(output, encoded)); // Now let's try decode. in = new ByteArrayInputStream(encoded); in = new Base64InputStream(in); output = Base64TestData.streamToBytes(in); assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 decode", Arrays.equals(output, decoded)); // I always wanted to do this! (wrap encoder with decoder etc etc). in = new ByteArrayInputStream(decoded); for (int i = 0; i < 10; i++) { in = new Base64InputStream(in, true, chunkSize, seperator); in = new Base64InputStream(in, false); } output = Base64TestData.streamToBytes(in); assertEquals("EOF", -1, in.read()); assertEquals("Still EOF", -1, in.read()); assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded)); } }
public void testFormat() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); Date date1 = cal1.getTime(); Date date2 = cal2.getTime(); long millis1 = date1.getTime(); long millis2 = date2.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); assertEquals(sdf.format(date1), fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); assertEquals("2003-07-10T09:00:00", fdf.format(date2)); assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); fdf = FastDateFormat.getInstance("Z"); assertEquals("-0500", fdf.format(date1)); assertEquals("-0500", fdf.format(cal1)); assertEquals("-0500", fdf.format(millis1)); assertEquals("-0400", fdf.format(date2)); assertEquals("-0400", fdf.format(cal2)); assertEquals("-0400", fdf.format(millis2)); fdf = FastDateFormat.getInstance("ZZ"); assertEquals("-05:00", fdf.format(date1)); assertEquals("-05:00", fdf.format(cal1)); assertEquals("-05:00", fdf.format(millis1)); assertEquals("-04:00", fdf.format(date2)); assertEquals("-04:00", fdf.format(cal2)); assertEquals("-04:00", fdf.format(millis2)); String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; fdf = FastDateFormat.getInstance(pattern); sdf = new SimpleDateFormat(pattern); // SDF bug fix starting with Java 7 assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1)); assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2)); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } }
org.apache.commons.lang3.time.FastDateFormatTest::testFormat
src/test/java/org/apache/commons/lang3/time/FastDateFormatTest.java
225
src/test/java/org/apache/commons/lang3/time/FastDateFormatTest.java
testFormat
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import org.apache.commons.lang3.SerializationUtils; /** * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}. * * @since 2.0 * @version $Id$ */ public class FastDateFormatTest extends TestCase { public FastDateFormatTest(String name) { super(name); } public void test_getInstance() { FastDateFormat format1 = FastDateFormat.getInstance(); FastDateFormat format2 = FastDateFormat.getInstance(); assertSame(format1, format2); assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern()); } public void test_getInstance_String() { FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format2, format3); assertEquals("MM/DD/yyyy", format1.getPattern()); assertEquals(TimeZone.getDefault(), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); } public void test_getInstance_String_TimeZone() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik")); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault()); FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertSame(format3, format4); assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void test_getInstance_String_Locale() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format1, format3); assertEquals(Locale.GERMANY, format1.getLocale()); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateTimeInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_getInstance_String_TimeZone_Locale() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault(), Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale()); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void testFormat() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); Date date1 = cal1.getTime(); Date date2 = cal2.getTime(); long millis1 = date1.getTime(); long millis2 = date2.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); assertEquals(sdf.format(date1), fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); assertEquals("2003-07-10T09:00:00", fdf.format(date2)); assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); fdf = FastDateFormat.getInstance("Z"); assertEquals("-0500", fdf.format(date1)); assertEquals("-0500", fdf.format(cal1)); assertEquals("-0500", fdf.format(millis1)); assertEquals("-0400", fdf.format(date2)); assertEquals("-0400", fdf.format(cal2)); assertEquals("-0400", fdf.format(millis2)); fdf = FastDateFormat.getInstance("ZZ"); assertEquals("-05:00", fdf.format(date1)); assertEquals("-05:00", fdf.format(cal1)); assertEquals("-05:00", fdf.format(millis1)); assertEquals("-04:00", fdf.format(date2)); assertEquals("-04:00", fdf.format(cal2)); assertEquals("-04:00", fdf.format(millis2)); String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; fdf = FastDateFormat.getInstance(pattern); sdf = new SimpleDateFormat(pattern); // SDF bug fix starting with Java 7 assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1)); assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2)); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } /** * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}. */ public void testShortDateStyleWithLocales() { Locale usLocale = Locale.US; Locale swedishLocale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ public void testLowYearPadding() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD"); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ public void testMilleniumBug() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ public void testSimpleDate() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } public void testLang303() { Calendar cal = Calendar.getInstance(); cal.set(2004,11,31); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); String output = format.format(cal); format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) ); assertEquals(output, format.format(cal)); } public void testLang538() { // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", "2009-10-16T16:42:16.000Z", format.format(cal.getTime())); assertEquals("dateTime", "2009-10-16T08:42:16.000Z", format.format(cal)); } public void testLang645() { Locale locale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1, 12, 0, 0); Date d = cal.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); assertEquals("fredag, week 53", fdf.format(d)); } }
// You are a professional Java test case writer, please create a test case named `testFormat` for the issue `Lang-LANG-719`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-719 // // ## Issue-Title: // FastDateFormat formats year differently than SimpleDateFormat in Java 7 // // ## Issue-Description: // // Starting with Java 7 does SimpleDateFormat format a year pattern of 'Y' or 'YYY' as '2003' instead of '03' as in former Java releases. According Javadoc this pattern should have been always been formatted as number, therefore the new behavior seems to be a bug fix in the JDK. FastDateFormat is adjusted to behave the same. // // // // // public void testFormat() {
225
18
172
src/test/java/org/apache/commons/lang3/time/FastDateFormatTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-719 ## Issue-Title: FastDateFormat formats year differently than SimpleDateFormat in Java 7 ## Issue-Description: Starting with Java 7 does SimpleDateFormat format a year pattern of 'Y' or 'YYY' as '2003' instead of '03' as in former Java releases. According Javadoc this pattern should have been always been formatted as number, therefore the new behavior seems to be a bug fix in the JDK. FastDateFormat is adjusted to behave the same. ``` You are a professional Java test case writer, please create a test case named `testFormat` for the issue `Lang-LANG-719`, utilizing the provided issue report information and the following function signature. ```java public void testFormat() { ```
172
[ "org.apache.commons.lang3.time.FastDateFormat" ]
fec544dcf14f8541d7bf7111738de24ced64f2fd0a56652b323c93e68dccc80f
public void testFormat()
// You are a professional Java test case writer, please create a test case named `testFormat` for the issue `Lang-LANG-719`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-719 // // ## Issue-Title: // FastDateFormat formats year differently than SimpleDateFormat in Java 7 // // ## Issue-Description: // // Starting with Java 7 does SimpleDateFormat format a year pattern of 'Y' or 'YYY' as '2003' instead of '03' as in former Java releases. According Javadoc this pattern should have been always been formatted as number, therefore the new behavior seems to be a bug fix in the JDK. FastDateFormat is adjusted to behave the same. // // // // //
Lang
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import org.apache.commons.lang3.SerializationUtils; /** * Unit tests {@link org.apache.commons.lang3.time.FastDateFormat}. * * @since 2.0 * @version $Id$ */ public class FastDateFormatTest extends TestCase { public FastDateFormatTest(String name) { super(name); } public void test_getInstance() { FastDateFormat format1 = FastDateFormat.getInstance(); FastDateFormat format2 = FastDateFormat.getInstance(); assertSame(format1, format2); assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern()); } public void test_getInstance_String() { FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format2, format3); assertEquals("MM/DD/yyyy", format1.getPattern()); assertEquals(TimeZone.getDefault(), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); } public void test_getInstance_String_TimeZone() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik")); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault()); FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertSame(format3, format4); assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void test_getInstance_String_Locale() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format1, format3); assertEquals(Locale.GERMANY, format1.getLocale()); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateTimeInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_getInstance_String_TimeZone_Locale() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault(), Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale()); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void testFormat() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); Date date1 = cal1.getTime(); Date date2 = cal2.getTime(); long millis1 = date1.getTime(); long millis2 = date2.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); assertEquals(sdf.format(date1), fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); assertEquals("2003-07-10T09:00:00", fdf.format(date2)); assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); fdf = FastDateFormat.getInstance("Z"); assertEquals("-0500", fdf.format(date1)); assertEquals("-0500", fdf.format(cal1)); assertEquals("-0500", fdf.format(millis1)); assertEquals("-0400", fdf.format(date2)); assertEquals("-0400", fdf.format(cal2)); assertEquals("-0400", fdf.format(millis2)); fdf = FastDateFormat.getInstance("ZZ"); assertEquals("-05:00", fdf.format(date1)); assertEquals("-05:00", fdf.format(cal1)); assertEquals("-05:00", fdf.format(millis1)); assertEquals("-04:00", fdf.format(date2)); assertEquals("-04:00", fdf.format(cal2)); assertEquals("-04:00", fdf.format(millis2)); String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; fdf = FastDateFormat.getInstance(pattern); sdf = new SimpleDateFormat(pattern); // SDF bug fix starting with Java 7 assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1)); assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2)); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } /** * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}. */ public void testShortDateStyleWithLocales() { Locale usLocale = Locale.US; Locale swedishLocale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ public void testLowYearPadding() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD"); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ public void testMilleniumBug() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ public void testSimpleDate() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } public void testLang303() { Calendar cal = Calendar.getInstance(); cal.set(2004,11,31); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); String output = format.format(cal); format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) ); assertEquals(output, format.format(cal)); } public void testLang538() { // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", "2009-10-16T16:42:16.000Z", format.format(cal.getTime())); assertEquals("dateTime", "2009-10-16T08:42:16.000Z", format.format(cal)); } public void testLang645() { Locale locale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1, 12, 0, 0); Date d = cal.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); assertEquals("fredag, week 53", fdf.format(d)); } }
public void testLocalValue1() throws Exception { // Names are not known to be local. assertFalse(testLocalValue("x")); assertFalse(testLocalValue("x()")); assertFalse(testLocalValue("this")); assertFalse(testLocalValue("arguments")); // We can't know if new objects are local unless we know // that they don't alias themselves. assertFalse(testLocalValue("new x()")); // property references are assume to be non-local assertFalse(testLocalValue("(new x()).y")); assertFalse(testLocalValue("(new x())['y']")); // Primitive values are local assertTrue(testLocalValue("null")); assertTrue(testLocalValue("undefined")); assertTrue(testLocalValue("Infinity")); assertTrue(testLocalValue("NaN")); assertTrue(testLocalValue("1")); assertTrue(testLocalValue("'a'")); assertTrue(testLocalValue("true")); assertTrue(testLocalValue("false")); assertTrue(testLocalValue("[]")); assertTrue(testLocalValue("{}")); // The contents of arrays and objects don't matter assertTrue(testLocalValue("[x]")); assertTrue(testLocalValue("{'a':x}")); // Pre-increment results in primitive number assertTrue(testLocalValue("++x")); assertTrue(testLocalValue("--x")); // Post-increment, the previous value matters. assertFalse(testLocalValue("x++")); assertFalse(testLocalValue("x--")); // The left side of an only assign matters if it is an alias or mutable. assertTrue(testLocalValue("x=1")); assertFalse(testLocalValue("x=[]")); assertFalse(testLocalValue("x=y")); // The right hand side of assignment opts don't matter, as they force // a local result. assertTrue(testLocalValue("x+=y")); assertTrue(testLocalValue("x*=y")); // Comparisons always result in locals, as they force a local boolean // result. assertTrue(testLocalValue("x==y")); assertTrue(testLocalValue("x!=y")); assertTrue(testLocalValue("x>y")); // Only the right side of a comma matters assertTrue(testLocalValue("(1,2)")); assertTrue(testLocalValue("(x,1)")); assertFalse(testLocalValue("(x,y)")); // Both the operands of OR matter assertTrue(testLocalValue("1||2")); assertFalse(testLocalValue("x||1")); assertFalse(testLocalValue("x||y")); assertFalse(testLocalValue("1||y")); // Both the operands of AND matter assertTrue(testLocalValue("1&&2")); assertFalse(testLocalValue("x&&1")); assertFalse(testLocalValue("x&&y")); assertFalse(testLocalValue("1&&y")); // Only the results of HOOK matter assertTrue(testLocalValue("x?1:2")); assertFalse(testLocalValue("x?x:2")); assertFalse(testLocalValue("x?1:x")); assertFalse(testLocalValue("x?x:y")); // Results of ops are local values assertTrue(testLocalValue("!y")); assertTrue(testLocalValue("~y")); assertTrue(testLocalValue("y + 1")); assertTrue(testLocalValue("y + z")); assertTrue(testLocalValue("y * z")); assertTrue(testLocalValue("'a' in x")); assertTrue(testLocalValue("typeof x")); assertTrue(testLocalValue("x instanceof y")); assertTrue(testLocalValue("void x")); assertTrue(testLocalValue("void 0")); assertFalse(testLocalValue("{}.x")); assertTrue(testLocalValue("{}.toString()")); assertTrue(testLocalValue("o.toString()")); assertFalse(testLocalValue("o.valueOf()")); }
com.google.javascript.jscomp.NodeUtilTest::testLocalValue1
test/com/google/javascript/jscomp/NodeUtilTest.java
1,108
test/com/google/javascript/jscomp/NodeUtilTest.java
testLocalValue1
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.TernaryValue; import junit.framework.TestCase; import java.util.Collection; import java.util.List; import java.util.Set; public class NodeUtilTest extends TestCase { private static Node parse(String js) { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n; } static Node getNode(String js) { Node root = parse("var a=(" + js + ");"); Node expr = root.getFirstChild(); Node var = expr.getFirstChild(); return var.getFirstChild(); } public void testIsLiteralOrConstValue() { assertLiteralAndImmutable(getNode("10")); assertLiteralAndImmutable(getNode("-10")); assertLiteralButNotImmutable(getNode("[10, 20]")); assertLiteralButNotImmutable(getNode("{'a': 20}")); assertLiteralButNotImmutable(getNode("[10, , 1.0, [undefined], 'a']")); assertLiteralButNotImmutable(getNode("/abc/")); assertLiteralAndImmutable(getNode("\"string\"")); assertLiteralAndImmutable(getNode("'aaa'")); assertLiteralAndImmutable(getNode("null")); assertLiteralAndImmutable(getNode("undefined")); assertLiteralAndImmutable(getNode("void 0")); assertNotLiteral(getNode("abc")); assertNotLiteral(getNode("[10, foo(), 20]")); assertNotLiteral(getNode("foo()")); assertNotLiteral(getNode("c + d")); assertNotLiteral(getNode("{'a': foo()}")); assertNotLiteral(getNode("void foo()")); } public void assertLiteralAndImmutable(Node n) { assertTrue(NodeUtil.isLiteralValue(n, true)); assertTrue(NodeUtil.isLiteralValue(n, false)); assertTrue(NodeUtil.isImmutableValue(n)); } public void assertLiteralButNotImmutable(Node n) { assertTrue(NodeUtil.isLiteralValue(n, true)); assertTrue(NodeUtil.isLiteralValue(n, false)); assertFalse(NodeUtil.isImmutableValue(n)); } public void assertNotLiteral(Node n) { assertFalse(NodeUtil.isLiteralValue(n, true)); assertFalse(NodeUtil.isLiteralValue(n, false)); assertFalse(NodeUtil.isImmutableValue(n)); } public void testGetBooleanValue() { assertBooleanTrue("true"); assertBooleanTrue("10"); assertBooleanTrue("'0'"); assertBooleanTrue("/a/"); assertBooleanTrue("{}"); assertBooleanTrue("[]"); assertBooleanFalse("false"); assertBooleanFalse("null"); assertBooleanFalse("0"); assertBooleanFalse("''"); assertBooleanFalse("undefined"); assertBooleanFalse("void 0"); assertBooleanFalse("void foo()"); assertBooleanUnknown("b"); assertBooleanUnknown("-'0.0'"); } private void assertBooleanTrue(String val) { assertEquals(TernaryValue.TRUE, NodeUtil.getBooleanValue(getNode(val))); } private void assertBooleanFalse(String val) { assertEquals(TernaryValue.FALSE, NodeUtil.getBooleanValue(getNode(val))); } private void assertBooleanUnknown(String val) { assertEquals(TernaryValue.UNKNOWN, NodeUtil.getBooleanValue(getNode(val))); } public void testGetExpressionBooleanValue() { assertExpressionBooleanTrue("a=true"); assertExpressionBooleanFalse("a=false"); assertExpressionBooleanTrue("a=(false,true)"); assertExpressionBooleanFalse("a=(true,false)"); assertExpressionBooleanTrue("a=(false || true)"); assertExpressionBooleanFalse("a=(true && false)"); assertExpressionBooleanTrue("a=!(true && false)"); assertExpressionBooleanTrue("a,true"); assertExpressionBooleanFalse("a,false"); assertExpressionBooleanTrue("true||false"); assertExpressionBooleanFalse("false||false"); assertExpressionBooleanTrue("true&&true"); assertExpressionBooleanFalse("true&&false"); assertExpressionBooleanFalse("!true"); assertExpressionBooleanTrue("!false"); assertExpressionBooleanTrue("!''"); // Assignment ops other than ASSIGN are unknown. assertExpressionBooleanUnknown("a *= 2"); // Complex expressions that contain anything other then "=", ",", or "!" are // unknown. assertExpressionBooleanUnknown("2 + 2"); assertExpressionBooleanTrue("a=1"); assertExpressionBooleanTrue("a=/a/"); assertExpressionBooleanTrue("a={}"); assertExpressionBooleanTrue("true"); assertExpressionBooleanTrue("10"); assertExpressionBooleanTrue("'0'"); assertExpressionBooleanTrue("/a/"); assertExpressionBooleanTrue("{}"); assertExpressionBooleanTrue("[]"); assertExpressionBooleanFalse("false"); assertExpressionBooleanFalse("null"); assertExpressionBooleanFalse("0"); assertExpressionBooleanFalse("''"); assertExpressionBooleanFalse("undefined"); assertExpressionBooleanFalse("void 0"); assertExpressionBooleanFalse("void foo()"); assertExpressionBooleanTrue("a?true:true"); assertExpressionBooleanFalse("a?false:false"); assertExpressionBooleanUnknown("a?true:false"); assertExpressionBooleanUnknown("a?true:foo()"); assertExpressionBooleanUnknown("b"); assertExpressionBooleanUnknown("-'0.0'"); } private void assertExpressionBooleanTrue(String val) { assertEquals(TernaryValue.TRUE, NodeUtil.getExpressionBooleanValue(getNode(val))); } private void assertExpressionBooleanFalse(String val) { assertEquals(TernaryValue.FALSE, NodeUtil.getExpressionBooleanValue(getNode(val))); } private void assertExpressionBooleanUnknown(String val) { assertEquals(TernaryValue.UNKNOWN, NodeUtil.getExpressionBooleanValue(getNode(val))); } public void testGetStringValue() { assertEquals("true", NodeUtil.getStringValue(getNode("true"))); assertEquals("10", NodeUtil.getStringValue(getNode("10"))); assertEquals("1", NodeUtil.getStringValue(getNode("1.0"))); assertEquals("0", NodeUtil.getStringValue(getNode("'0'"))); assertEquals(null, NodeUtil.getStringValue(getNode("/a/"))); assertEquals(null, NodeUtil.getStringValue(getNode("{}"))); assertEquals(null, NodeUtil.getStringValue(getNode("[]"))); assertEquals("false", NodeUtil.getStringValue(getNode("false"))); assertEquals("null", NodeUtil.getStringValue(getNode("null"))); assertEquals("0", NodeUtil.getStringValue(getNode("0"))); assertEquals("", NodeUtil.getStringValue(getNode("''"))); assertEquals("undefined", NodeUtil.getStringValue(getNode("undefined"))); assertEquals("undefined", NodeUtil.getStringValue(getNode("void 0"))); assertEquals("undefined", NodeUtil.getStringValue(getNode("void foo()"))); assertEquals("NaN", NodeUtil.getStringValue(getNode("NaN"))); assertEquals("Infinity", NodeUtil.getStringValue(getNode("Infinity"))); assertEquals(null, NodeUtil.getStringValue(getNode("x"))); } public void testIsObjectLiteralKey1() throws Exception { testIsObjectLiteralKey( parseExpr("({})"), false); testIsObjectLiteralKey( parseExpr("a"), false); testIsObjectLiteralKey( parseExpr("'a'"), false); testIsObjectLiteralKey( parseExpr("1"), false); testIsObjectLiteralKey( parseExpr("({a: 1})").getFirstChild(), true); testIsObjectLiteralKey( parseExpr("({1: 1})").getFirstChild(), true); testIsObjectLiteralKey( parseExpr("({get a(){}})").getFirstChild(), true); testIsObjectLiteralKey( parseExpr("({set a(b){}})").getFirstChild(), true); } private Node parseExpr(String js) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); options.languageIn = LanguageMode.ECMASCRIPT5; compiler.initOptions(options); Node root = compiler.parseTestCode(js); return root.getFirstChild().getFirstChild(); } private void testIsObjectLiteralKey(Node node, boolean expected) { assertEquals(expected, NodeUtil.isObjectLitKey(node, node.getParent())); } public void testGetFunctionName1() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("function name(){}"); testGetFunctionName(parent.getFirstChild(), "name"); } public void testGetFunctionName2() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("var name = function(){}") .getFirstChild().getFirstChild(); testGetFunctionName(parent.getFirstChild(), "name"); } public void testGetFunctionName3() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("qualified.name = function(){}") .getFirstChild().getFirstChild(); testGetFunctionName(parent.getLastChild(), "qualified.name"); } public void testGetFunctionName4() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("var name2 = function name1(){}") .getFirstChild().getFirstChild(); testGetFunctionName(parent.getFirstChild(), "name2"); } public void testGetFunctionName5() throws Exception { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("qualified.name2 = function name1(){}"); Node parent = n.getFirstChild().getFirstChild(); testGetFunctionName(parent.getLastChild(), "qualified.name2"); } private void testGetFunctionName(Node function, String name) { assertEquals(Token.FUNCTION, function.getType()); assertEquals(name, NodeUtil.getFunctionName(function)); } public void testContainsFunctionDeclaration() { assertTrue(NodeUtil.containsFunction( getNode("function foo(){}"))); assertTrue(NodeUtil.containsFunction( getNode("(b?function(){}:null)"))); assertFalse(NodeUtil.containsFunction( getNode("(b?foo():null)"))); assertFalse(NodeUtil.containsFunction( getNode("foo()"))); } private void assertSideEffect(boolean se, String js) { Node n = parse(js); assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild())); } private void assertSideEffect(boolean se, String js, boolean GlobalRegExp) { Node n = parse(js); Compiler compiler = new Compiler(); compiler.setHasRegExpGlobalReferences(GlobalRegExp); assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild(), compiler)); } public void testMayHaveSideEffects() { assertSideEffect(true, "i++"); assertSideEffect(true, "[b, [a, i++]]"); assertSideEffect(true, "i=3"); assertSideEffect(true, "[0, i=3]"); assertSideEffect(true, "b()"); assertSideEffect(true, "[1, b()]"); assertSideEffect(true, "b.b=4"); assertSideEffect(true, "b.b--"); assertSideEffect(true, "i--"); assertSideEffect(true, "a[0][i=4]"); assertSideEffect(true, "a += 3"); assertSideEffect(true, "a, b, z += 4"); assertSideEffect(true, "a ? c : d++"); assertSideEffect(true, "a + c++"); assertSideEffect(true, "a + c - d()"); assertSideEffect(true, "a + c - d()"); assertSideEffect(true, "function foo() {}"); assertSideEffect(true, "while(true);"); assertSideEffect(true, "if(true){a()}"); assertSideEffect(false, "if(true){a}"); assertSideEffect(false, "(function() { })"); assertSideEffect(false, "(function() { i++ })"); assertSideEffect(false, "[function a(){}]"); assertSideEffect(false, "a"); assertSideEffect(false, "[b, c [d, [e]]]"); assertSideEffect(false, "({a: x, b: y, c: z})"); assertSideEffect(false, "/abc/gi"); assertSideEffect(false, "'a'"); assertSideEffect(false, "0"); assertSideEffect(false, "a + c"); assertSideEffect(false, "'c' + a[0]"); assertSideEffect(false, "a[0][1]"); assertSideEffect(false, "'a' + c"); assertSideEffect(false, "'a' + a.name"); assertSideEffect(false, "1, 2, 3"); assertSideEffect(false, "a, b, 3"); assertSideEffect(false, "(function(a, b) { })"); assertSideEffect(false, "a ? c : d"); assertSideEffect(false, "'1' + navigator.userAgent"); assertSideEffect(false, "new RegExp('foobar', 'i')"); assertSideEffect(true, "new RegExp(SomethingWacky(), 'i')"); assertSideEffect(false, "new Array()"); assertSideEffect(false, "new Array"); assertSideEffect(false, "new Array(4)"); assertSideEffect(false, "new Array('a', 'b', 'c')"); assertSideEffect(true, "new SomeClassINeverHeardOf()"); assertSideEffect(true, "new SomeClassINeverHeardOf()"); assertSideEffect(false, "({}).foo = 4"); assertSideEffect(false, "([]).foo = 4"); assertSideEffect(false, "(function() {}).foo = 4"); assertSideEffect(true, "this.foo = 4"); assertSideEffect(true, "a.foo = 4"); assertSideEffect(true, "(function() { return n; })().foo = 4"); assertSideEffect(true, "([]).foo = bar()"); assertSideEffect(false, "undefined"); assertSideEffect(false, "void 0"); assertSideEffect(true, "void foo()"); assertSideEffect(false, "-Infinity"); assertSideEffect(false, "Infinity"); assertSideEffect(false, "NaN"); assertSideEffect(false, "({}||[]).foo = 2;"); assertSideEffect(false, "(true ? {} : []).foo = 2;"); assertSideEffect(false, "({},[]).foo = 2;"); } public void testObjectMethodSideEffects() { // "toString" and "valueOf" are assumed to be side-effect free assertSideEffect(false, "o.toString()"); assertSideEffect(false, "o.valueOf()"); // other methods depend on the extern definitions assertSideEffect(true, "o.watch()"); } public void testRegExpSideEffect() { // A RegExp Object by itself doesn't have any side-effects assertSideEffect(false, "/abc/gi", true); assertSideEffect(false, "/abc/gi", false); // RegExp instance methods have global side-effects, so whether they are // considered side-effect free depends on whether the global properties // are referenced. assertSideEffect(true, "(/abc/gi).test('')", true); assertSideEffect(false, "(/abc/gi).test('')", false); assertSideEffect(true, "(/abc/gi).test(a)", true); assertSideEffect(false, "(/abc/gi).test(b)", false); assertSideEffect(true, "(/abc/gi).exec('')", true); assertSideEffect(false, "(/abc/gi).exec('')", false); // Some RegExp object method that may have side-effects. assertSideEffect(true, "(/abc/gi).foo('')", true); assertSideEffect(true, "(/abc/gi).foo('')", false); // Try the string RegExp ops. assertSideEffect(true, "''.match('a')", true); assertSideEffect(false, "''.match('a')", false); assertSideEffect(true, "''.match(/(a)/)", true); assertSideEffect(false, "''.match(/(a)/)", false); assertSideEffect(true, "''.replace('a')", true); assertSideEffect(false, "''.replace('a')", false); assertSideEffect(true, "''.search('a')", true); assertSideEffect(false, "''.search('a')", false); assertSideEffect(true, "''.split('a')", true); assertSideEffect(false, "''.split('a')", false); // Some non-RegExp string op that may have side-effects. assertSideEffect(true, "''.foo('a')", true); assertSideEffect(true, "''.foo('a')", false); // 'a' might be a RegExp object with the 'g' flag, in which case // the state might change by running any of the string ops. // Specifically, using these methods resets the "lastIndex" if used // in combination with a RegExp instance "exec" method. assertSideEffect(true, "''.match(a)", true); assertSideEffect(true, "''.match(a)", false); } private void assertMutableState(boolean se, String js) { Node n = parse(js); assertEquals(se, NodeUtil.mayEffectMutableState(n.getFirstChild())); } public void testMayEffectMutableState() { assertMutableState(true, "i++"); assertMutableState(true, "[b, [a, i++]]"); assertMutableState(true, "i=3"); assertMutableState(true, "[0, i=3]"); assertMutableState(true, "b()"); assertMutableState(true, "void b()"); assertMutableState(true, "[1, b()]"); assertMutableState(true, "b.b=4"); assertMutableState(true, "b.b--"); assertMutableState(true, "i--"); assertMutableState(true, "a[0][i=4]"); assertMutableState(true, "a += 3"); assertMutableState(true, "a, b, z += 4"); assertMutableState(true, "a ? c : d++"); assertMutableState(true, "a + c++"); assertMutableState(true, "a + c - d()"); assertMutableState(true, "a + c - d()"); assertMutableState(true, "function foo() {}"); assertMutableState(true, "while(true);"); assertMutableState(true, "if(true){a()}"); assertMutableState(false, "if(true){a}"); assertMutableState(true, "(function() { })"); assertMutableState(true, "(function() { i++ })"); assertMutableState(true, "[function a(){}]"); assertMutableState(false, "a"); assertMutableState(true, "[b, c [d, [e]]]"); assertMutableState(true, "({a: x, b: y, c: z})"); // Note: RegEx objects are not immutable, for instance, the exec // method maintains state for "global" searches. assertMutableState(true, "/abc/gi"); assertMutableState(false, "'a'"); assertMutableState(false, "0"); assertMutableState(false, "a + c"); assertMutableState(false, "'c' + a[0]"); assertMutableState(false, "a[0][1]"); assertMutableState(false, "'a' + c"); assertMutableState(false, "'a' + a.name"); assertMutableState(false, "1, 2, 3"); assertMutableState(false, "a, b, 3"); assertMutableState(true, "(function(a, b) { })"); assertMutableState(false, "a ? c : d"); assertMutableState(false, "'1' + navigator.userAgent"); assertMutableState(true, "new RegExp('foobar', 'i')"); assertMutableState(true, "new RegExp(SomethingWacky(), 'i')"); assertMutableState(true, "new Array()"); assertMutableState(true, "new Array"); assertMutableState(true, "new Array(4)"); assertMutableState(true, "new Array('a', 'b', 'c')"); assertMutableState(true, "new SomeClassINeverHeardOf()"); } public void testIsFunctionExpression() { assertContainsAnonFunc(true, "(function(){})"); assertContainsAnonFunc(true, "[function a(){}]"); assertContainsAnonFunc(false, "{x: function a(){}}"); assertContainsAnonFunc(true, "(function a(){})()"); assertContainsAnonFunc(true, "x = function a(){};"); assertContainsAnonFunc(true, "var x = function a(){};"); assertContainsAnonFunc(true, "if (function a(){});"); assertContainsAnonFunc(true, "while (function a(){});"); assertContainsAnonFunc(true, "do; while (function a(){});"); assertContainsAnonFunc(true, "for (function a(){};;);"); assertContainsAnonFunc(true, "for (;function a(){};);"); assertContainsAnonFunc(true, "for (;;function a(){});"); assertContainsAnonFunc(true, "for (p in function a(){});"); assertContainsAnonFunc(true, "with (function a(){}) {}"); assertContainsAnonFunc(false, "function a(){}"); assertContainsAnonFunc(false, "if (x) function a(){};"); assertContainsAnonFunc(false, "if (x) { function a(){} }"); assertContainsAnonFunc(false, "if (x); else function a(){};"); assertContainsAnonFunc(false, "while (x) function a(){};"); assertContainsAnonFunc(false, "do function a(){} while (0);"); assertContainsAnonFunc(false, "for (;;) function a(){}"); assertContainsAnonFunc(false, "for (p in o) function a(){};"); assertContainsAnonFunc(false, "with (x) function a(){}"); } public void testNewFunctionNode() { Node expected = parse("function foo(p1, p2, p3) { throw 2; }"); Node body = new Node(Token.BLOCK, new Node(Token.THROW, Node.newNumber(2))); List<Node> params = Lists.newArrayList(Node.newString(Token.NAME, "p1"), Node.newString(Token.NAME, "p2"), Node.newString(Token.NAME, "p3")); Node function = NodeUtil.newFunctionNode( "foo", params, body, -1, -1); Node actual = new Node(Token.SCRIPT); actual.addChildToFront(function); String difference = expected.checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } private void assertContainsAnonFunc(boolean expected, String js) { Node funcParent = findParentOfFuncDescendant(parse(js)); assertNotNull("Expected function node in parse tree of: " + js, funcParent); Node funcNode = getFuncChild(funcParent); assertEquals(expected, NodeUtil.isFunctionExpression(funcNode)); } private Node findParentOfFuncDescendant(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.getType() == Token.FUNCTION) { return n; } Node result = findParentOfFuncDescendant(c); if (result != null) { return result; } } return null; } private Node getFuncChild(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.getType() == Token.FUNCTION) { return c; } } return null; } public void testContainsType() { assertTrue(NodeUtil.containsType( parse("this"), Token.THIS)); assertTrue(NodeUtil.containsType( parse("function foo(){}(this)"), Token.THIS)); assertTrue(NodeUtil.containsType( parse("b?this:null"), Token.THIS)); assertFalse(NodeUtil.containsType( parse("a"), Token.THIS)); assertFalse(NodeUtil.containsType( parse("function foo(){}"), Token.THIS)); assertFalse(NodeUtil.containsType( parse("(b?foo():null)"), Token.THIS)); } public void testReferencesThis() { assertTrue(NodeUtil.referencesThis( parse("this"))); assertTrue(NodeUtil.referencesThis( parse("function foo(){}(this)"))); assertTrue(NodeUtil.referencesThis( parse("b?this:null"))); assertFalse(NodeUtil.referencesThis( parse("a"))); assertFalse(NodeUtil.referencesThis( parse("function foo(){}"))); assertFalse(NodeUtil.referencesThis( parse("(b?foo():null)"))); } public void testGetNodeTypeReferenceCount() { assertEquals(0, NodeUtil.getNodeTypeReferenceCount( parse("function foo(){}"), Token.THIS, Predicates.<Node>alwaysTrue())); assertEquals(1, NodeUtil.getNodeTypeReferenceCount( parse("this"), Token.THIS, Predicates.<Node>alwaysTrue())); assertEquals(2, NodeUtil.getNodeTypeReferenceCount( parse("this;function foo(){}(this)"), Token.THIS, Predicates.<Node>alwaysTrue())); } public void testIsNameReferenceCount() { assertTrue(NodeUtil.isNameReferenced( parse("function foo(){}"), "foo")); assertTrue(NodeUtil.isNameReferenced( parse("var foo = function(){}"), "foo")); assertFalse(NodeUtil.isNameReferenced( parse("function foo(){}"), "undefined")); assertTrue(NodeUtil.isNameReferenced( parse("undefined"), "undefined")); assertTrue(NodeUtil.isNameReferenced( parse("undefined;function foo(){}(undefined)"), "undefined")); assertTrue(NodeUtil.isNameReferenced( parse("goo.foo"), "goo")); assertFalse(NodeUtil.isNameReferenced( parse("goo.foo"), "foo")); } public void testGetNameReferenceCount() { assertEquals(0, NodeUtil.getNameReferenceCount( parse("function foo(){}"), "undefined")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("undefined"), "undefined")); assertEquals(2, NodeUtil.getNameReferenceCount( parse("undefined;function foo(){}(undefined)"), "undefined")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("goo.foo"), "goo")); assertEquals(0, NodeUtil.getNameReferenceCount( parse("goo.foo"), "foo")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("function foo(){}"), "foo")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("var foo = function(){}"), "foo")); } public void testGetVarsDeclaredInBranch() { Compiler compiler = new Compiler(); assertNodeNames(Sets.newHashSet("foo"), NodeUtil.getVarsDeclaredInBranch( parse("var foo;"))); assertNodeNames(Sets.newHashSet("foo","goo"), NodeUtil.getVarsDeclaredInBranch( parse("var foo,goo;"))); assertNodeNames(Sets.<String>newHashSet(), NodeUtil.getVarsDeclaredInBranch( parse("foo();"))); assertNodeNames(Sets.<String>newHashSet(), NodeUtil.getVarsDeclaredInBranch( parse("function(){var foo;}"))); assertNodeNames(Sets.newHashSet("goo"), NodeUtil.getVarsDeclaredInBranch( parse("var goo;function(){var foo;}"))); } private void assertNodeNames(Set<String> nodeNames, Collection<Node> nodes) { Set<String> actualNames = Sets.newHashSet(); for (Node node : nodes) { actualNames.add(node.getString()); } assertEquals(nodeNames, actualNames); } public void testIsControlStructureCodeBlock() { Compiler compiler = new Compiler(); Node root = parse("if (x) foo(); else boo();"); Node ifNode = root.getFirstChild(); Node ifCondition = ifNode.getFirstChild(); Node ifCase = ifNode.getFirstChild().getNext(); Node elseCase = ifNode.getLastChild(); assertFalse(NodeUtil.isControlStructureCodeBlock(ifNode, ifCondition)); assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, ifCase)); assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, elseCase)); } public void testIsFunctionExpression1() { Compiler compiler = new Compiler(); Node root = parse("(function foo() {})"); Node StatementNode = root.getFirstChild(); assertTrue(NodeUtil.isExpressionNode(StatementNode)); Node functionNode = StatementNode.getFirstChild(); assertTrue(NodeUtil.isFunction(functionNode)); assertTrue(NodeUtil.isFunctionExpression(functionNode)); } public void testIsFunctionExpression2() { Compiler compiler = new Compiler(); Node root = parse("function foo() {}"); Node functionNode = root.getFirstChild(); assertTrue(NodeUtil.isFunction(functionNode)); assertFalse(NodeUtil.isFunctionExpression(functionNode)); } public void testRemoveTryChild() { Compiler compiler = new Compiler(); Node root = parse("try {foo()} catch(e) {} finally {}"); // Test removing the finally clause. Node actual = root.cloneTree(); Node tryNode = actual.getFirstChild(); Node tryBlock = tryNode.getFirstChild(); Node catchBlocks = tryNode.getFirstChild().getNext(); Node finallyBlock = tryNode.getLastChild(); NodeUtil.removeChild(tryNode, finallyBlock); String expected = "try {foo()} catch(e) {}"; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the try clause. actual = root.cloneTree(); tryNode = actual.getFirstChild(); tryBlock = tryNode.getFirstChild(); catchBlocks = tryNode.getFirstChild().getNext(); finallyBlock = tryNode.getLastChild(); NodeUtil.removeChild(tryNode, tryBlock); expected = "try {} catch(e) {} finally {}"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the catch clause. actual = root.cloneTree(); tryNode = actual.getFirstChild(); tryBlock = tryNode.getFirstChild(); catchBlocks = tryNode.getFirstChild().getNext(); Node catchBlock = catchBlocks.getFirstChild(); finallyBlock = tryNode.getLastChild(); NodeUtil.removeChild(catchBlocks, catchBlock); expected = "try {foo()} finally {}"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveVarChild() { Compiler compiler = new Compiler(); // Test removing the first child. Node actual = parse("var foo, goo, hoo"); Node varNode = actual.getFirstChild(); Node nameNode = varNode.getFirstChild(); NodeUtil.removeChild(varNode, nameNode); String expected = "var goo, hoo"; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the second child. actual = parse("var foo, goo, hoo"); varNode = actual.getFirstChild(); nameNode = varNode.getFirstChild().getNext(); NodeUtil.removeChild(varNode, nameNode); expected = "var foo, hoo"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the last child of several children. actual = parse("var foo, hoo"); varNode = actual.getFirstChild(); nameNode = varNode.getFirstChild().getNext(); NodeUtil.removeChild(varNode, nameNode); expected = "var foo"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the last. actual = parse("var hoo"); varNode = actual.getFirstChild(); nameNode = varNode.getFirstChild(); NodeUtil.removeChild(varNode, nameNode); expected = ""; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveLabelChild1() { Compiler compiler = new Compiler(); // Test removing the first child. Node actual = parse("foo: goo()"); Node labelNode = actual.getFirstChild(); Node callExpressNode = labelNode.getLastChild(); NodeUtil.removeChild(labelNode, callExpressNode); String expected = ""; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveLabelChild2() { // Test removing the first child. Node actual = parse("achoo: foo: goo()"); Node labelNode = actual.getFirstChild(); Node callExpressNode = labelNode.getLastChild(); NodeUtil.removeChild(labelNode, callExpressNode); String expected = ""; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveForChild() { Compiler compiler = new Compiler(); // Test removing the initializer. Node actual = parse("for(var a=0;a<0;a++)foo()"); Node forNode = actual.getFirstChild(); Node child = forNode.getFirstChild(); NodeUtil.removeChild(forNode, child); String expected = "for(;a<0;a++)foo()"; String difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the condition. actual = parse("for(var a=0;a<0;a++)foo()"); forNode = actual.getFirstChild(); child = forNode.getFirstChild().getNext(); NodeUtil.removeChild(forNode, child); expected = "for(var a=0;;a++)foo()"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the increment. actual = parse("for(var a=0;a<0;a++)foo()"); forNode = actual.getFirstChild(); child = forNode.getFirstChild().getNext().getNext(); NodeUtil.removeChild(forNode, child); expected = "for(var a=0;a<0;)foo()"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the body. actual = parse("for(var a=0;a<0;a++)foo()"); forNode = actual.getFirstChild(); child = forNode.getLastChild(); NodeUtil.removeChild(forNode, child); expected = "for(var a=0;a<0;a++);"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the body. actual = parse("for(a in ack)foo();"); forNode = actual.getFirstChild(); child = forNode.getLastChild(); NodeUtil.removeChild(forNode, child); expected = "for(a in ack);"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); } public void testMergeBlock1() { Compiler compiler = new Compiler(); // Test removing the initializer. Node actual = parse("{{a();b();}}"); Node parentBlock = actual.getFirstChild(); Node childBlock = parentBlock.getFirstChild(); assertTrue(NodeUtil.tryMergeBlock(childBlock)); String expected = "{a();b();}"; String difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); } public void testMergeBlock2() { Compiler compiler = new Compiler(); // Test removing the initializer. Node actual = parse("foo:{a();}"); Node parentLabel = actual.getFirstChild(); Node childBlock = parentLabel.getLastChild(); assertFalse(NodeUtil.tryMergeBlock(childBlock)); } public void testMergeBlock3() { Compiler compiler = new Compiler(); // Test removing the initializer. String code = "foo:{a();boo()}"; Node actual = parse("foo:{a();boo()}"); Node parentLabel = actual.getFirstChild(); Node childBlock = parentLabel.getLastChild(); assertFalse(NodeUtil.tryMergeBlock(childBlock)); String expected = code; String difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); } public void testGetSourceName() { Node n = new Node(Token.BLOCK); Node parent = new Node(Token.BLOCK, n); parent.putProp(Node.SOURCENAME_PROP, "foo"); assertEquals("foo", NodeUtil.getSourceName(n)); } public void testIsLabelName() { Compiler compiler = new Compiler(); // Test removing the initializer. String code = "a:while(1) {a; continue a; break a; break;}"; Node actual = parse(code); Node labelNode = actual.getFirstChild(); assertTrue(labelNode.getType() == Token.LABEL); assertTrue(NodeUtil.isLabelName(labelNode.getFirstChild())); assertFalse(NodeUtil.isLabelName(labelNode.getLastChild())); Node whileNode = labelNode.getLastChild(); assertTrue(whileNode.getType() == Token.WHILE); Node whileBlock = whileNode.getLastChild(); assertTrue(whileBlock.getType() == Token.BLOCK); assertFalse(NodeUtil.isLabelName(whileBlock)); Node firstStatement = whileBlock.getFirstChild(); assertTrue(firstStatement.getType() == Token.EXPR_RESULT); Node variableReference = firstStatement.getFirstChild(); assertTrue(variableReference.getType() == Token.NAME); assertFalse(NodeUtil.isLabelName(variableReference)); Node continueStatement = firstStatement.getNext(); assertTrue(continueStatement.getType() == Token.CONTINUE); assertTrue(NodeUtil.isLabelName(continueStatement.getFirstChild())); Node firstBreak = continueStatement.getNext(); assertTrue(firstBreak.getType() == Token.BREAK); assertTrue(NodeUtil.isLabelName(firstBreak.getFirstChild())); Node secondBreak = firstBreak.getNext(); assertTrue(secondBreak.getType() == Token.BREAK); assertFalse(secondBreak.hasChildren()); assertFalse(NodeUtil.isLabelName(secondBreak.getFirstChild())); } public void testLocalValue1() throws Exception { // Names are not known to be local. assertFalse(testLocalValue("x")); assertFalse(testLocalValue("x()")); assertFalse(testLocalValue("this")); assertFalse(testLocalValue("arguments")); // We can't know if new objects are local unless we know // that they don't alias themselves. assertFalse(testLocalValue("new x()")); // property references are assume to be non-local assertFalse(testLocalValue("(new x()).y")); assertFalse(testLocalValue("(new x())['y']")); // Primitive values are local assertTrue(testLocalValue("null")); assertTrue(testLocalValue("undefined")); assertTrue(testLocalValue("Infinity")); assertTrue(testLocalValue("NaN")); assertTrue(testLocalValue("1")); assertTrue(testLocalValue("'a'")); assertTrue(testLocalValue("true")); assertTrue(testLocalValue("false")); assertTrue(testLocalValue("[]")); assertTrue(testLocalValue("{}")); // The contents of arrays and objects don't matter assertTrue(testLocalValue("[x]")); assertTrue(testLocalValue("{'a':x}")); // Pre-increment results in primitive number assertTrue(testLocalValue("++x")); assertTrue(testLocalValue("--x")); // Post-increment, the previous value matters. assertFalse(testLocalValue("x++")); assertFalse(testLocalValue("x--")); // The left side of an only assign matters if it is an alias or mutable. assertTrue(testLocalValue("x=1")); assertFalse(testLocalValue("x=[]")); assertFalse(testLocalValue("x=y")); // The right hand side of assignment opts don't matter, as they force // a local result. assertTrue(testLocalValue("x+=y")); assertTrue(testLocalValue("x*=y")); // Comparisons always result in locals, as they force a local boolean // result. assertTrue(testLocalValue("x==y")); assertTrue(testLocalValue("x!=y")); assertTrue(testLocalValue("x>y")); // Only the right side of a comma matters assertTrue(testLocalValue("(1,2)")); assertTrue(testLocalValue("(x,1)")); assertFalse(testLocalValue("(x,y)")); // Both the operands of OR matter assertTrue(testLocalValue("1||2")); assertFalse(testLocalValue("x||1")); assertFalse(testLocalValue("x||y")); assertFalse(testLocalValue("1||y")); // Both the operands of AND matter assertTrue(testLocalValue("1&&2")); assertFalse(testLocalValue("x&&1")); assertFalse(testLocalValue("x&&y")); assertFalse(testLocalValue("1&&y")); // Only the results of HOOK matter assertTrue(testLocalValue("x?1:2")); assertFalse(testLocalValue("x?x:2")); assertFalse(testLocalValue("x?1:x")); assertFalse(testLocalValue("x?x:y")); // Results of ops are local values assertTrue(testLocalValue("!y")); assertTrue(testLocalValue("~y")); assertTrue(testLocalValue("y + 1")); assertTrue(testLocalValue("y + z")); assertTrue(testLocalValue("y * z")); assertTrue(testLocalValue("'a' in x")); assertTrue(testLocalValue("typeof x")); assertTrue(testLocalValue("x instanceof y")); assertTrue(testLocalValue("void x")); assertTrue(testLocalValue("void 0")); assertFalse(testLocalValue("{}.x")); assertTrue(testLocalValue("{}.toString()")); assertTrue(testLocalValue("o.toString()")); assertFalse(testLocalValue("o.valueOf()")); } private boolean testLocalValue(String js) { Node script = parse("var test = " + js +";"); Preconditions.checkState(script.getType() == Token.SCRIPT); Node var = script.getFirstChild(); Preconditions.checkState(var.getType() == Token.VAR); Node name = var.getFirstChild(); Preconditions.checkState(name.getType() == Token.NAME); Node value = name.getFirstChild(); return NodeUtil.evaluatesToLocalValue(value); } public void testValidDefine() { assertTrue(testValidDefineValue("1")); assertTrue(testValidDefineValue("-3")); assertTrue(testValidDefineValue("true")); assertTrue(testValidDefineValue("false")); assertTrue(testValidDefineValue("'foo'")); assertFalse(testValidDefineValue("x")); assertFalse(testValidDefineValue("null")); assertFalse(testValidDefineValue("undefined")); assertFalse(testValidDefineValue("NaN")); assertTrue(testValidDefineValue("!true")); assertTrue(testValidDefineValue("-true")); assertTrue(testValidDefineValue("1 & 8")); assertTrue(testValidDefineValue("1 + 8")); assertTrue(testValidDefineValue("'a' + 'b'")); assertFalse(testValidDefineValue("1 & foo")); } private boolean testValidDefineValue(String js) { Node script = parse("var test = " + js +";"); Node var = script.getFirstChild(); Node name = var.getFirstChild(); Node value = name.getFirstChild(); ImmutableSet<String> defines = ImmutableSet.of(); return NodeUtil.isValidDefineValue(value, defines); } }
// You are a professional Java test case writer, please create a test case named `testLocalValue1` for the issue `Closure-303`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-303 // // ## Issue-Title: // side-effects analysis incorrectly removing function calls with side effects // // ## Issue-Description: // Sample Code: // --- // /\*\* @constructor \*/ // function Foo() { // var self = this; // window.setTimeout(function() { // window.location = self.location; // }, 0); // } // // Foo.prototype.setLocation = function(loc) { // this.location = loc; // }; // // (new Foo()).setLocation('http://www.google.com/'); // --- // // The setLocation call will get removed in advanced mode. // // public void testLocalValue1() throws Exception {
1,108
86
1,013
test/com/google/javascript/jscomp/NodeUtilTest.java
test
```markdown ## Issue-ID: Closure-303 ## Issue-Title: side-effects analysis incorrectly removing function calls with side effects ## Issue-Description: Sample Code: --- /\*\* @constructor \*/ function Foo() { var self = this; window.setTimeout(function() { window.location = self.location; }, 0); } Foo.prototype.setLocation = function(loc) { this.location = loc; }; (new Foo()).setLocation('http://www.google.com/'); --- The setLocation call will get removed in advanced mode. ``` You are a professional Java test case writer, please create a test case named `testLocalValue1` for the issue `Closure-303`, utilizing the provided issue report information and the following function signature. ```java public void testLocalValue1() throws Exception { ```
1,013
[ "com.google.javascript.jscomp.NodeUtil" ]
fee568c2289096948779d7ab9ec10bc3c6b08d4a2be623e6e65b9d8ead9a3e25
public void testLocalValue1() throws Exception
// You are a professional Java test case writer, please create a test case named `testLocalValue1` for the issue `Closure-303`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-303 // // ## Issue-Title: // side-effects analysis incorrectly removing function calls with side effects // // ## Issue-Description: // Sample Code: // --- // /\*\* @constructor \*/ // function Foo() { // var self = this; // window.setTimeout(function() { // window.location = self.location; // }, 0); // } // // Foo.prototype.setLocation = function(loc) { // this.location = loc; // }; // // (new Foo()).setLocation('http://www.google.com/'); // --- // // The setLocation call will get removed in advanced mode. // //
Closure
/* * Copyright 2004 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.TernaryValue; import junit.framework.TestCase; import java.util.Collection; import java.util.List; import java.util.Set; public class NodeUtilTest extends TestCase { private static Node parse(String js) { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode(js); assertEquals(0, compiler.getErrorCount()); return n; } static Node getNode(String js) { Node root = parse("var a=(" + js + ");"); Node expr = root.getFirstChild(); Node var = expr.getFirstChild(); return var.getFirstChild(); } public void testIsLiteralOrConstValue() { assertLiteralAndImmutable(getNode("10")); assertLiteralAndImmutable(getNode("-10")); assertLiteralButNotImmutable(getNode("[10, 20]")); assertLiteralButNotImmutable(getNode("{'a': 20}")); assertLiteralButNotImmutable(getNode("[10, , 1.0, [undefined], 'a']")); assertLiteralButNotImmutable(getNode("/abc/")); assertLiteralAndImmutable(getNode("\"string\"")); assertLiteralAndImmutable(getNode("'aaa'")); assertLiteralAndImmutable(getNode("null")); assertLiteralAndImmutable(getNode("undefined")); assertLiteralAndImmutable(getNode("void 0")); assertNotLiteral(getNode("abc")); assertNotLiteral(getNode("[10, foo(), 20]")); assertNotLiteral(getNode("foo()")); assertNotLiteral(getNode("c + d")); assertNotLiteral(getNode("{'a': foo()}")); assertNotLiteral(getNode("void foo()")); } public void assertLiteralAndImmutable(Node n) { assertTrue(NodeUtil.isLiteralValue(n, true)); assertTrue(NodeUtil.isLiteralValue(n, false)); assertTrue(NodeUtil.isImmutableValue(n)); } public void assertLiteralButNotImmutable(Node n) { assertTrue(NodeUtil.isLiteralValue(n, true)); assertTrue(NodeUtil.isLiteralValue(n, false)); assertFalse(NodeUtil.isImmutableValue(n)); } public void assertNotLiteral(Node n) { assertFalse(NodeUtil.isLiteralValue(n, true)); assertFalse(NodeUtil.isLiteralValue(n, false)); assertFalse(NodeUtil.isImmutableValue(n)); } public void testGetBooleanValue() { assertBooleanTrue("true"); assertBooleanTrue("10"); assertBooleanTrue("'0'"); assertBooleanTrue("/a/"); assertBooleanTrue("{}"); assertBooleanTrue("[]"); assertBooleanFalse("false"); assertBooleanFalse("null"); assertBooleanFalse("0"); assertBooleanFalse("''"); assertBooleanFalse("undefined"); assertBooleanFalse("void 0"); assertBooleanFalse("void foo()"); assertBooleanUnknown("b"); assertBooleanUnknown("-'0.0'"); } private void assertBooleanTrue(String val) { assertEquals(TernaryValue.TRUE, NodeUtil.getBooleanValue(getNode(val))); } private void assertBooleanFalse(String val) { assertEquals(TernaryValue.FALSE, NodeUtil.getBooleanValue(getNode(val))); } private void assertBooleanUnknown(String val) { assertEquals(TernaryValue.UNKNOWN, NodeUtil.getBooleanValue(getNode(val))); } public void testGetExpressionBooleanValue() { assertExpressionBooleanTrue("a=true"); assertExpressionBooleanFalse("a=false"); assertExpressionBooleanTrue("a=(false,true)"); assertExpressionBooleanFalse("a=(true,false)"); assertExpressionBooleanTrue("a=(false || true)"); assertExpressionBooleanFalse("a=(true && false)"); assertExpressionBooleanTrue("a=!(true && false)"); assertExpressionBooleanTrue("a,true"); assertExpressionBooleanFalse("a,false"); assertExpressionBooleanTrue("true||false"); assertExpressionBooleanFalse("false||false"); assertExpressionBooleanTrue("true&&true"); assertExpressionBooleanFalse("true&&false"); assertExpressionBooleanFalse("!true"); assertExpressionBooleanTrue("!false"); assertExpressionBooleanTrue("!''"); // Assignment ops other than ASSIGN are unknown. assertExpressionBooleanUnknown("a *= 2"); // Complex expressions that contain anything other then "=", ",", or "!" are // unknown. assertExpressionBooleanUnknown("2 + 2"); assertExpressionBooleanTrue("a=1"); assertExpressionBooleanTrue("a=/a/"); assertExpressionBooleanTrue("a={}"); assertExpressionBooleanTrue("true"); assertExpressionBooleanTrue("10"); assertExpressionBooleanTrue("'0'"); assertExpressionBooleanTrue("/a/"); assertExpressionBooleanTrue("{}"); assertExpressionBooleanTrue("[]"); assertExpressionBooleanFalse("false"); assertExpressionBooleanFalse("null"); assertExpressionBooleanFalse("0"); assertExpressionBooleanFalse("''"); assertExpressionBooleanFalse("undefined"); assertExpressionBooleanFalse("void 0"); assertExpressionBooleanFalse("void foo()"); assertExpressionBooleanTrue("a?true:true"); assertExpressionBooleanFalse("a?false:false"); assertExpressionBooleanUnknown("a?true:false"); assertExpressionBooleanUnknown("a?true:foo()"); assertExpressionBooleanUnknown("b"); assertExpressionBooleanUnknown("-'0.0'"); } private void assertExpressionBooleanTrue(String val) { assertEquals(TernaryValue.TRUE, NodeUtil.getExpressionBooleanValue(getNode(val))); } private void assertExpressionBooleanFalse(String val) { assertEquals(TernaryValue.FALSE, NodeUtil.getExpressionBooleanValue(getNode(val))); } private void assertExpressionBooleanUnknown(String val) { assertEquals(TernaryValue.UNKNOWN, NodeUtil.getExpressionBooleanValue(getNode(val))); } public void testGetStringValue() { assertEquals("true", NodeUtil.getStringValue(getNode("true"))); assertEquals("10", NodeUtil.getStringValue(getNode("10"))); assertEquals("1", NodeUtil.getStringValue(getNode("1.0"))); assertEquals("0", NodeUtil.getStringValue(getNode("'0'"))); assertEquals(null, NodeUtil.getStringValue(getNode("/a/"))); assertEquals(null, NodeUtil.getStringValue(getNode("{}"))); assertEquals(null, NodeUtil.getStringValue(getNode("[]"))); assertEquals("false", NodeUtil.getStringValue(getNode("false"))); assertEquals("null", NodeUtil.getStringValue(getNode("null"))); assertEquals("0", NodeUtil.getStringValue(getNode("0"))); assertEquals("", NodeUtil.getStringValue(getNode("''"))); assertEquals("undefined", NodeUtil.getStringValue(getNode("undefined"))); assertEquals("undefined", NodeUtil.getStringValue(getNode("void 0"))); assertEquals("undefined", NodeUtil.getStringValue(getNode("void foo()"))); assertEquals("NaN", NodeUtil.getStringValue(getNode("NaN"))); assertEquals("Infinity", NodeUtil.getStringValue(getNode("Infinity"))); assertEquals(null, NodeUtil.getStringValue(getNode("x"))); } public void testIsObjectLiteralKey1() throws Exception { testIsObjectLiteralKey( parseExpr("({})"), false); testIsObjectLiteralKey( parseExpr("a"), false); testIsObjectLiteralKey( parseExpr("'a'"), false); testIsObjectLiteralKey( parseExpr("1"), false); testIsObjectLiteralKey( parseExpr("({a: 1})").getFirstChild(), true); testIsObjectLiteralKey( parseExpr("({1: 1})").getFirstChild(), true); testIsObjectLiteralKey( parseExpr("({get a(){}})").getFirstChild(), true); testIsObjectLiteralKey( parseExpr("({set a(b){}})").getFirstChild(), true); } private Node parseExpr(String js) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); options.languageIn = LanguageMode.ECMASCRIPT5; compiler.initOptions(options); Node root = compiler.parseTestCode(js); return root.getFirstChild().getFirstChild(); } private void testIsObjectLiteralKey(Node node, boolean expected) { assertEquals(expected, NodeUtil.isObjectLitKey(node, node.getParent())); } public void testGetFunctionName1() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("function name(){}"); testGetFunctionName(parent.getFirstChild(), "name"); } public void testGetFunctionName2() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("var name = function(){}") .getFirstChild().getFirstChild(); testGetFunctionName(parent.getFirstChild(), "name"); } public void testGetFunctionName3() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("qualified.name = function(){}") .getFirstChild().getFirstChild(); testGetFunctionName(parent.getLastChild(), "qualified.name"); } public void testGetFunctionName4() throws Exception { Compiler compiler = new Compiler(); Node parent = compiler.parseTestCode("var name2 = function name1(){}") .getFirstChild().getFirstChild(); testGetFunctionName(parent.getFirstChild(), "name2"); } public void testGetFunctionName5() throws Exception { Compiler compiler = new Compiler(); Node n = compiler.parseTestCode("qualified.name2 = function name1(){}"); Node parent = n.getFirstChild().getFirstChild(); testGetFunctionName(parent.getLastChild(), "qualified.name2"); } private void testGetFunctionName(Node function, String name) { assertEquals(Token.FUNCTION, function.getType()); assertEquals(name, NodeUtil.getFunctionName(function)); } public void testContainsFunctionDeclaration() { assertTrue(NodeUtil.containsFunction( getNode("function foo(){}"))); assertTrue(NodeUtil.containsFunction( getNode("(b?function(){}:null)"))); assertFalse(NodeUtil.containsFunction( getNode("(b?foo():null)"))); assertFalse(NodeUtil.containsFunction( getNode("foo()"))); } private void assertSideEffect(boolean se, String js) { Node n = parse(js); assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild())); } private void assertSideEffect(boolean se, String js, boolean GlobalRegExp) { Node n = parse(js); Compiler compiler = new Compiler(); compiler.setHasRegExpGlobalReferences(GlobalRegExp); assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild(), compiler)); } public void testMayHaveSideEffects() { assertSideEffect(true, "i++"); assertSideEffect(true, "[b, [a, i++]]"); assertSideEffect(true, "i=3"); assertSideEffect(true, "[0, i=3]"); assertSideEffect(true, "b()"); assertSideEffect(true, "[1, b()]"); assertSideEffect(true, "b.b=4"); assertSideEffect(true, "b.b--"); assertSideEffect(true, "i--"); assertSideEffect(true, "a[0][i=4]"); assertSideEffect(true, "a += 3"); assertSideEffect(true, "a, b, z += 4"); assertSideEffect(true, "a ? c : d++"); assertSideEffect(true, "a + c++"); assertSideEffect(true, "a + c - d()"); assertSideEffect(true, "a + c - d()"); assertSideEffect(true, "function foo() {}"); assertSideEffect(true, "while(true);"); assertSideEffect(true, "if(true){a()}"); assertSideEffect(false, "if(true){a}"); assertSideEffect(false, "(function() { })"); assertSideEffect(false, "(function() { i++ })"); assertSideEffect(false, "[function a(){}]"); assertSideEffect(false, "a"); assertSideEffect(false, "[b, c [d, [e]]]"); assertSideEffect(false, "({a: x, b: y, c: z})"); assertSideEffect(false, "/abc/gi"); assertSideEffect(false, "'a'"); assertSideEffect(false, "0"); assertSideEffect(false, "a + c"); assertSideEffect(false, "'c' + a[0]"); assertSideEffect(false, "a[0][1]"); assertSideEffect(false, "'a' + c"); assertSideEffect(false, "'a' + a.name"); assertSideEffect(false, "1, 2, 3"); assertSideEffect(false, "a, b, 3"); assertSideEffect(false, "(function(a, b) { })"); assertSideEffect(false, "a ? c : d"); assertSideEffect(false, "'1' + navigator.userAgent"); assertSideEffect(false, "new RegExp('foobar', 'i')"); assertSideEffect(true, "new RegExp(SomethingWacky(), 'i')"); assertSideEffect(false, "new Array()"); assertSideEffect(false, "new Array"); assertSideEffect(false, "new Array(4)"); assertSideEffect(false, "new Array('a', 'b', 'c')"); assertSideEffect(true, "new SomeClassINeverHeardOf()"); assertSideEffect(true, "new SomeClassINeverHeardOf()"); assertSideEffect(false, "({}).foo = 4"); assertSideEffect(false, "([]).foo = 4"); assertSideEffect(false, "(function() {}).foo = 4"); assertSideEffect(true, "this.foo = 4"); assertSideEffect(true, "a.foo = 4"); assertSideEffect(true, "(function() { return n; })().foo = 4"); assertSideEffect(true, "([]).foo = bar()"); assertSideEffect(false, "undefined"); assertSideEffect(false, "void 0"); assertSideEffect(true, "void foo()"); assertSideEffect(false, "-Infinity"); assertSideEffect(false, "Infinity"); assertSideEffect(false, "NaN"); assertSideEffect(false, "({}||[]).foo = 2;"); assertSideEffect(false, "(true ? {} : []).foo = 2;"); assertSideEffect(false, "({},[]).foo = 2;"); } public void testObjectMethodSideEffects() { // "toString" and "valueOf" are assumed to be side-effect free assertSideEffect(false, "o.toString()"); assertSideEffect(false, "o.valueOf()"); // other methods depend on the extern definitions assertSideEffect(true, "o.watch()"); } public void testRegExpSideEffect() { // A RegExp Object by itself doesn't have any side-effects assertSideEffect(false, "/abc/gi", true); assertSideEffect(false, "/abc/gi", false); // RegExp instance methods have global side-effects, so whether they are // considered side-effect free depends on whether the global properties // are referenced. assertSideEffect(true, "(/abc/gi).test('')", true); assertSideEffect(false, "(/abc/gi).test('')", false); assertSideEffect(true, "(/abc/gi).test(a)", true); assertSideEffect(false, "(/abc/gi).test(b)", false); assertSideEffect(true, "(/abc/gi).exec('')", true); assertSideEffect(false, "(/abc/gi).exec('')", false); // Some RegExp object method that may have side-effects. assertSideEffect(true, "(/abc/gi).foo('')", true); assertSideEffect(true, "(/abc/gi).foo('')", false); // Try the string RegExp ops. assertSideEffect(true, "''.match('a')", true); assertSideEffect(false, "''.match('a')", false); assertSideEffect(true, "''.match(/(a)/)", true); assertSideEffect(false, "''.match(/(a)/)", false); assertSideEffect(true, "''.replace('a')", true); assertSideEffect(false, "''.replace('a')", false); assertSideEffect(true, "''.search('a')", true); assertSideEffect(false, "''.search('a')", false); assertSideEffect(true, "''.split('a')", true); assertSideEffect(false, "''.split('a')", false); // Some non-RegExp string op that may have side-effects. assertSideEffect(true, "''.foo('a')", true); assertSideEffect(true, "''.foo('a')", false); // 'a' might be a RegExp object with the 'g' flag, in which case // the state might change by running any of the string ops. // Specifically, using these methods resets the "lastIndex" if used // in combination with a RegExp instance "exec" method. assertSideEffect(true, "''.match(a)", true); assertSideEffect(true, "''.match(a)", false); } private void assertMutableState(boolean se, String js) { Node n = parse(js); assertEquals(se, NodeUtil.mayEffectMutableState(n.getFirstChild())); } public void testMayEffectMutableState() { assertMutableState(true, "i++"); assertMutableState(true, "[b, [a, i++]]"); assertMutableState(true, "i=3"); assertMutableState(true, "[0, i=3]"); assertMutableState(true, "b()"); assertMutableState(true, "void b()"); assertMutableState(true, "[1, b()]"); assertMutableState(true, "b.b=4"); assertMutableState(true, "b.b--"); assertMutableState(true, "i--"); assertMutableState(true, "a[0][i=4]"); assertMutableState(true, "a += 3"); assertMutableState(true, "a, b, z += 4"); assertMutableState(true, "a ? c : d++"); assertMutableState(true, "a + c++"); assertMutableState(true, "a + c - d()"); assertMutableState(true, "a + c - d()"); assertMutableState(true, "function foo() {}"); assertMutableState(true, "while(true);"); assertMutableState(true, "if(true){a()}"); assertMutableState(false, "if(true){a}"); assertMutableState(true, "(function() { })"); assertMutableState(true, "(function() { i++ })"); assertMutableState(true, "[function a(){}]"); assertMutableState(false, "a"); assertMutableState(true, "[b, c [d, [e]]]"); assertMutableState(true, "({a: x, b: y, c: z})"); // Note: RegEx objects are not immutable, for instance, the exec // method maintains state for "global" searches. assertMutableState(true, "/abc/gi"); assertMutableState(false, "'a'"); assertMutableState(false, "0"); assertMutableState(false, "a + c"); assertMutableState(false, "'c' + a[0]"); assertMutableState(false, "a[0][1]"); assertMutableState(false, "'a' + c"); assertMutableState(false, "'a' + a.name"); assertMutableState(false, "1, 2, 3"); assertMutableState(false, "a, b, 3"); assertMutableState(true, "(function(a, b) { })"); assertMutableState(false, "a ? c : d"); assertMutableState(false, "'1' + navigator.userAgent"); assertMutableState(true, "new RegExp('foobar', 'i')"); assertMutableState(true, "new RegExp(SomethingWacky(), 'i')"); assertMutableState(true, "new Array()"); assertMutableState(true, "new Array"); assertMutableState(true, "new Array(4)"); assertMutableState(true, "new Array('a', 'b', 'c')"); assertMutableState(true, "new SomeClassINeverHeardOf()"); } public void testIsFunctionExpression() { assertContainsAnonFunc(true, "(function(){})"); assertContainsAnonFunc(true, "[function a(){}]"); assertContainsAnonFunc(false, "{x: function a(){}}"); assertContainsAnonFunc(true, "(function a(){})()"); assertContainsAnonFunc(true, "x = function a(){};"); assertContainsAnonFunc(true, "var x = function a(){};"); assertContainsAnonFunc(true, "if (function a(){});"); assertContainsAnonFunc(true, "while (function a(){});"); assertContainsAnonFunc(true, "do; while (function a(){});"); assertContainsAnonFunc(true, "for (function a(){};;);"); assertContainsAnonFunc(true, "for (;function a(){};);"); assertContainsAnonFunc(true, "for (;;function a(){});"); assertContainsAnonFunc(true, "for (p in function a(){});"); assertContainsAnonFunc(true, "with (function a(){}) {}"); assertContainsAnonFunc(false, "function a(){}"); assertContainsAnonFunc(false, "if (x) function a(){};"); assertContainsAnonFunc(false, "if (x) { function a(){} }"); assertContainsAnonFunc(false, "if (x); else function a(){};"); assertContainsAnonFunc(false, "while (x) function a(){};"); assertContainsAnonFunc(false, "do function a(){} while (0);"); assertContainsAnonFunc(false, "for (;;) function a(){}"); assertContainsAnonFunc(false, "for (p in o) function a(){};"); assertContainsAnonFunc(false, "with (x) function a(){}"); } public void testNewFunctionNode() { Node expected = parse("function foo(p1, p2, p3) { throw 2; }"); Node body = new Node(Token.BLOCK, new Node(Token.THROW, Node.newNumber(2))); List<Node> params = Lists.newArrayList(Node.newString(Token.NAME, "p1"), Node.newString(Token.NAME, "p2"), Node.newString(Token.NAME, "p3")); Node function = NodeUtil.newFunctionNode( "foo", params, body, -1, -1); Node actual = new Node(Token.SCRIPT); actual.addChildToFront(function); String difference = expected.checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } private void assertContainsAnonFunc(boolean expected, String js) { Node funcParent = findParentOfFuncDescendant(parse(js)); assertNotNull("Expected function node in parse tree of: " + js, funcParent); Node funcNode = getFuncChild(funcParent); assertEquals(expected, NodeUtil.isFunctionExpression(funcNode)); } private Node findParentOfFuncDescendant(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.getType() == Token.FUNCTION) { return n; } Node result = findParentOfFuncDescendant(c); if (result != null) { return result; } } return null; } private Node getFuncChild(Node n) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.getType() == Token.FUNCTION) { return c; } } return null; } public void testContainsType() { assertTrue(NodeUtil.containsType( parse("this"), Token.THIS)); assertTrue(NodeUtil.containsType( parse("function foo(){}(this)"), Token.THIS)); assertTrue(NodeUtil.containsType( parse("b?this:null"), Token.THIS)); assertFalse(NodeUtil.containsType( parse("a"), Token.THIS)); assertFalse(NodeUtil.containsType( parse("function foo(){}"), Token.THIS)); assertFalse(NodeUtil.containsType( parse("(b?foo():null)"), Token.THIS)); } public void testReferencesThis() { assertTrue(NodeUtil.referencesThis( parse("this"))); assertTrue(NodeUtil.referencesThis( parse("function foo(){}(this)"))); assertTrue(NodeUtil.referencesThis( parse("b?this:null"))); assertFalse(NodeUtil.referencesThis( parse("a"))); assertFalse(NodeUtil.referencesThis( parse("function foo(){}"))); assertFalse(NodeUtil.referencesThis( parse("(b?foo():null)"))); } public void testGetNodeTypeReferenceCount() { assertEquals(0, NodeUtil.getNodeTypeReferenceCount( parse("function foo(){}"), Token.THIS, Predicates.<Node>alwaysTrue())); assertEquals(1, NodeUtil.getNodeTypeReferenceCount( parse("this"), Token.THIS, Predicates.<Node>alwaysTrue())); assertEquals(2, NodeUtil.getNodeTypeReferenceCount( parse("this;function foo(){}(this)"), Token.THIS, Predicates.<Node>alwaysTrue())); } public void testIsNameReferenceCount() { assertTrue(NodeUtil.isNameReferenced( parse("function foo(){}"), "foo")); assertTrue(NodeUtil.isNameReferenced( parse("var foo = function(){}"), "foo")); assertFalse(NodeUtil.isNameReferenced( parse("function foo(){}"), "undefined")); assertTrue(NodeUtil.isNameReferenced( parse("undefined"), "undefined")); assertTrue(NodeUtil.isNameReferenced( parse("undefined;function foo(){}(undefined)"), "undefined")); assertTrue(NodeUtil.isNameReferenced( parse("goo.foo"), "goo")); assertFalse(NodeUtil.isNameReferenced( parse("goo.foo"), "foo")); } public void testGetNameReferenceCount() { assertEquals(0, NodeUtil.getNameReferenceCount( parse("function foo(){}"), "undefined")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("undefined"), "undefined")); assertEquals(2, NodeUtil.getNameReferenceCount( parse("undefined;function foo(){}(undefined)"), "undefined")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("goo.foo"), "goo")); assertEquals(0, NodeUtil.getNameReferenceCount( parse("goo.foo"), "foo")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("function foo(){}"), "foo")); assertEquals(1, NodeUtil.getNameReferenceCount( parse("var foo = function(){}"), "foo")); } public void testGetVarsDeclaredInBranch() { Compiler compiler = new Compiler(); assertNodeNames(Sets.newHashSet("foo"), NodeUtil.getVarsDeclaredInBranch( parse("var foo;"))); assertNodeNames(Sets.newHashSet("foo","goo"), NodeUtil.getVarsDeclaredInBranch( parse("var foo,goo;"))); assertNodeNames(Sets.<String>newHashSet(), NodeUtil.getVarsDeclaredInBranch( parse("foo();"))); assertNodeNames(Sets.<String>newHashSet(), NodeUtil.getVarsDeclaredInBranch( parse("function(){var foo;}"))); assertNodeNames(Sets.newHashSet("goo"), NodeUtil.getVarsDeclaredInBranch( parse("var goo;function(){var foo;}"))); } private void assertNodeNames(Set<String> nodeNames, Collection<Node> nodes) { Set<String> actualNames = Sets.newHashSet(); for (Node node : nodes) { actualNames.add(node.getString()); } assertEquals(nodeNames, actualNames); } public void testIsControlStructureCodeBlock() { Compiler compiler = new Compiler(); Node root = parse("if (x) foo(); else boo();"); Node ifNode = root.getFirstChild(); Node ifCondition = ifNode.getFirstChild(); Node ifCase = ifNode.getFirstChild().getNext(); Node elseCase = ifNode.getLastChild(); assertFalse(NodeUtil.isControlStructureCodeBlock(ifNode, ifCondition)); assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, ifCase)); assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, elseCase)); } public void testIsFunctionExpression1() { Compiler compiler = new Compiler(); Node root = parse("(function foo() {})"); Node StatementNode = root.getFirstChild(); assertTrue(NodeUtil.isExpressionNode(StatementNode)); Node functionNode = StatementNode.getFirstChild(); assertTrue(NodeUtil.isFunction(functionNode)); assertTrue(NodeUtil.isFunctionExpression(functionNode)); } public void testIsFunctionExpression2() { Compiler compiler = new Compiler(); Node root = parse("function foo() {}"); Node functionNode = root.getFirstChild(); assertTrue(NodeUtil.isFunction(functionNode)); assertFalse(NodeUtil.isFunctionExpression(functionNode)); } public void testRemoveTryChild() { Compiler compiler = new Compiler(); Node root = parse("try {foo()} catch(e) {} finally {}"); // Test removing the finally clause. Node actual = root.cloneTree(); Node tryNode = actual.getFirstChild(); Node tryBlock = tryNode.getFirstChild(); Node catchBlocks = tryNode.getFirstChild().getNext(); Node finallyBlock = tryNode.getLastChild(); NodeUtil.removeChild(tryNode, finallyBlock); String expected = "try {foo()} catch(e) {}"; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the try clause. actual = root.cloneTree(); tryNode = actual.getFirstChild(); tryBlock = tryNode.getFirstChild(); catchBlocks = tryNode.getFirstChild().getNext(); finallyBlock = tryNode.getLastChild(); NodeUtil.removeChild(tryNode, tryBlock); expected = "try {} catch(e) {} finally {}"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the catch clause. actual = root.cloneTree(); tryNode = actual.getFirstChild(); tryBlock = tryNode.getFirstChild(); catchBlocks = tryNode.getFirstChild().getNext(); Node catchBlock = catchBlocks.getFirstChild(); finallyBlock = tryNode.getLastChild(); NodeUtil.removeChild(catchBlocks, catchBlock); expected = "try {foo()} finally {}"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveVarChild() { Compiler compiler = new Compiler(); // Test removing the first child. Node actual = parse("var foo, goo, hoo"); Node varNode = actual.getFirstChild(); Node nameNode = varNode.getFirstChild(); NodeUtil.removeChild(varNode, nameNode); String expected = "var goo, hoo"; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the second child. actual = parse("var foo, goo, hoo"); varNode = actual.getFirstChild(); nameNode = varNode.getFirstChild().getNext(); NodeUtil.removeChild(varNode, nameNode); expected = "var foo, hoo"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the last child of several children. actual = parse("var foo, hoo"); varNode = actual.getFirstChild(); nameNode = varNode.getFirstChild().getNext(); NodeUtil.removeChild(varNode, nameNode); expected = "var foo"; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } // Test removing the last. actual = parse("var hoo"); varNode = actual.getFirstChild(); nameNode = varNode.getFirstChild(); NodeUtil.removeChild(varNode, nameNode); expected = ""; difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveLabelChild1() { Compiler compiler = new Compiler(); // Test removing the first child. Node actual = parse("foo: goo()"); Node labelNode = actual.getFirstChild(); Node callExpressNode = labelNode.getLastChild(); NodeUtil.removeChild(labelNode, callExpressNode); String expected = ""; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveLabelChild2() { // Test removing the first child. Node actual = parse("achoo: foo: goo()"); Node labelNode = actual.getFirstChild(); Node callExpressNode = labelNode.getLastChild(); NodeUtil.removeChild(labelNode, callExpressNode); String expected = ""; String difference = parse(expected).checkTreeEquals(actual); if (difference != null) { assertTrue("Nodes do not match:\n" + difference, false); } } public void testRemoveForChild() { Compiler compiler = new Compiler(); // Test removing the initializer. Node actual = parse("for(var a=0;a<0;a++)foo()"); Node forNode = actual.getFirstChild(); Node child = forNode.getFirstChild(); NodeUtil.removeChild(forNode, child); String expected = "for(;a<0;a++)foo()"; String difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the condition. actual = parse("for(var a=0;a<0;a++)foo()"); forNode = actual.getFirstChild(); child = forNode.getFirstChild().getNext(); NodeUtil.removeChild(forNode, child); expected = "for(var a=0;;a++)foo()"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the increment. actual = parse("for(var a=0;a<0;a++)foo()"); forNode = actual.getFirstChild(); child = forNode.getFirstChild().getNext().getNext(); NodeUtil.removeChild(forNode, child); expected = "for(var a=0;a<0;)foo()"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the body. actual = parse("for(var a=0;a<0;a++)foo()"); forNode = actual.getFirstChild(); child = forNode.getLastChild(); NodeUtil.removeChild(forNode, child); expected = "for(var a=0;a<0;a++);"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); // Test removing the body. actual = parse("for(a in ack)foo();"); forNode = actual.getFirstChild(); child = forNode.getLastChild(); NodeUtil.removeChild(forNode, child); expected = "for(a in ack);"; difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); } public void testMergeBlock1() { Compiler compiler = new Compiler(); // Test removing the initializer. Node actual = parse("{{a();b();}}"); Node parentBlock = actual.getFirstChild(); Node childBlock = parentBlock.getFirstChild(); assertTrue(NodeUtil.tryMergeBlock(childBlock)); String expected = "{a();b();}"; String difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); } public void testMergeBlock2() { Compiler compiler = new Compiler(); // Test removing the initializer. Node actual = parse("foo:{a();}"); Node parentLabel = actual.getFirstChild(); Node childBlock = parentLabel.getLastChild(); assertFalse(NodeUtil.tryMergeBlock(childBlock)); } public void testMergeBlock3() { Compiler compiler = new Compiler(); // Test removing the initializer. String code = "foo:{a();boo()}"; Node actual = parse("foo:{a();boo()}"); Node parentLabel = actual.getFirstChild(); Node childBlock = parentLabel.getLastChild(); assertFalse(NodeUtil.tryMergeBlock(childBlock)); String expected = code; String difference = parse(expected).checkTreeEquals(actual); assertNull("Nodes do not match:\n" + difference, difference); } public void testGetSourceName() { Node n = new Node(Token.BLOCK); Node parent = new Node(Token.BLOCK, n); parent.putProp(Node.SOURCENAME_PROP, "foo"); assertEquals("foo", NodeUtil.getSourceName(n)); } public void testIsLabelName() { Compiler compiler = new Compiler(); // Test removing the initializer. String code = "a:while(1) {a; continue a; break a; break;}"; Node actual = parse(code); Node labelNode = actual.getFirstChild(); assertTrue(labelNode.getType() == Token.LABEL); assertTrue(NodeUtil.isLabelName(labelNode.getFirstChild())); assertFalse(NodeUtil.isLabelName(labelNode.getLastChild())); Node whileNode = labelNode.getLastChild(); assertTrue(whileNode.getType() == Token.WHILE); Node whileBlock = whileNode.getLastChild(); assertTrue(whileBlock.getType() == Token.BLOCK); assertFalse(NodeUtil.isLabelName(whileBlock)); Node firstStatement = whileBlock.getFirstChild(); assertTrue(firstStatement.getType() == Token.EXPR_RESULT); Node variableReference = firstStatement.getFirstChild(); assertTrue(variableReference.getType() == Token.NAME); assertFalse(NodeUtil.isLabelName(variableReference)); Node continueStatement = firstStatement.getNext(); assertTrue(continueStatement.getType() == Token.CONTINUE); assertTrue(NodeUtil.isLabelName(continueStatement.getFirstChild())); Node firstBreak = continueStatement.getNext(); assertTrue(firstBreak.getType() == Token.BREAK); assertTrue(NodeUtil.isLabelName(firstBreak.getFirstChild())); Node secondBreak = firstBreak.getNext(); assertTrue(secondBreak.getType() == Token.BREAK); assertFalse(secondBreak.hasChildren()); assertFalse(NodeUtil.isLabelName(secondBreak.getFirstChild())); } public void testLocalValue1() throws Exception { // Names are not known to be local. assertFalse(testLocalValue("x")); assertFalse(testLocalValue("x()")); assertFalse(testLocalValue("this")); assertFalse(testLocalValue("arguments")); // We can't know if new objects are local unless we know // that they don't alias themselves. assertFalse(testLocalValue("new x()")); // property references are assume to be non-local assertFalse(testLocalValue("(new x()).y")); assertFalse(testLocalValue("(new x())['y']")); // Primitive values are local assertTrue(testLocalValue("null")); assertTrue(testLocalValue("undefined")); assertTrue(testLocalValue("Infinity")); assertTrue(testLocalValue("NaN")); assertTrue(testLocalValue("1")); assertTrue(testLocalValue("'a'")); assertTrue(testLocalValue("true")); assertTrue(testLocalValue("false")); assertTrue(testLocalValue("[]")); assertTrue(testLocalValue("{}")); // The contents of arrays and objects don't matter assertTrue(testLocalValue("[x]")); assertTrue(testLocalValue("{'a':x}")); // Pre-increment results in primitive number assertTrue(testLocalValue("++x")); assertTrue(testLocalValue("--x")); // Post-increment, the previous value matters. assertFalse(testLocalValue("x++")); assertFalse(testLocalValue("x--")); // The left side of an only assign matters if it is an alias or mutable. assertTrue(testLocalValue("x=1")); assertFalse(testLocalValue("x=[]")); assertFalse(testLocalValue("x=y")); // The right hand side of assignment opts don't matter, as they force // a local result. assertTrue(testLocalValue("x+=y")); assertTrue(testLocalValue("x*=y")); // Comparisons always result in locals, as they force a local boolean // result. assertTrue(testLocalValue("x==y")); assertTrue(testLocalValue("x!=y")); assertTrue(testLocalValue("x>y")); // Only the right side of a comma matters assertTrue(testLocalValue("(1,2)")); assertTrue(testLocalValue("(x,1)")); assertFalse(testLocalValue("(x,y)")); // Both the operands of OR matter assertTrue(testLocalValue("1||2")); assertFalse(testLocalValue("x||1")); assertFalse(testLocalValue("x||y")); assertFalse(testLocalValue("1||y")); // Both the operands of AND matter assertTrue(testLocalValue("1&&2")); assertFalse(testLocalValue("x&&1")); assertFalse(testLocalValue("x&&y")); assertFalse(testLocalValue("1&&y")); // Only the results of HOOK matter assertTrue(testLocalValue("x?1:2")); assertFalse(testLocalValue("x?x:2")); assertFalse(testLocalValue("x?1:x")); assertFalse(testLocalValue("x?x:y")); // Results of ops are local values assertTrue(testLocalValue("!y")); assertTrue(testLocalValue("~y")); assertTrue(testLocalValue("y + 1")); assertTrue(testLocalValue("y + z")); assertTrue(testLocalValue("y * z")); assertTrue(testLocalValue("'a' in x")); assertTrue(testLocalValue("typeof x")); assertTrue(testLocalValue("x instanceof y")); assertTrue(testLocalValue("void x")); assertTrue(testLocalValue("void 0")); assertFalse(testLocalValue("{}.x")); assertTrue(testLocalValue("{}.toString()")); assertTrue(testLocalValue("o.toString()")); assertFalse(testLocalValue("o.valueOf()")); } private boolean testLocalValue(String js) { Node script = parse("var test = " + js +";"); Preconditions.checkState(script.getType() == Token.SCRIPT); Node var = script.getFirstChild(); Preconditions.checkState(var.getType() == Token.VAR); Node name = var.getFirstChild(); Preconditions.checkState(name.getType() == Token.NAME); Node value = name.getFirstChild(); return NodeUtil.evaluatesToLocalValue(value); } public void testValidDefine() { assertTrue(testValidDefineValue("1")); assertTrue(testValidDefineValue("-3")); assertTrue(testValidDefineValue("true")); assertTrue(testValidDefineValue("false")); assertTrue(testValidDefineValue("'foo'")); assertFalse(testValidDefineValue("x")); assertFalse(testValidDefineValue("null")); assertFalse(testValidDefineValue("undefined")); assertFalse(testValidDefineValue("NaN")); assertTrue(testValidDefineValue("!true")); assertTrue(testValidDefineValue("-true")); assertTrue(testValidDefineValue("1 & 8")); assertTrue(testValidDefineValue("1 + 8")); assertTrue(testValidDefineValue("'a' + 'b'")); assertFalse(testValidDefineValue("1 & foo")); } private boolean testValidDefineValue(String js) { Node script = parse("var test = " + js +";"); Node var = script.getFirstChild(); Node name = var.getFirstChild(); Node value = name.getFirstChild(); ImmutableSet<String> defines = ImmutableSet.of(); return NodeUtil.isValidDefineValue(value, defines); } }
@Test public void shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch() throws Exception { //given mock.varargs(); Invocation invocation = getLastInvocation(); //when InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new LocalizedMatcher(AnyVararg.ANY_VARARG))); //then invocationMatcher.captureArgumentsFrom(invocation); }
org.mockito.internal.invocation.InvocationMatcherTest::shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch
test/org/mockito/internal/invocation/InvocationMatcherTest.java
152
test/org/mockito/internal/invocation/InvocationMatcherTest.java
shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.invocation; import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.internal.matchers.*; import org.mockito.internal.reporting.PrintingFriendlyInvocation; import org.mockitousage.IMethods; import static org.mockito.Matchers.anyVararg; import static org.mockitoutil.ExtraMatchers.hasExactlyInOrder; import org.mockitoutil.TestBase; import java.lang.reflect.Method; import static java.util.Arrays.asList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings("unchecked") public class InvocationMatcherTest extends TestBase { private InvocationMatcher simpleMethod; @Mock private IMethods mock; @Before public void setup() { simpleMethod = new InvocationBuilder().mock(mock).simpleMethod().toInvocationMatcher(); } @Test public void shouldBeACitizenOfHashes() throws Exception { Invocation invocation = new InvocationBuilder().toInvocation(); Invocation invocationTwo = new InvocationBuilder().args("blah").toInvocation(); Map map = new HashMap(); map.put(new InvocationMatcher(invocation), "one"); map.put(new InvocationMatcher(invocationTwo), "two"); assertEquals(2, map.size()); } @Test public void shouldNotEqualIfNumberOfArgumentsDiffer() throws Exception { PrintingFriendlyInvocation withOneArg = new InvocationMatcher(new InvocationBuilder().args("test").toInvocation()); PrintingFriendlyInvocation withTwoArgs = new InvocationMatcher(new InvocationBuilder().args("test", 100).toInvocation()); assertFalse(withOneArg.equals(null)); assertFalse(withOneArg.equals(withTwoArgs)); } @Test public void shouldToStringWithMatchers() throws Exception { Matcher m = NotNull.NOT_NULL; InvocationMatcher notNull = new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(m)); Matcher mTwo = new Equals('x'); InvocationMatcher equals = new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(mTwo)); assertContains("simpleMethod(notNull())", notNull.toString()); assertContains("simpleMethod('x')", equals.toString()); } @Test public void shouldKnowIfIsSimilarTo() throws Exception { Invocation same = new InvocationBuilder().mock(mock).simpleMethod().toInvocation(); assertTrue(simpleMethod.hasSimilarMethod(same)); Invocation different = new InvocationBuilder().mock(mock).differentMethod().toInvocation(); assertFalse(simpleMethod.hasSimilarMethod(different)); } @Test public void shouldNotBeSimilarToVerifiedInvocation() throws Exception { Invocation verified = new InvocationBuilder().simpleMethod().verified().toInvocation(); assertFalse(simpleMethod.hasSimilarMethod(verified)); } @Test public void shouldNotBeSimilarIfMocksAreDifferent() throws Exception { Invocation onDifferentMock = new InvocationBuilder().simpleMethod().mock("different mock").toInvocation(); assertFalse(simpleMethod.hasSimilarMethod(onDifferentMock)); } @Test public void shouldNotBeSimilarIfIsOverloadedButUsedWithTheSameArg() throws Exception { Method method = IMethods.class.getMethod("simpleMethod", String.class); Method overloadedMethod = IMethods.class.getMethod("simpleMethod", Object.class); String sameArg = "test"; InvocationMatcher invocation = new InvocationBuilder().method(method).arg(sameArg).toInvocationMatcher(); Invocation overloadedInvocation = new InvocationBuilder().method(overloadedMethod).arg(sameArg).toInvocation(); assertFalse(invocation.hasSimilarMethod(overloadedInvocation)); } @Test public void shouldBeSimilarIfIsOverloadedButUsedWithDifferentArg() throws Exception { Method method = IMethods.class.getMethod("simpleMethod", String.class); Method overloadedMethod = IMethods.class.getMethod("simpleMethod", Object.class); InvocationMatcher invocation = new InvocationBuilder().mock(mock).method(method).arg("foo").toInvocationMatcher(); Invocation overloadedInvocation = new InvocationBuilder().mock(mock).method(overloadedMethod).arg("bar").toInvocation(); assertTrue(invocation.hasSimilarMethod(overloadedInvocation)); } @Test public void shouldCaptureArgumentsFromInvocation() throws Exception { //given Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation(); CapturingMatcher capturingMatcher = new CapturingMatcher(); InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("1"), capturingMatcher)); //when invocationMatcher.captureArgumentsFrom(invocation); //then assertEquals(1, capturingMatcher.getAllValues().size()); assertEquals(100, capturingMatcher.getLastValue()); } @Test public void shouldMatchVarargsUsingAnyVarargs() throws Exception { //given mock.varargs("1", "2"); Invocation invocation = getLastInvocation(); InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(AnyVararg.ANY_VARARG)); //when boolean match = invocationMatcher.matches(invocation); //then assertTrue(match); } @Test public void shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch() throws Exception { //given mock.varargs(); Invocation invocation = getLastInvocation(); //when InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new LocalizedMatcher(AnyVararg.ANY_VARARG))); //then invocationMatcher.captureArgumentsFrom(invocation); } }
// You are a professional Java test case writer, please create a test case named `shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch` for the issue `Mockito-157`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-157 // // ## Issue-Title: // Source files should not be put in binary JAR // // ## Issue-Description: // Source files (`*.java`) should not be put into binary `mockito-core.jar`. It stupefies Idea to show decompiled file even when source jar is available. // // // // @Test public void shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch() throws Exception {
152
34
141
test/org/mockito/internal/invocation/InvocationMatcherTest.java
test
```markdown ## Issue-ID: Mockito-157 ## Issue-Title: Source files should not be put in binary JAR ## Issue-Description: Source files (`*.java`) should not be put into binary `mockito-core.jar`. It stupefies Idea to show decompiled file even when source jar is available. ``` You are a professional Java test case writer, please create a test case named `shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch` for the issue `Mockito-157`, utilizing the provided issue report information and the following function signature. ```java @Test public void shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch() throws Exception { ```
141
[ "org.mockito.internal.invocation.InvocationMatcher" ]
ff5d5673d84afa7e81c05657887fc762368c350c5675cfa3c920c1d6ba1335a2
@Test public void shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch() throws Exception
// You are a professional Java test case writer, please create a test case named `shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch` for the issue `Mockito-157`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-157 // // ## Issue-Title: // Source files should not be put in binary JAR // // ## Issue-Description: // Source files (`*.java`) should not be put into binary `mockito-core.jar`. It stupefies Idea to show decompiled file even when source jar is available. // // // //
Mockito
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.invocation; import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.internal.matchers.*; import org.mockito.internal.reporting.PrintingFriendlyInvocation; import org.mockitousage.IMethods; import static org.mockito.Matchers.anyVararg; import static org.mockitoutil.ExtraMatchers.hasExactlyInOrder; import org.mockitoutil.TestBase; import java.lang.reflect.Method; import static java.util.Arrays.asList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings("unchecked") public class InvocationMatcherTest extends TestBase { private InvocationMatcher simpleMethod; @Mock private IMethods mock; @Before public void setup() { simpleMethod = new InvocationBuilder().mock(mock).simpleMethod().toInvocationMatcher(); } @Test public void shouldBeACitizenOfHashes() throws Exception { Invocation invocation = new InvocationBuilder().toInvocation(); Invocation invocationTwo = new InvocationBuilder().args("blah").toInvocation(); Map map = new HashMap(); map.put(new InvocationMatcher(invocation), "one"); map.put(new InvocationMatcher(invocationTwo), "two"); assertEquals(2, map.size()); } @Test public void shouldNotEqualIfNumberOfArgumentsDiffer() throws Exception { PrintingFriendlyInvocation withOneArg = new InvocationMatcher(new InvocationBuilder().args("test").toInvocation()); PrintingFriendlyInvocation withTwoArgs = new InvocationMatcher(new InvocationBuilder().args("test", 100).toInvocation()); assertFalse(withOneArg.equals(null)); assertFalse(withOneArg.equals(withTwoArgs)); } @Test public void shouldToStringWithMatchers() throws Exception { Matcher m = NotNull.NOT_NULL; InvocationMatcher notNull = new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(m)); Matcher mTwo = new Equals('x'); InvocationMatcher equals = new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(mTwo)); assertContains("simpleMethod(notNull())", notNull.toString()); assertContains("simpleMethod('x')", equals.toString()); } @Test public void shouldKnowIfIsSimilarTo() throws Exception { Invocation same = new InvocationBuilder().mock(mock).simpleMethod().toInvocation(); assertTrue(simpleMethod.hasSimilarMethod(same)); Invocation different = new InvocationBuilder().mock(mock).differentMethod().toInvocation(); assertFalse(simpleMethod.hasSimilarMethod(different)); } @Test public void shouldNotBeSimilarToVerifiedInvocation() throws Exception { Invocation verified = new InvocationBuilder().simpleMethod().verified().toInvocation(); assertFalse(simpleMethod.hasSimilarMethod(verified)); } @Test public void shouldNotBeSimilarIfMocksAreDifferent() throws Exception { Invocation onDifferentMock = new InvocationBuilder().simpleMethod().mock("different mock").toInvocation(); assertFalse(simpleMethod.hasSimilarMethod(onDifferentMock)); } @Test public void shouldNotBeSimilarIfIsOverloadedButUsedWithTheSameArg() throws Exception { Method method = IMethods.class.getMethod("simpleMethod", String.class); Method overloadedMethod = IMethods.class.getMethod("simpleMethod", Object.class); String sameArg = "test"; InvocationMatcher invocation = new InvocationBuilder().method(method).arg(sameArg).toInvocationMatcher(); Invocation overloadedInvocation = new InvocationBuilder().method(overloadedMethod).arg(sameArg).toInvocation(); assertFalse(invocation.hasSimilarMethod(overloadedInvocation)); } @Test public void shouldBeSimilarIfIsOverloadedButUsedWithDifferentArg() throws Exception { Method method = IMethods.class.getMethod("simpleMethod", String.class); Method overloadedMethod = IMethods.class.getMethod("simpleMethod", Object.class); InvocationMatcher invocation = new InvocationBuilder().mock(mock).method(method).arg("foo").toInvocationMatcher(); Invocation overloadedInvocation = new InvocationBuilder().mock(mock).method(overloadedMethod).arg("bar").toInvocation(); assertTrue(invocation.hasSimilarMethod(overloadedInvocation)); } @Test public void shouldCaptureArgumentsFromInvocation() throws Exception { //given Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation(); CapturingMatcher capturingMatcher = new CapturingMatcher(); InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("1"), capturingMatcher)); //when invocationMatcher.captureArgumentsFrom(invocation); //then assertEquals(1, capturingMatcher.getAllValues().size()); assertEquals(100, capturingMatcher.getLastValue()); } @Test public void shouldMatchVarargsUsingAnyVarargs() throws Exception { //given mock.varargs("1", "2"); Invocation invocation = getLastInvocation(); InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(AnyVararg.ANY_VARARG)); //when boolean match = invocationMatcher.matches(invocation); //then assertTrue(match); } @Test public void shouldMatchCaptureArgumentsWhenArgsCountDoesNOTMatch() throws Exception { //given mock.varargs(); Invocation invocation = getLastInvocation(); //when InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new LocalizedMatcher(AnyVararg.ANY_VARARG))); //then invocationMatcher.captureArgumentsFrom(invocation); } }