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
@SuppressWarnings("resource") public void testNotAllowMultipleMatches() throws Exception { String jsonString = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'value':4,'b':true}"); JsonParser p0 = JSON_F.createParser(jsonString); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), false, // includePath false // multipleMatches -false ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("3"), result); }
com.fasterxml.jackson.core.filter.BasicParserFilteringTest::testNotAllowMultipleMatches
src/test/java/com/fasterxml/jackson/core/filter/BasicParserFilteringTest.java
118
src/test/java/com/fasterxml/jackson/core/filter/BasicParserFilteringTest.java
testNotAllowMultipleMatches
package com.fasterxml.jackson.core.filter; import java.util.*; import com.fasterxml.jackson.core.*; public class BasicParserFilteringTest extends BaseTest { static class NameMatchFilter extends TokenFilter { private final Set<String> _names; public NameMatchFilter(String... names) { _names = new HashSet<String>(Arrays.asList(names)); } @Override public TokenFilter includeElement(int index) { return this; } @Override public TokenFilter includeProperty(String name) { if (_names.contains(name)) { return TokenFilter.INCLUDE_ALL; } return this; } @Override protected boolean _includeScalar() { return false; } } static class IndexMatchFilter extends TokenFilter { private final BitSet _indices; public IndexMatchFilter(int... ixs) { _indices = new BitSet(); for (int ix : ixs) { _indices.set(ix); } } @Override public TokenFilter includeProperty(String name) { return this; } @Override public TokenFilter includeElement(int index) { if (_indices.get(index)) { return TokenFilter.INCLUDE_ALL; } return null; } @Override protected boolean _includeScalar() { return false; } } /* /********************************************************** /* Test methods /********************************************************** */ private final JsonFactory JSON_F = new JsonFactory(); private final String SIMPLE = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"); @SuppressWarnings("resource") public void testNonFiltering() throws Exception { JsonParser p = JSON_F.createParser(SIMPLE); String result = readAndWrite(JSON_F, p); assertEquals(SIMPLE, result); } @SuppressWarnings("resource") public void testSingleMatchFilteringWithoutPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), false, // includePath false // multipleMatches ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("3"), result); } @SuppressWarnings("resource") public void testSingleMatchFilteringWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); } @SuppressWarnings("resource") public void testNotAllowMultipleMatches() throws Exception { String jsonString = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'value':4,'b':true}"); JsonParser p0 = JSON_F.createParser(jsonString); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), false, // includePath false // multipleMatches -false ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("3"), result); } @SuppressWarnings("resource") public void testAllowMultipleMatches() throws Exception { String jsonString = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'value':4,'b':true}"); JsonParser p0 = JSON_F.createParser(jsonString); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), false, // includePath true // multipleMatches - true ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("3 4"), result); } @SuppressWarnings("resource") public void testMultipleMatchFilteringWithPath1() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value0", "value2"), true, /* includePath */ true /* multipleMatches */ ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value0':2,'value2':4}}"), result); } @SuppressWarnings("resource") public void testMultipleMatchFilteringWithPath2() throws Exception { String INPUT = aposToQuotes("{'a':123,'ob':{'value0':2,'value':3,'value2':4},'b':true}"); JsonParser p0 = JSON_F.createParser(INPUT); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("b", "value"), true, true); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value':3},'b':true}"), result); } @SuppressWarnings("resource") public void testMultipleMatchFilteringWithPath3() throws Exception { final String JSON = aposToQuotes("{'root':{'a0':true,'a':{'value':3},'b':{'value':4}},'b0':false}"); JsonParser p0 = JSON_F.createParser(JSON); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, true); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'root':{'a':{'value':3},'b':{'value':4}}}"), result); } @SuppressWarnings("resource") public void testIndexMatchWithPath1() throws Exception { JsonParser p = new FilteringParserDelegate(JSON_F.createParser(SIMPLE), new IndexMatchFilter(1), true, true); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'array':[2]}"), result); p = new FilteringParserDelegate(JSON_F.createParser(SIMPLE), new IndexMatchFilter(0), true, true); result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'array':[1]}"), result); } @SuppressWarnings("resource") public void testIndexMatchWithPath2() throws Exception { JsonParser p = new FilteringParserDelegate(JSON_F.createParser(SIMPLE), new IndexMatchFilter(0, 1), true, true); assertEquals(aposToQuotes("{'array':[1,2]}"), readAndWrite(JSON_F, p)); String JSON = aposToQuotes("{'a':123,'array':[1,2,3,4,5],'b':[1,2,3]}"); p = new FilteringParserDelegate(JSON_F.createParser(JSON), new IndexMatchFilter(1, 3), true, true); assertEquals(aposToQuotes("{'array':[2,4],'b':[2]}"), readAndWrite(JSON_F, p)); } }
// You are a professional Java test case writer, please create a test case named `testNotAllowMultipleMatches` for the issue `JacksonCore-209`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-209 // // ## Issue-Title: // Make use of _allowMultipleMatches in FilteringParserDelegate // // ## Issue-Description: // Currently, it looks like that the \_allowMultipleMatches attribute in FilteringGeneratorDelegate is not utilised (i.e. no value is assigned to this variable). Re. the documentation this attribute offers some useful functionality. So it would be nice, if it could be implemented properly. See <https://groups.google.com/d/msg/jackson-user/VzZ94G9hvrs/JGFozl6lCQAJ> // // // // @SuppressWarnings("resource") public void testNotAllowMultipleMatches() throws Exception {
118
15
106
src/test/java/com/fasterxml/jackson/core/filter/BasicParserFilteringTest.java
src/test/java
```markdown ## Issue-ID: JacksonCore-209 ## Issue-Title: Make use of _allowMultipleMatches in FilteringParserDelegate ## Issue-Description: Currently, it looks like that the \_allowMultipleMatches attribute in FilteringGeneratorDelegate is not utilised (i.e. no value is assigned to this variable). Re. the documentation this attribute offers some useful functionality. So it would be nice, if it could be implemented properly. See <https://groups.google.com/d/msg/jackson-user/VzZ94G9hvrs/JGFozl6lCQAJ> ``` You are a professional Java test case writer, please create a test case named `testNotAllowMultipleMatches` for the issue `JacksonCore-209`, utilizing the provided issue report information and the following function signature. ```java @SuppressWarnings("resource") public void testNotAllowMultipleMatches() throws Exception { ```
106
[ "com.fasterxml.jackson.core.filter.FilteringParserDelegate" ]
a65cd145b90cf23d816237364328915c432bddd63059d5f21464aa24207a3823
@SuppressWarnings("resource") public void testNotAllowMultipleMatches() throws Exception
// You are a professional Java test case writer, please create a test case named `testNotAllowMultipleMatches` for the issue `JacksonCore-209`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-209 // // ## Issue-Title: // Make use of _allowMultipleMatches in FilteringParserDelegate // // ## Issue-Description: // Currently, it looks like that the \_allowMultipleMatches attribute in FilteringGeneratorDelegate is not utilised (i.e. no value is assigned to this variable). Re. the documentation this attribute offers some useful functionality. So it would be nice, if it could be implemented properly. See <https://groups.google.com/d/msg/jackson-user/VzZ94G9hvrs/JGFozl6lCQAJ> // // // //
JacksonCore
package com.fasterxml.jackson.core.filter; import java.util.*; import com.fasterxml.jackson.core.*; public class BasicParserFilteringTest extends BaseTest { static class NameMatchFilter extends TokenFilter { private final Set<String> _names; public NameMatchFilter(String... names) { _names = new HashSet<String>(Arrays.asList(names)); } @Override public TokenFilter includeElement(int index) { return this; } @Override public TokenFilter includeProperty(String name) { if (_names.contains(name)) { return TokenFilter.INCLUDE_ALL; } return this; } @Override protected boolean _includeScalar() { return false; } } static class IndexMatchFilter extends TokenFilter { private final BitSet _indices; public IndexMatchFilter(int... ixs) { _indices = new BitSet(); for (int ix : ixs) { _indices.set(ix); } } @Override public TokenFilter includeProperty(String name) { return this; } @Override public TokenFilter includeElement(int index) { if (_indices.get(index)) { return TokenFilter.INCLUDE_ALL; } return null; } @Override protected boolean _includeScalar() { return false; } } /* /********************************************************** /* Test methods /********************************************************** */ private final JsonFactory JSON_F = new JsonFactory(); private final String SIMPLE = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"); @SuppressWarnings("resource") public void testNonFiltering() throws Exception { JsonParser p = JSON_F.createParser(SIMPLE); String result = readAndWrite(JSON_F, p); assertEquals(SIMPLE, result); } @SuppressWarnings("resource") public void testSingleMatchFilteringWithoutPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), false, // includePath false // multipleMatches ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("3"), result); } @SuppressWarnings("resource") public void testSingleMatchFilteringWithPath() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, // includePath false // multipleMatches ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value':3}}"), result); } @SuppressWarnings("resource") public void testNotAllowMultipleMatches() throws Exception { String jsonString = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'value':4,'b':true}"); JsonParser p0 = JSON_F.createParser(jsonString); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), false, // includePath false // multipleMatches -false ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("3"), result); } @SuppressWarnings("resource") public void testAllowMultipleMatches() throws Exception { String jsonString = aposToQuotes("{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'value':4,'b':true}"); JsonParser p0 = JSON_F.createParser(jsonString); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), false, // includePath true // multipleMatches - true ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("3 4"), result); } @SuppressWarnings("resource") public void testMultipleMatchFilteringWithPath1() throws Exception { JsonParser p0 = JSON_F.createParser(SIMPLE); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value0", "value2"), true, /* includePath */ true /* multipleMatches */ ); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value0':2,'value2':4}}"), result); } @SuppressWarnings("resource") public void testMultipleMatchFilteringWithPath2() throws Exception { String INPUT = aposToQuotes("{'a':123,'ob':{'value0':2,'value':3,'value2':4},'b':true}"); JsonParser p0 = JSON_F.createParser(INPUT); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("b", "value"), true, true); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'ob':{'value':3},'b':true}"), result); } @SuppressWarnings("resource") public void testMultipleMatchFilteringWithPath3() throws Exception { final String JSON = aposToQuotes("{'root':{'a0':true,'a':{'value':3},'b':{'value':4}},'b0':false}"); JsonParser p0 = JSON_F.createParser(JSON); JsonParser p = new FilteringParserDelegate(p0, new NameMatchFilter("value"), true, true); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'root':{'a':{'value':3},'b':{'value':4}}}"), result); } @SuppressWarnings("resource") public void testIndexMatchWithPath1() throws Exception { JsonParser p = new FilteringParserDelegate(JSON_F.createParser(SIMPLE), new IndexMatchFilter(1), true, true); String result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'array':[2]}"), result); p = new FilteringParserDelegate(JSON_F.createParser(SIMPLE), new IndexMatchFilter(0), true, true); result = readAndWrite(JSON_F, p); assertEquals(aposToQuotes("{'array':[1]}"), result); } @SuppressWarnings("resource") public void testIndexMatchWithPath2() throws Exception { JsonParser p = new FilteringParserDelegate(JSON_F.createParser(SIMPLE), new IndexMatchFilter(0, 1), true, true); assertEquals(aposToQuotes("{'array':[1,2]}"), readAndWrite(JSON_F, p)); String JSON = aposToQuotes("{'a':123,'array':[1,2,3,4,5],'b':[1,2,3]}"); p = new FilteringParserDelegate(JSON_F.createParser(JSON), new IndexMatchFilter(1, 3), true, true); assertEquals(aposToQuotes("{'array':[2,4],'b':[2]}"), readAndWrite(JSON_F, p)); } }
public void testExcessDataInZip64ExtraField() throws Exception { File archive = getFile("COMPRESS-228.zip"); zf = new ZipFile(archive); // actually, if we get here, the test already has passed ZipArchiveEntry ze = zf.getEntry("src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java"); assertEquals(26101, ze.getSize()); }
org.apache.commons.compress.archivers.zip.ZipFileTest::testExcessDataInZip64ExtraField
src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
238
src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
testExcessDataInZip64ExtraField
/* * 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 static org.apache.commons.compress.AbstractTestCase.getFile; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.TreeMap; import java.util.zip.ZipEntry; import junit.framework.TestCase; public class ZipFileTest extends TestCase { private ZipFile zf = null; @Override public void tearDown() { ZipFile.closeQuietly(zf); } public void testCDOrder() throws Exception { readOrderTest(); ArrayList<ZipArchiveEntry> l = Collections.list(zf.getEntries()); assertEntryName(l, 0, "AbstractUnicodeExtraField"); assertEntryName(l, 1, "AsiExtraField"); assertEntryName(l, 2, "ExtraFieldUtils"); assertEntryName(l, 3, "FallbackZipEncoding"); assertEntryName(l, 4, "GeneralPurposeBit"); assertEntryName(l, 5, "JarMarker"); assertEntryName(l, 6, "NioZipEncoding"); assertEntryName(l, 7, "Simple8BitZipEncoding"); assertEntryName(l, 8, "UnicodeCommentExtraField"); assertEntryName(l, 9, "UnicodePathExtraField"); assertEntryName(l, 10, "UnixStat"); assertEntryName(l, 11, "UnparseableExtraFieldData"); assertEntryName(l, 12, "UnrecognizedExtraField"); assertEntryName(l, 13, "ZipArchiveEntry"); assertEntryName(l, 14, "ZipArchiveInputStream"); assertEntryName(l, 15, "ZipArchiveOutputStream"); assertEntryName(l, 16, "ZipEncoding"); assertEntryName(l, 17, "ZipEncodingHelper"); assertEntryName(l, 18, "ZipExtraField"); assertEntryName(l, 19, "ZipUtil"); assertEntryName(l, 20, "ZipLong"); assertEntryName(l, 21, "ZipShort"); assertEntryName(l, 22, "ZipFile"); } public void testPhysicalOrder() throws Exception { readOrderTest(); ArrayList<ZipArchiveEntry> l = Collections.list(zf.getEntriesInPhysicalOrder()); assertEntryName(l, 0, "AbstractUnicodeExtraField"); assertEntryName(l, 1, "AsiExtraField"); assertEntryName(l, 2, "ExtraFieldUtils"); assertEntryName(l, 3, "FallbackZipEncoding"); assertEntryName(l, 4, "GeneralPurposeBit"); assertEntryName(l, 5, "JarMarker"); assertEntryName(l, 6, "NioZipEncoding"); assertEntryName(l, 7, "Simple8BitZipEncoding"); assertEntryName(l, 8, "UnicodeCommentExtraField"); assertEntryName(l, 9, "UnicodePathExtraField"); assertEntryName(l, 10, "UnixStat"); assertEntryName(l, 11, "UnparseableExtraFieldData"); assertEntryName(l, 12, "UnrecognizedExtraField"); assertEntryName(l, 13, "ZipArchiveEntry"); assertEntryName(l, 14, "ZipArchiveInputStream"); assertEntryName(l, 15, "ZipArchiveOutputStream"); assertEntryName(l, 16, "ZipEncoding"); assertEntryName(l, 17, "ZipEncodingHelper"); assertEntryName(l, 18, "ZipExtraField"); assertEntryName(l, 19, "ZipFile"); assertEntryName(l, 20, "ZipLong"); assertEntryName(l, 21, "ZipShort"); assertEntryName(l, 22, "ZipUtil"); } public void testDoubleClose() throws Exception { readOrderTest(); zf.close(); try { zf.close(); } catch (Exception ex) { fail("Caught exception of second close"); } } public void testReadingOfStoredEntry() throws Exception { File f = File.createTempFile("commons-compress-zipfiletest", ".zip"); f.deleteOnExit(); OutputStream o = null; InputStream i = null; try { o = new FileOutputStream(f); ZipArchiveOutputStream zo = new ZipArchiveOutputStream(o); ZipArchiveEntry ze = new ZipArchiveEntry("foo"); ze.setMethod(ZipEntry.STORED); ze.setSize(4); ze.setCrc(0xb63cfbcdl); zo.putArchiveEntry(ze); zo.write(new byte[] { 1, 2, 3, 4 }); zo.closeArchiveEntry(); zo.close(); o.close(); o = null; zf = new ZipFile(f); ze = zf.getEntry("foo"); assertNotNull(ze); i = zf.getInputStream(ze); byte[] b = new byte[4]; assertEquals(4, i.read(b)); assertEquals(-1, i.read()); } finally { if (o != null) { o.close(); } if (i != null) { i.close(); } f.delete(); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-176" */ public void testWinzipBackSlashWorkaround() throws Exception { File archive = getFile("test-winzip.zip"); zf = new ZipFile(archive); assertNull(zf.getEntry("\u00e4\\\u00fc.txt")); assertNotNull(zf.getEntry("\u00e4/\u00fc.txt")); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-208" * >COMPRESS-208</a>. */ public void testSkipsPK00Prefix() throws Exception { File archive = getFile("COMPRESS-208.zip"); zf = new ZipFile(archive); assertNotNull(zf.getEntry("test1.xml")); assertNotNull(zf.getEntry("test2.xml")); } public void testUnixSymlinkSampleFile() throws Exception { final String entryPrefix = "COMPRESS-214_unix_symlinks/"; final TreeMap<String, String> expectedVals = new TreeMap<String, String>(); // I threw in some Japanese characters to keep things interesting. expectedVals.put(entryPrefix + "link1", "../COMPRESS-214_unix_symlinks/./a/b/c/../../../\uF999"); expectedVals.put(entryPrefix + "link2", "../COMPRESS-214_unix_symlinks/./a/b/c/../../../g"); expectedVals.put(entryPrefix + "link3", "../COMPRESS-214_unix_symlinks/././a/b/c/../../../\u76F4\u6A39"); expectedVals.put(entryPrefix + "link4", "\u82B1\u5B50/\u745B\u5B50"); expectedVals.put(entryPrefix + "\uF999", "./\u82B1\u5B50/\u745B\u5B50/\u5897\u8C37/\uF999"); expectedVals.put(entryPrefix + "g", "./a/b/c/d/e/f/g"); expectedVals.put(entryPrefix + "\u76F4\u6A39", "./g"); // Notice how a directory link might contain a trailing slash, or it might not. // Also note: symlinks are always stored as files, even if they link to directories. expectedVals.put(entryPrefix + "link5", "../COMPRESS-214_unix_symlinks/././a/b"); expectedVals.put(entryPrefix + "link6", "../COMPRESS-214_unix_symlinks/././a/b/"); // I looked into creating a test with hard links, but zip does not appear to // support hard links, so nevermind. File archive = getFile("COMPRESS-214_unix_symlinks.zip"); zf = new ZipFile(archive); Enumeration<ZipArchiveEntry> en = zf.getEntries(); while (en.hasMoreElements()) { ZipArchiveEntry zae = en.nextElement(); String link = zf.getUnixSymlink(zae); if (zae.isUnixSymlink()) { String name = zae.getName(); String expected = expectedVals.get(name); assertEquals(expected, link); } else { // Should be null if it's not a symlink! assertNull(link); } } } /** * @see https://issues.apache.org/jira/browse/COMPRESS-227 */ public void testDuplicateEntry() throws Exception { File archive = getFile("COMPRESS-227.zip"); zf = new ZipFile(archive); ZipArchiveEntry ze = zf.getEntry("test1.txt"); assertNotNull(ze); assertNotNull(zf.getInputStream(ze)); int numberOfEntries = 0; for (Iterator<ZipArchiveEntry> it = zf.getEntries("test1.txt"); it.hasNext(); ) { numberOfEntries++; ze = it.next(); assertNotNull(zf.getInputStream(ze)); } assertEquals(2, numberOfEntries); } /** * @see https://issues.apache.org/jira/browse/COMPRESS-228 */ public void testExcessDataInZip64ExtraField() throws Exception { File archive = getFile("COMPRESS-228.zip"); zf = new ZipFile(archive); // actually, if we get here, the test already has passed ZipArchiveEntry ze = zf.getEntry("src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java"); assertEquals(26101, ze.getSize()); } /* * ordertest.zip has been handcrafted. * * It contains enough files so any random coincidence of * entries.keySet() and central directory order would be unlikely * - in fact testCDOrder fails in svn revision 920284. * * The central directory has ZipFile and ZipUtil swapped so * central directory order is different from entry data order. */ private void readOrderTest() throws Exception { File archive = getFile("ordertest.zip"); zf = new ZipFile(archive); } private static void assertEntryName(ArrayList<ZipArchiveEntry> entries, int index, String expectedName) { ZipArchiveEntry ze = entries.get(index); assertEquals("src/main/java/org/apache/commons/compress/archivers/zip/" + expectedName + ".java", ze.getName()); } }
// You are a professional Java test case writer, please create a test case named `testExcessDataInZip64ExtraField` for the issue `Compress-COMPRESS-228`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-228 // // ## Issue-Title: // ZipException on reading valid zip64 file // // ## Issue-Description: // // ZipFile zip = new ZipFile(new File("ordertest-64.zip")); throws ZipException "central directory zip64 extended information extra field's length doesn't match central directory data. Expected length 16 but is 28". // // // The archive was created by using DotNetZip-WinFormsTool uzing zip64 flag (forces always to make zip64 archives). // // // Zip file is tested from the console: $zip -T ordertest-64.zip // // // Output: // // test of ordertest-64.zip OK // // // I can open the archive with FileRoller without problem on my machine, browse and extract it. // // // // // public void testExcessDataInZip64ExtraField() throws Exception {
238
/** * @see https://issues.apache.org/jira/browse/COMPRESS-228 */
19
231
src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-228 ## Issue-Title: ZipException on reading valid zip64 file ## Issue-Description: ZipFile zip = new ZipFile(new File("ordertest-64.zip")); throws ZipException "central directory zip64 extended information extra field's length doesn't match central directory data. Expected length 16 but is 28". The archive was created by using DotNetZip-WinFormsTool uzing zip64 flag (forces always to make zip64 archives). Zip file is tested from the console: $zip -T ordertest-64.zip Output: test of ordertest-64.zip OK I can open the archive with FileRoller without problem on my machine, browse and extract it. ``` You are a professional Java test case writer, please create a test case named `testExcessDataInZip64ExtraField` for the issue `Compress-COMPRESS-228`, utilizing the provided issue report information and the following function signature. ```java public void testExcessDataInZip64ExtraField() throws Exception { ```
231
[ "org.apache.commons.compress.archivers.zip.Zip64ExtendedInformationExtraField" ]
a6c0abaf530457e66f257e7095b67c7cc560ad33b4c407ee92359a341faa0a56
public void testExcessDataInZip64ExtraField() throws Exception
// You are a professional Java test case writer, please create a test case named `testExcessDataInZip64ExtraField` for the issue `Compress-COMPRESS-228`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-228 // // ## Issue-Title: // ZipException on reading valid zip64 file // // ## Issue-Description: // // ZipFile zip = new ZipFile(new File("ordertest-64.zip")); throws ZipException "central directory zip64 extended information extra field's length doesn't match central directory data. Expected length 16 but is 28". // // // The archive was created by using DotNetZip-WinFormsTool uzing zip64 flag (forces always to make zip64 archives). // // // Zip file is tested from the console: $zip -T ordertest-64.zip // // // Output: // // test of ordertest-64.zip OK // // // I can open the archive with FileRoller without problem on my machine, browse and extract it. // // // // //
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 static org.apache.commons.compress.AbstractTestCase.getFile; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.TreeMap; import java.util.zip.ZipEntry; import junit.framework.TestCase; public class ZipFileTest extends TestCase { private ZipFile zf = null; @Override public void tearDown() { ZipFile.closeQuietly(zf); } public void testCDOrder() throws Exception { readOrderTest(); ArrayList<ZipArchiveEntry> l = Collections.list(zf.getEntries()); assertEntryName(l, 0, "AbstractUnicodeExtraField"); assertEntryName(l, 1, "AsiExtraField"); assertEntryName(l, 2, "ExtraFieldUtils"); assertEntryName(l, 3, "FallbackZipEncoding"); assertEntryName(l, 4, "GeneralPurposeBit"); assertEntryName(l, 5, "JarMarker"); assertEntryName(l, 6, "NioZipEncoding"); assertEntryName(l, 7, "Simple8BitZipEncoding"); assertEntryName(l, 8, "UnicodeCommentExtraField"); assertEntryName(l, 9, "UnicodePathExtraField"); assertEntryName(l, 10, "UnixStat"); assertEntryName(l, 11, "UnparseableExtraFieldData"); assertEntryName(l, 12, "UnrecognizedExtraField"); assertEntryName(l, 13, "ZipArchiveEntry"); assertEntryName(l, 14, "ZipArchiveInputStream"); assertEntryName(l, 15, "ZipArchiveOutputStream"); assertEntryName(l, 16, "ZipEncoding"); assertEntryName(l, 17, "ZipEncodingHelper"); assertEntryName(l, 18, "ZipExtraField"); assertEntryName(l, 19, "ZipUtil"); assertEntryName(l, 20, "ZipLong"); assertEntryName(l, 21, "ZipShort"); assertEntryName(l, 22, "ZipFile"); } public void testPhysicalOrder() throws Exception { readOrderTest(); ArrayList<ZipArchiveEntry> l = Collections.list(zf.getEntriesInPhysicalOrder()); assertEntryName(l, 0, "AbstractUnicodeExtraField"); assertEntryName(l, 1, "AsiExtraField"); assertEntryName(l, 2, "ExtraFieldUtils"); assertEntryName(l, 3, "FallbackZipEncoding"); assertEntryName(l, 4, "GeneralPurposeBit"); assertEntryName(l, 5, "JarMarker"); assertEntryName(l, 6, "NioZipEncoding"); assertEntryName(l, 7, "Simple8BitZipEncoding"); assertEntryName(l, 8, "UnicodeCommentExtraField"); assertEntryName(l, 9, "UnicodePathExtraField"); assertEntryName(l, 10, "UnixStat"); assertEntryName(l, 11, "UnparseableExtraFieldData"); assertEntryName(l, 12, "UnrecognizedExtraField"); assertEntryName(l, 13, "ZipArchiveEntry"); assertEntryName(l, 14, "ZipArchiveInputStream"); assertEntryName(l, 15, "ZipArchiveOutputStream"); assertEntryName(l, 16, "ZipEncoding"); assertEntryName(l, 17, "ZipEncodingHelper"); assertEntryName(l, 18, "ZipExtraField"); assertEntryName(l, 19, "ZipFile"); assertEntryName(l, 20, "ZipLong"); assertEntryName(l, 21, "ZipShort"); assertEntryName(l, 22, "ZipUtil"); } public void testDoubleClose() throws Exception { readOrderTest(); zf.close(); try { zf.close(); } catch (Exception ex) { fail("Caught exception of second close"); } } public void testReadingOfStoredEntry() throws Exception { File f = File.createTempFile("commons-compress-zipfiletest", ".zip"); f.deleteOnExit(); OutputStream o = null; InputStream i = null; try { o = new FileOutputStream(f); ZipArchiveOutputStream zo = new ZipArchiveOutputStream(o); ZipArchiveEntry ze = new ZipArchiveEntry("foo"); ze.setMethod(ZipEntry.STORED); ze.setSize(4); ze.setCrc(0xb63cfbcdl); zo.putArchiveEntry(ze); zo.write(new byte[] { 1, 2, 3, 4 }); zo.closeArchiveEntry(); zo.close(); o.close(); o = null; zf = new ZipFile(f); ze = zf.getEntry("foo"); assertNotNull(ze); i = zf.getInputStream(ze); byte[] b = new byte[4]; assertEquals(4, i.read(b)); assertEquals(-1, i.read()); } finally { if (o != null) { o.close(); } if (i != null) { i.close(); } f.delete(); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-176" */ public void testWinzipBackSlashWorkaround() throws Exception { File archive = getFile("test-winzip.zip"); zf = new ZipFile(archive); assertNull(zf.getEntry("\u00e4\\\u00fc.txt")); assertNotNull(zf.getEntry("\u00e4/\u00fc.txt")); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-208" * >COMPRESS-208</a>. */ public void testSkipsPK00Prefix() throws Exception { File archive = getFile("COMPRESS-208.zip"); zf = new ZipFile(archive); assertNotNull(zf.getEntry("test1.xml")); assertNotNull(zf.getEntry("test2.xml")); } public void testUnixSymlinkSampleFile() throws Exception { final String entryPrefix = "COMPRESS-214_unix_symlinks/"; final TreeMap<String, String> expectedVals = new TreeMap<String, String>(); // I threw in some Japanese characters to keep things interesting. expectedVals.put(entryPrefix + "link1", "../COMPRESS-214_unix_symlinks/./a/b/c/../../../\uF999"); expectedVals.put(entryPrefix + "link2", "../COMPRESS-214_unix_symlinks/./a/b/c/../../../g"); expectedVals.put(entryPrefix + "link3", "../COMPRESS-214_unix_symlinks/././a/b/c/../../../\u76F4\u6A39"); expectedVals.put(entryPrefix + "link4", "\u82B1\u5B50/\u745B\u5B50"); expectedVals.put(entryPrefix + "\uF999", "./\u82B1\u5B50/\u745B\u5B50/\u5897\u8C37/\uF999"); expectedVals.put(entryPrefix + "g", "./a/b/c/d/e/f/g"); expectedVals.put(entryPrefix + "\u76F4\u6A39", "./g"); // Notice how a directory link might contain a trailing slash, or it might not. // Also note: symlinks are always stored as files, even if they link to directories. expectedVals.put(entryPrefix + "link5", "../COMPRESS-214_unix_symlinks/././a/b"); expectedVals.put(entryPrefix + "link6", "../COMPRESS-214_unix_symlinks/././a/b/"); // I looked into creating a test with hard links, but zip does not appear to // support hard links, so nevermind. File archive = getFile("COMPRESS-214_unix_symlinks.zip"); zf = new ZipFile(archive); Enumeration<ZipArchiveEntry> en = zf.getEntries(); while (en.hasMoreElements()) { ZipArchiveEntry zae = en.nextElement(); String link = zf.getUnixSymlink(zae); if (zae.isUnixSymlink()) { String name = zae.getName(); String expected = expectedVals.get(name); assertEquals(expected, link); } else { // Should be null if it's not a symlink! assertNull(link); } } } /** * @see https://issues.apache.org/jira/browse/COMPRESS-227 */ public void testDuplicateEntry() throws Exception { File archive = getFile("COMPRESS-227.zip"); zf = new ZipFile(archive); ZipArchiveEntry ze = zf.getEntry("test1.txt"); assertNotNull(ze); assertNotNull(zf.getInputStream(ze)); int numberOfEntries = 0; for (Iterator<ZipArchiveEntry> it = zf.getEntries("test1.txt"); it.hasNext(); ) { numberOfEntries++; ze = it.next(); assertNotNull(zf.getInputStream(ze)); } assertEquals(2, numberOfEntries); } /** * @see https://issues.apache.org/jira/browse/COMPRESS-228 */ public void testExcessDataInZip64ExtraField() throws Exception { File archive = getFile("COMPRESS-228.zip"); zf = new ZipFile(archive); // actually, if we get here, the test already has passed ZipArchiveEntry ze = zf.getEntry("src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java"); assertEquals(26101, ze.getSize()); } /* * ordertest.zip has been handcrafted. * * It contains enough files so any random coincidence of * entries.keySet() and central directory order would be unlikely * - in fact testCDOrder fails in svn revision 920284. * * The central directory has ZipFile and ZipUtil swapped so * central directory order is different from entry data order. */ private void readOrderTest() throws Exception { File archive = getFile("ordertest.zip"); zf = new ZipFile(archive); } private static void assertEntryName(ArrayList<ZipArchiveEntry> entries, int index, String expectedName) { ZipArchiveEntry ze = entries.get(index); assertEquals("src/main/java/org/apache/commons/compress/archivers/zip/" + expectedName + ".java", ze.getName()); } }
public void testPOJONodeCustomSer() throws Exception { Data data = new Data(); data.aStr = "Hello"; Map<String, Object> mapTest = new HashMap<>(); mapTest.put("data", data); ObjectNode treeTest = MAPPER.createObjectNode(); treeTest.putPOJO("data", data); final String EXP = "{\"data\":{\"aStr\":\"The value is: Hello!\"}}"; String mapOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest); assertEquals(EXP, mapOut); String treeOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest); assertEquals(EXP, treeOut); }
com.fasterxml.jackson.databind.node.POJONodeTest::testPOJONodeCustomSer
src/test/java/com/fasterxml/jackson/databind/node/POJONodeTest.java
53
src/test/java/com/fasterxml/jackson/databind/node/POJONodeTest.java
testPOJONodeCustomSer
package com.fasterxml.jackson.databind.node; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class POJONodeTest extends NodeTestBase { @JsonSerialize(using = CustomSer.class) public static class Data { public String aStr; } @SuppressWarnings("serial") public static class CustomSer extends StdSerializer<Data> { public CustomSer() { super(Data.class); } @Override public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException { String attrStr = (String) provider.getAttribute("myAttr"); gen.writeStartObject(); gen.writeStringField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr)); gen.writeEndObject(); } } final ObjectMapper MAPPER = newObjectMapper(); public void testPOJONodeCustomSer() throws Exception { Data data = new Data(); data.aStr = "Hello"; Map<String, Object> mapTest = new HashMap<>(); mapTest.put("data", data); ObjectNode treeTest = MAPPER.createObjectNode(); treeTest.putPOJO("data", data); final String EXP = "{\"data\":{\"aStr\":\"The value is: Hello!\"}}"; String mapOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest); assertEquals(EXP, mapOut); String treeOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest); assertEquals(EXP, treeOut); } }
// You are a professional Java test case writer, please create a test case named `testPOJONodeCustomSer` for the issue `JacksonDatabind-1991`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1991 // // ## Issue-Title: // Context attributes are not passed/available to custom serializer if object is in POJO // // ## Issue-Description: // Below is a test case where I create a custom serializer and use it to serialize an object 1) in a HashMap and 2) in an ObjectNode. In both cases I pass attribute to the serializer like this: // // `mapper.writer().withAttribute("myAttr", "Hello!")` // // Serializing HashMap works as expected, but during ObjectNode serialization the attribute is null . It seems that in both cases the custom serializer should get access to the passed attribute and so both lines in the output should contain "Hello!" // // // Produced output from running testCase.test() // // // // ``` // {"data":{"aStr":"The value is: Hello!"}} // {"data":{"aStr":"The value is: NULL"}} // // // ``` // // Test case: // // // // ``` // import com.fasterxml.jackson.core.JsonGenerator; // import com.fasterxml.jackson.databind.ObjectMapper; // import com.fasterxml.jackson.databind.SerializerProvider; // import com.fasterxml.jackson.databind.annotation.JsonSerialize; // import com.fasterxml.jackson.databind.node.ObjectNode; // import com.fasterxml.jackson.databind.ser.std.StdSerializer; // // import java.io.IOException; // import java.util.HashMap; // import java.util.Map; // // public class TestCase { // public final static ObjectMapper mapper = new ObjectMapper(); // // @JsonSerialize(using = TestCase.CustomSer.class) // public static class Data { // public String aStr; // } // // public static class CustomSer extends StdSerializer<Data> { // public CustomSer() { // super(Data.class); // } // // @Override // public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException { // String attrStr = (String) provider.getAttribute("myAttr"); // gen.writeStartObject(); // gen.writeObjectField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr)); // gen.writeEndObject(); // } // } // // public static void test() throws IOException { // Data data = new Data(); // data.aStr = "Hello"; // // Map<String, Object> mapTest = new HashMap<>(); // mapTest.put("data", data); // // ObjectNode treeTest = mapper.createObjectNode(); // treeTest.putPOJO("data", data); // // String mapOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest); // System.out.println(mapOut); // // String treeOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest); // System.out.println(treeOut); // } // } // // // ``` // // // public void testPOJONodeCustomSer() throws Exception {
53
97
35
src/test/java/com/fasterxml/jackson/databind/node/POJONodeTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1991 ## Issue-Title: Context attributes are not passed/available to custom serializer if object is in POJO ## Issue-Description: Below is a test case where I create a custom serializer and use it to serialize an object 1) in a HashMap and 2) in an ObjectNode. In both cases I pass attribute to the serializer like this: `mapper.writer().withAttribute("myAttr", "Hello!")` Serializing HashMap works as expected, but during ObjectNode serialization the attribute is null . It seems that in both cases the custom serializer should get access to the passed attribute and so both lines in the output should contain "Hello!" Produced output from running testCase.test() ``` {"data":{"aStr":"The value is: Hello!"}} {"data":{"aStr":"The value is: NULL"}} ``` Test case: ``` import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class TestCase { public final static ObjectMapper mapper = new ObjectMapper(); @JsonSerialize(using = TestCase.CustomSer.class) public static class Data { public String aStr; } public static class CustomSer extends StdSerializer<Data> { public CustomSer() { super(Data.class); } @Override public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException { String attrStr = (String) provider.getAttribute("myAttr"); gen.writeStartObject(); gen.writeObjectField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr)); gen.writeEndObject(); } } public static void test() throws IOException { Data data = new Data(); data.aStr = "Hello"; Map<String, Object> mapTest = new HashMap<>(); mapTest.put("data", data); ObjectNode treeTest = mapper.createObjectNode(); treeTest.putPOJO("data", data); String mapOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest); System.out.println(mapOut); String treeOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest); System.out.println(treeOut); } } ``` ``` You are a professional Java test case writer, please create a test case named `testPOJONodeCustomSer` for the issue `JacksonDatabind-1991`, utilizing the provided issue report information and the following function signature. ```java public void testPOJONodeCustomSer() throws Exception { ```
35
[ "com.fasterxml.jackson.databind.node.POJONode" ]
a721a6aa0411de7c03ea50ac7b3f90aac3606bc0fc025914717869c607781474
public void testPOJONodeCustomSer() throws Exception
// You are a professional Java test case writer, please create a test case named `testPOJONodeCustomSer` for the issue `JacksonDatabind-1991`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1991 // // ## Issue-Title: // Context attributes are not passed/available to custom serializer if object is in POJO // // ## Issue-Description: // Below is a test case where I create a custom serializer and use it to serialize an object 1) in a HashMap and 2) in an ObjectNode. In both cases I pass attribute to the serializer like this: // // `mapper.writer().withAttribute("myAttr", "Hello!")` // // Serializing HashMap works as expected, but during ObjectNode serialization the attribute is null . It seems that in both cases the custom serializer should get access to the passed attribute and so both lines in the output should contain "Hello!" // // // Produced output from running testCase.test() // // // // ``` // {"data":{"aStr":"The value is: Hello!"}} // {"data":{"aStr":"The value is: NULL"}} // // // ``` // // Test case: // // // // ``` // import com.fasterxml.jackson.core.JsonGenerator; // import com.fasterxml.jackson.databind.ObjectMapper; // import com.fasterxml.jackson.databind.SerializerProvider; // import com.fasterxml.jackson.databind.annotation.JsonSerialize; // import com.fasterxml.jackson.databind.node.ObjectNode; // import com.fasterxml.jackson.databind.ser.std.StdSerializer; // // import java.io.IOException; // import java.util.HashMap; // import java.util.Map; // // public class TestCase { // public final static ObjectMapper mapper = new ObjectMapper(); // // @JsonSerialize(using = TestCase.CustomSer.class) // public static class Data { // public String aStr; // } // // public static class CustomSer extends StdSerializer<Data> { // public CustomSer() { // super(Data.class); // } // // @Override // public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException { // String attrStr = (String) provider.getAttribute("myAttr"); // gen.writeStartObject(); // gen.writeObjectField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr)); // gen.writeEndObject(); // } // } // // public static void test() throws IOException { // Data data = new Data(); // data.aStr = "Hello"; // // Map<String, Object> mapTest = new HashMap<>(); // mapTest.put("data", data); // // ObjectNode treeTest = mapper.createObjectNode(); // treeTest.putPOJO("data", data); // // String mapOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest); // System.out.println(mapOut); // // String treeOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest); // System.out.println(treeOut); // } // } // // // ``` // // //
JacksonDatabind
package com.fasterxml.jackson.databind.node; import java.io.IOException; import java.util.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class POJONodeTest extends NodeTestBase { @JsonSerialize(using = CustomSer.class) public static class Data { public String aStr; } @SuppressWarnings("serial") public static class CustomSer extends StdSerializer<Data> { public CustomSer() { super(Data.class); } @Override public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException { String attrStr = (String) provider.getAttribute("myAttr"); gen.writeStartObject(); gen.writeStringField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr)); gen.writeEndObject(); } } final ObjectMapper MAPPER = newObjectMapper(); public void testPOJONodeCustomSer() throws Exception { Data data = new Data(); data.aStr = "Hello"; Map<String, Object> mapTest = new HashMap<>(); mapTest.put("data", data); ObjectNode treeTest = MAPPER.createObjectNode(); treeTest.putPOJO("data", data); final String EXP = "{\"data\":{\"aStr\":\"The value is: Hello!\"}}"; String mapOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest); assertEquals(EXP, mapOut); String treeOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest); assertEquals(EXP, treeOut); } }
@Test public void testToMapWithShortRecord() throws Exception { final CSVParser parser = CSVParser.parse("a,b", CSVFormat.DEFAULT.withHeader("A", "B", "C")); final CSVRecord shortRec = parser.iterator().next(); shortRec.toMap(); }
org.apache.commons.csv.CSVRecordTest::testToMapWithShortRecord
src/test/java/org/apache/commons/csv/CSVRecordTest.java
167
src/test/java/org/apache/commons/csv/CSVRecordTest.java
testToMapWithShortRecord
/* * 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.csv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CSVRecordTest { private enum EnumFixture { UNKNOWN_COLUMN } private String[] values; private CSVRecord record, recordWithHeader; private Map<String, Integer> header; @Before public void setUp() throws Exception { values = new String[] { "A", "B", "C" }; record = new CSVRecord(values, null, null, 0); header = new HashMap<String, Integer>(); header.put("first", Integer.valueOf(0)); header.put("second", Integer.valueOf(1)); header.put("third", Integer.valueOf(2)); recordWithHeader = new CSVRecord(values, header, null, 0); } @Test public void testGetInt() { assertEquals(values[0], record.get(0)); assertEquals(values[1], record.get(1)); assertEquals(values[2], record.get(2)); } @Test public void testGetString() { assertEquals(values[0], recordWithHeader.get("first")); assertEquals(values[1], recordWithHeader.get("second")); assertEquals(values[2], recordWithHeader.get("third")); } @Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord() { header.put("fourth", Integer.valueOf(4)); recordWithHeader.get("fourth"); } @Test(expected = IllegalStateException.class) public void testGetStringNoHeader() { record.get("first"); } @Test(expected = IllegalArgumentException.class) public void testGetUnmappedEnum() { assertNull(recordWithHeader.get(EnumFixture.UNKNOWN_COLUMN)); } @Test(expected = IllegalArgumentException.class) public void testGetUnmappedName() { assertNull(recordWithHeader.get("fourth")); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testGetUnmappedNegativeInt() { assertNull(recordWithHeader.get(Integer.MIN_VALUE)); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testGetUnmappedPositiveInt() { assertNull(recordWithHeader.get(Integer.MAX_VALUE)); } @Test public void testIsConsistent() { assertTrue(record.isConsistent()); assertTrue(recordWithHeader.isConsistent()); header.put("fourth", Integer.valueOf(4)); assertFalse(recordWithHeader.isConsistent()); } @Test public void testIsMapped() { assertFalse(record.isMapped("first")); assertTrue(recordWithHeader.isMapped("first")); assertFalse(recordWithHeader.isMapped("fourth")); } @Test public void testIsSet() { assertFalse(record.isSet("first")); assertTrue(recordWithHeader.isSet("first")); assertFalse(recordWithHeader.isSet("fourth")); } @Test public void testIterator() { int i = 0; for (final String value : record) { assertEquals(values[i], value); i++; } } @Test public void testPutInMap() { final Map<String, String> map = new ConcurrentHashMap<String, String>(); this.recordWithHeader.putIn(map); this.validateMap(map, false); // Test that we can compile with assigment to the same map as the param. final TreeMap<String, String> map2 = recordWithHeader.putIn(new TreeMap<String, String>()); this.validateMap(map2, false); } @Test public void testRemoveAndAddColumns() throws IOException { // do: final CSVPrinter printer = new CSVPrinter(new StringBuilder(), CSVFormat.DEFAULT); final Map<String, String> map = recordWithHeader.toMap(); map.remove("OldColumn"); map.put("ZColumn", "NewValue"); // check: final ArrayList<String> list = new ArrayList<String>(map.values()); Collections.sort(list); printer.printRecord(list); Assert.assertEquals("A,B,C,NewValue" + CSVFormat.DEFAULT.getRecordSeparator(), printer.getOut().toString()); printer.close(); } @Test public void testToMap() { final Map<String, String> map = this.recordWithHeader.toMap(); this.validateMap(map, true); } @Test public void testToMapWithShortRecord() throws Exception { final CSVParser parser = CSVParser.parse("a,b", CSVFormat.DEFAULT.withHeader("A", "B", "C")); final CSVRecord shortRec = parser.iterator().next(); shortRec.toMap(); } private void validateMap(final Map<String, String> map, final boolean allowsNulls) { assertTrue(map.containsKey("first")); assertTrue(map.containsKey("second")); assertTrue(map.containsKey("third")); assertFalse(map.containsKey("fourth")); if (allowsNulls) { assertFalse(map.containsKey(null)); } assertEquals("A", map.get("first")); assertEquals("B", map.get("second")); assertEquals("C", map.get("third")); assertEquals(null, map.get("fourth")); } }
// You are a professional Java test case writer, please create a test case named `testToMapWithShortRecord` for the issue `Csv-CSV-111`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-111 // // ## Issue-Title: // CSVRecord.toMap() fails if row length shorter than header length // // ## Issue-Description: // // Similar to [~~CSV-96~~](https://issues.apache.org/jira/browse/CSV-96 "CSVRecord does not verify that the length of the header mapping matches the number of values"), if .toMap() is called on a record that has fewer fields than we have header columns we'll get an ArrayOutOfBoundsException. // // // // // ``` // @Test // public void testToMapWhenHeaderTooLong() throws Exception { // final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build()); // final CSVRecord record = parser.iterator().next(); // record.toMap(); // } // // ``` // // // // // @Test public void testToMapWithShortRecord() throws Exception {
167
6
162
src/test/java/org/apache/commons/csv/CSVRecordTest.java
src/test/java
```markdown ## Issue-ID: Csv-CSV-111 ## Issue-Title: CSVRecord.toMap() fails if row length shorter than header length ## Issue-Description: Similar to [~~CSV-96~~](https://issues.apache.org/jira/browse/CSV-96 "CSVRecord does not verify that the length of the header mapping matches the number of values"), if .toMap() is called on a record that has fewer fields than we have header columns we'll get an ArrayOutOfBoundsException. ``` @Test public void testToMapWhenHeaderTooLong() throws Exception { final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build()); final CSVRecord record = parser.iterator().next(); record.toMap(); } ``` ``` You are a professional Java test case writer, please create a test case named `testToMapWithShortRecord` for the issue `Csv-CSV-111`, utilizing the provided issue report information and the following function signature. ```java @Test public void testToMapWithShortRecord() throws Exception { ```
162
[ "org.apache.commons.csv.CSVRecord" ]
a7476023a472496122c0f2766e394ea627ebf8f38e611bcdccd26ab62a6ced2c
@Test public void testToMapWithShortRecord() throws Exception
// You are a professional Java test case writer, please create a test case named `testToMapWithShortRecord` for the issue `Csv-CSV-111`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-111 // // ## Issue-Title: // CSVRecord.toMap() fails if row length shorter than header length // // ## Issue-Description: // // Similar to [~~CSV-96~~](https://issues.apache.org/jira/browse/CSV-96 "CSVRecord does not verify that the length of the header mapping matches the number of values"), if .toMap() is called on a record that has fewer fields than we have header columns we'll get an ArrayOutOfBoundsException. // // // // // ``` // @Test // public void testToMapWhenHeaderTooLong() throws Exception { // final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build()); // final CSVRecord record = parser.iterator().next(); // record.toMap(); // } // // ``` // // // // //
Csv
/* * 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.csv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CSVRecordTest { private enum EnumFixture { UNKNOWN_COLUMN } private String[] values; private CSVRecord record, recordWithHeader; private Map<String, Integer> header; @Before public void setUp() throws Exception { values = new String[] { "A", "B", "C" }; record = new CSVRecord(values, null, null, 0); header = new HashMap<String, Integer>(); header.put("first", Integer.valueOf(0)); header.put("second", Integer.valueOf(1)); header.put("third", Integer.valueOf(2)); recordWithHeader = new CSVRecord(values, header, null, 0); } @Test public void testGetInt() { assertEquals(values[0], record.get(0)); assertEquals(values[1], record.get(1)); assertEquals(values[2], record.get(2)); } @Test public void testGetString() { assertEquals(values[0], recordWithHeader.get("first")); assertEquals(values[1], recordWithHeader.get("second")); assertEquals(values[2], recordWithHeader.get("third")); } @Test(expected = IllegalArgumentException.class) public void testGetStringInconsistentRecord() { header.put("fourth", Integer.valueOf(4)); recordWithHeader.get("fourth"); } @Test(expected = IllegalStateException.class) public void testGetStringNoHeader() { record.get("first"); } @Test(expected = IllegalArgumentException.class) public void testGetUnmappedEnum() { assertNull(recordWithHeader.get(EnumFixture.UNKNOWN_COLUMN)); } @Test(expected = IllegalArgumentException.class) public void testGetUnmappedName() { assertNull(recordWithHeader.get("fourth")); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testGetUnmappedNegativeInt() { assertNull(recordWithHeader.get(Integer.MIN_VALUE)); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testGetUnmappedPositiveInt() { assertNull(recordWithHeader.get(Integer.MAX_VALUE)); } @Test public void testIsConsistent() { assertTrue(record.isConsistent()); assertTrue(recordWithHeader.isConsistent()); header.put("fourth", Integer.valueOf(4)); assertFalse(recordWithHeader.isConsistent()); } @Test public void testIsMapped() { assertFalse(record.isMapped("first")); assertTrue(recordWithHeader.isMapped("first")); assertFalse(recordWithHeader.isMapped("fourth")); } @Test public void testIsSet() { assertFalse(record.isSet("first")); assertTrue(recordWithHeader.isSet("first")); assertFalse(recordWithHeader.isSet("fourth")); } @Test public void testIterator() { int i = 0; for (final String value : record) { assertEquals(values[i], value); i++; } } @Test public void testPutInMap() { final Map<String, String> map = new ConcurrentHashMap<String, String>(); this.recordWithHeader.putIn(map); this.validateMap(map, false); // Test that we can compile with assigment to the same map as the param. final TreeMap<String, String> map2 = recordWithHeader.putIn(new TreeMap<String, String>()); this.validateMap(map2, false); } @Test public void testRemoveAndAddColumns() throws IOException { // do: final CSVPrinter printer = new CSVPrinter(new StringBuilder(), CSVFormat.DEFAULT); final Map<String, String> map = recordWithHeader.toMap(); map.remove("OldColumn"); map.put("ZColumn", "NewValue"); // check: final ArrayList<String> list = new ArrayList<String>(map.values()); Collections.sort(list); printer.printRecord(list); Assert.assertEquals("A,B,C,NewValue" + CSVFormat.DEFAULT.getRecordSeparator(), printer.getOut().toString()); printer.close(); } @Test public void testToMap() { final Map<String, String> map = this.recordWithHeader.toMap(); this.validateMap(map, true); } @Test public void testToMapWithShortRecord() throws Exception { final CSVParser parser = CSVParser.parse("a,b", CSVFormat.DEFAULT.withHeader("A", "B", "C")); final CSVRecord shortRec = parser.iterator().next(); shortRec.toMap(); } private void validateMap(final Map<String, String> map, final boolean allowsNulls) { assertTrue(map.containsKey("first")); assertTrue(map.containsKey("second")); assertTrue(map.containsKey("third")); assertFalse(map.containsKey("fourth")); if (allowsNulls) { assertFalse(map.containsKey(null)); } assertEquals("A", map.get("first")); assertEquals("B", map.get("second")); assertEquals("C", map.get("third")); assertEquals(null, map.get("fourth")); } }
@Test public void testDontQuoteEuroFirstChar() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { printer.printRecord(EURO_CH, "Deux"); assertEquals(EURO_CH + ",Deux" + recordSeparator, sw.toString()); } }
org.apache.commons.csv.CSVPrinterTest::testDontQuoteEuroFirstChar
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
1,041
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
testDontQuoteEuroFirstChar
/* * 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.csv; import static org.apache.commons.csv.Constants.CR; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.io.CharArrayWriter; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.Vector; import org.apache.commons.io.FileUtils; import org.h2.value.Value; import org.h2.value.ValueArray; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * */ public class CSVPrinterTest { private static final char EURO_CH = '\u20AC'; private static final char DQUOTE_CHAR = '"'; private static final char BACKSLASH_CH = '\\'; private static final char QUOTE_CH = '\''; private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; private static String printable(final String s) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final char ch = s.charAt(i); if (ch <= ' ' || ch >= 128) { sb.append("(").append((int) ch).append(")"); } else { sb.append(ch); } } return sb.toString(); } private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); private void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = generateLines(nLines, nCol); final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[]) lines[i]); } printer.flush(); } final String result = sw.toString(); // System.out.println("### :" + printable(result)); try (final CSVParser parser = CSVParser.parse(result, format)) { final List<CSVRecord> parseResult = parser.getRecords(); final String[][] expected = lines.clone(); for (int i = 0; i < expected.length; i++) { expected[i] = expectNulls(expected[i], format); } Utils.compare("Printer output :" + printable(result), expected, parseResult); } } private void doRandom(final CSVFormat format, final int iter) throws Exception { for (int i = 0; i < iter; i++) { doOneRandom(format); } } /** * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values * because the parser will convert these strings to null. */ private <T> T[] expectNulls(final T[] original, final CSVFormat csvFormat) { final T[] fixed = original.clone(); for (int i = 0; i < fixed.length; i++) { if (Objects.equals(csvFormat.getNullString(), fixed[i])) { fixed[i] = null; } } return fixed; } private Connection geH2Connection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); } private String[][] generateLines(final int nLines, final int nCol) { final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } return lines; } private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) throws IOException { CSVFormat format = baseFormat; // Use withHeaderComments first to test CSV-145 format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); format = format.withCommentMarker('#'); format = format.withHeader("Col1", "Col2"); final CSVPrinter csvPrinter = format.print(sw); csvPrinter.printRecord("A", "B"); csvPrinter.printRecord("C", "D"); csvPrinter.close(); return csvPrinter; } private String randStr() { final Random r = new Random(); final int sz = r.nextInt(20); // sz = r.nextInt(3); final char[] buf = new char[sz]; for (int i = 0; i < sz; i++) { // stick in special chars with greater frequency char ch; final int what = r.nextInt(20); switch (what) { case 0: ch = '\r'; break; case 1: ch = '\n'; break; case 2: ch = '\t'; break; case 3: ch = '\f'; break; case 4: ch = ' '; break; case 5: ch = ','; break; case 6: ch = DQUOTE_CHAR; break; case 7: ch = '\''; break; case 8: ch = BACKSLASH_CH; break; default: ch = (char) r.nextInt(300); break; // default: ch = 'a'; break; } buf[i] = ch; } return new String(buf); } private void setUpTable(final Connection connection) throws SQLException { try (final Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); statement.execute("insert into TEST values(1, 'r1')"); statement.execute("insert into TEST values(2, 'r2')"); } } @Test public void testDelimeterQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("'a,b,c',xyz", sw.toString()); } } @Test public void testDelimeterQuoteNONE() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a,b,c,xyz", sw.toString()); } } @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printComment("This is a comment"); assertEquals("", sw.toString()); } } @Test public void testEOLEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a!rb!nc,x\fy\bz", sw.toString()); } } @Test public void testEOLPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a\rb\nc,x\fy\bz", sw.toString()); } } @Test public void testEOLQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a\rb\nc"); printer.print("x\by\fz"); assertEquals("'a\rb\nc',x\by\fz", sw.toString()); } } @Test public void testEscapeBackslash1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeBackslash2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\r"); } assertEquals("'\\\r'", sw.toString()); } @Test public void testEscapeBackslash3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("X\\\r"); } assertEquals("'X\\\r'", sw.toString()); } @Test public void testEscapeBackslash4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeBackslash5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeNull2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\r"); } assertEquals("\"\\\r\"", sw.toString()); } @Test public void testEscapeNull3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("X\\\r"); } assertEquals("\"X\\\r\"", sw.toString()); } @Test public void testEscapeNull4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testExcelPrintAllArrayOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testHeader() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testHeaderCommentExcel() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.EXCEL; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", sw.toString()); } } @Test public void testHeaderCommentTdf() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.TDF; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", sw.toString()); } } @Test public void testHeaderNotSet() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception { final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), invalidFormat)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); } } assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection();) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { printer.printRecords(resultSet); } } assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { printer.printRecords(resultSet); assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } } } @Test @Ignore public void testJira135_part1() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); printer.printRecord(list); } final String expected = "\"\\\"\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part2() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\n"); printer.printRecord(list); } final String expected = "\"\\n\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part3() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135All() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); list.add("\n"); list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test public void testMultiLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment\non multiple lines"); assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); } } @Test public void testMySqlNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test @Ignore public void testPostgreSqlCsvNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.POSTGRESQL_CSV.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\",NULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_CSV.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test @Ignore public void testPostgreSqlCsvTextOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.POSTGRESQL_TEXT.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test public void testMySqlNullStringDefault() { assertEquals("\\N", CSVFormat.MYSQL.getNullString()); } @Test public void testPostgreSQLNullStringDefaultCsv() { assertEquals("", CSVFormat.POSTGRESQL_CSV.getNullString()); } @Test public void testPostgreSQLNullStringDefaultText() { assertEquals("\\N", CSVFormat.POSTGRESQL_TEXT.getNullString()); } @Test(expected = IllegalArgumentException.class) public void testNewCsvPrinterAppendableNullFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), null)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVPrinterNullAppendableFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.printRecord("a", null, "b"); } final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); try (final CSVParser iterable = format.parse(new StringReader(csvString))) { final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } } @Test public void testPlainEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("abc"); assertEquals("abc", sw.toString()); } } @Test public void testPrint() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { printer.printRecord("a", null, "b"); assertEquals("a,NULL,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testDontQuoteEuroFirstChar() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { printer.printRecord(EURO_CH, "Deux"); assertEquals(EURO_CH + ",Deux" + recordSeparator, sw.toString()); } } @Test public void testQuoteCommaFirstChar() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { printer.printRecord(","); assertEquals("\",\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testPrinter3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a, b", "b "); assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); } } @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\nc"); assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter6() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\r\nc"); assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter7() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", null, "b"); assertEquals("a,,b" + recordSeparator, sw.toString()); } } @Test public void testPrintOnePositiveInteger() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { printer.print(Integer.MAX_VALUE); assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); } } @Test public void testPrintToFileWithCharsetUtf16Be() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); } @Test public void testPrintToFileWithDefaultCharset() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testPrintToPathWithDefaultCharset() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testQuoteAll() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { printer.printRecord("a", "b\nc", "d"); assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); } } @Test public void testQuoteNonNumeric() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { printer.printRecord("a", "b\nc", Integer.valueOf(1)); assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); } } @Test public void testRandomDefault() throws Exception { doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomExcel() throws Exception { doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomMySql() throws Exception { doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); } @Test @Ignore public void testRandomPostgreSqlCsv() throws Exception { doRandom(CSVFormat.POSTGRESQL_CSV, ITERATIONS_FOR_RANDOM_TEST); } @Test @Ignore public void testRandomPostgreSqlText() throws Exception { doRandom(CSVFormat.POSTGRESQL_TEXT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomRfc4180() throws Exception { doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomTdf() throws Exception { doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testSingleLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment"); assertEquals("# This is a comment" + recordSeparator, sw.toString()); } } @Test public void testSingleQuoteQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a'b'c"); printer.print("xyz"); assertEquals("'a''b''c',xyz", sw.toString()); } } @Test public void testSkipHeaderRecordFalse() throws IOException { // functionally identical to testHeader, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testSkipHeaderRecordTrue() throws IOException { // functionally identical to testHeaderNotSet, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testTrailingDelimiterOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { printer.printRecord("A", "B"); assertEquals("A,B,\r\n", sw.toString()); } } @Test public void testTrimOffOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { printer.print(" A "); assertEquals("\" A \"", sw.toString()); } } @Test public void testTrimOnOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); assertEquals("A", sw.toString()); } } @Test public void testTrimOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); printer.print(" B "); assertEquals("A,B", sw.toString()); } } private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { return CSVParser.parse(expected, format).getRecords().get(0).values(); } @Test public void testPrintRecordsWithResultSetOneRow() throws IOException, SQLException { try (CSVPrinter csvPrinter = CSVFormat.MYSQL.printer()) { final Value[] valueArray = new Value[0]; final ValueArray valueArrayTwo = ValueArray.get(valueArray); try (ResultSet resultSet = valueArrayTwo.getResultSet()) { csvPrinter.printRecords(resultSet); assertEquals(0, resultSet.getRow()); } } } @Test public void testPrintRecordsWithObjectArray() throws IOException { final CharArrayWriter charArrayWriter = new CharArrayWriter(0); try (CSVPrinter csvPrinter = CSVFormat.INFORMIX_UNLOAD.print(charArrayWriter)) { final HashSet<BatchUpdateException> hashSet = new HashSet<>(); final Object[] objectArray = new Object[6]; objectArray[3] = hashSet; csvPrinter.printRecords(objectArray); } assertEquals(6, charArrayWriter.size()); assertEquals("\n\n\n\n\n\n", charArrayWriter.toString()); } @Test public void testPrintRecordsWithEmptyVector() throws IOException { try (CSVPrinter csvPrinter = CSVFormat.POSTGRESQL_TEXT.printer()) { final Vector<CSVFormatTest.EmptyEnum> vector = new Vector<>(); final int expectedCapacity = 23; vector.setSize(expectedCapacity); csvPrinter.printRecords(vector); assertEquals(expectedCapacity, vector.capacity()); } } @Test public void testCloseWithFlushOn() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT; final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); csvPrinter.close(true); verify(writer, times(1)).flush(); } @Test public void testCloseWithFlushOff() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT; final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); csvPrinter.close(false); verify(writer, never()).flush(); verify(writer, times(1)).close(); } @Test public void testCloseBackwardCompatibility() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT; try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { } verify(writer, never()).flush(); verify(writer, times(1)).close(); } @Test public void testCloseWithCsvFormatAutoFlushOn() throws IOException { // System.out.println("start method"); final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(true); try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { } verify(writer, times(1)).flush(); verify(writer, times(1)).close(); } @Test public void testCloseWithCsvFormatAutoFlushOff() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(false); try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { } verify(writer, never()).flush(); verify(writer, times(1)).close(); } }
// You are a professional Java test case writer, please create a test case named `testDontQuoteEuroFirstChar` for the issue `Csv-CSV-219`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-219 // // ## Issue-Title: // The behavior of quote char using is not similar as Excel does when the first string contains CJK char(s) // // ## Issue-Description: // // When using CSVFormat.EXCEL to print a CSV file, the behavior of quote char using is not similar as Microsoft Excel does when the first string contains Chinese, Japanese or Korean (CJK) char(s). // // // e.g. // // There are 3 data members in a record, with Japanese chars: "あ", "い", "う": // // Microsoft Excel outputs: // // あ,い,う // // Apache Common CSV outputs: // // "あ",い,う // // // // // @Test public void testDontQuoteEuroFirstChar() throws IOException {
1,041
15
1,034
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
src/test/java
```markdown ## Issue-ID: Csv-CSV-219 ## Issue-Title: The behavior of quote char using is not similar as Excel does when the first string contains CJK char(s) ## Issue-Description: When using CSVFormat.EXCEL to print a CSV file, the behavior of quote char using is not similar as Microsoft Excel does when the first string contains Chinese, Japanese or Korean (CJK) char(s). e.g. There are 3 data members in a record, with Japanese chars: "あ", "い", "う": Microsoft Excel outputs: あ,い,う Apache Common CSV outputs: "あ",い,う ``` You are a professional Java test case writer, please create a test case named `testDontQuoteEuroFirstChar` for the issue `Csv-CSV-219`, utilizing the provided issue report information and the following function signature. ```java @Test public void testDontQuoteEuroFirstChar() throws IOException { ```
1,034
[ "org.apache.commons.csv.CSVFormat" ]
a891fd450d7db7ba7a55b5af72b45ce12c069d808e49a88a558cd4e0bb3a39f2
@Test public void testDontQuoteEuroFirstChar() throws IOException
// You are a professional Java test case writer, please create a test case named `testDontQuoteEuroFirstChar` for the issue `Csv-CSV-219`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-219 // // ## Issue-Title: // The behavior of quote char using is not similar as Excel does when the first string contains CJK char(s) // // ## Issue-Description: // // When using CSVFormat.EXCEL to print a CSV file, the behavior of quote char using is not similar as Microsoft Excel does when the first string contains Chinese, Japanese or Korean (CJK) char(s). // // // e.g. // // There are 3 data members in a record, with Japanese chars: "あ", "い", "う": // // Microsoft Excel outputs: // // あ,い,う // // Apache Common CSV outputs: // // "あ",い,う // // // // //
Csv
/* * 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.csv; import static org.apache.commons.csv.Constants.CR; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.io.CharArrayWriter; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.Vector; import org.apache.commons.io.FileUtils; import org.h2.value.Value; import org.h2.value.ValueArray; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * */ public class CSVPrinterTest { private static final char EURO_CH = '\u20AC'; private static final char DQUOTE_CHAR = '"'; private static final char BACKSLASH_CH = '\\'; private static final char QUOTE_CH = '\''; private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; private static String printable(final String s) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final char ch = s.charAt(i); if (ch <= ' ' || ch >= 128) { sb.append("(").append((int) ch).append(")"); } else { sb.append(ch); } } return sb.toString(); } private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); private void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = generateLines(nLines, nCol); final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[]) lines[i]); } printer.flush(); } final String result = sw.toString(); // System.out.println("### :" + printable(result)); try (final CSVParser parser = CSVParser.parse(result, format)) { final List<CSVRecord> parseResult = parser.getRecords(); final String[][] expected = lines.clone(); for (int i = 0; i < expected.length; i++) { expected[i] = expectNulls(expected[i], format); } Utils.compare("Printer output :" + printable(result), expected, parseResult); } } private void doRandom(final CSVFormat format, final int iter) throws Exception { for (int i = 0; i < iter; i++) { doOneRandom(format); } } /** * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values * because the parser will convert these strings to null. */ private <T> T[] expectNulls(final T[] original, final CSVFormat csvFormat) { final T[] fixed = original.clone(); for (int i = 0; i < fixed.length; i++) { if (Objects.equals(csvFormat.getNullString(), fixed[i])) { fixed[i] = null; } } return fixed; } private Connection geH2Connection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); } private String[][] generateLines(final int nLines, final int nCol) { final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } return lines; } private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) throws IOException { CSVFormat format = baseFormat; // Use withHeaderComments first to test CSV-145 format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); format = format.withCommentMarker('#'); format = format.withHeader("Col1", "Col2"); final CSVPrinter csvPrinter = format.print(sw); csvPrinter.printRecord("A", "B"); csvPrinter.printRecord("C", "D"); csvPrinter.close(); return csvPrinter; } private String randStr() { final Random r = new Random(); final int sz = r.nextInt(20); // sz = r.nextInt(3); final char[] buf = new char[sz]; for (int i = 0; i < sz; i++) { // stick in special chars with greater frequency char ch; final int what = r.nextInt(20); switch (what) { case 0: ch = '\r'; break; case 1: ch = '\n'; break; case 2: ch = '\t'; break; case 3: ch = '\f'; break; case 4: ch = ' '; break; case 5: ch = ','; break; case 6: ch = DQUOTE_CHAR; break; case 7: ch = '\''; break; case 8: ch = BACKSLASH_CH; break; default: ch = (char) r.nextInt(300); break; // default: ch = 'a'; break; } buf[i] = ch; } return new String(buf); } private void setUpTable(final Connection connection) throws SQLException { try (final Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); statement.execute("insert into TEST values(1, 'r1')"); statement.execute("insert into TEST values(2, 'r2')"); } } @Test public void testDelimeterQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("'a,b,c',xyz", sw.toString()); } } @Test public void testDelimeterQuoteNONE() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a,b,c,xyz", sw.toString()); } } @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printComment("This is a comment"); assertEquals("", sw.toString()); } } @Test public void testEOLEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a!rb!nc,x\fy\bz", sw.toString()); } } @Test public void testEOLPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a\rb\nc,x\fy\bz", sw.toString()); } } @Test public void testEOLQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a\rb\nc"); printer.print("x\by\fz"); assertEquals("'a\rb\nc',x\by\fz", sw.toString()); } } @Test public void testEscapeBackslash1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeBackslash2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\r"); } assertEquals("'\\\r'", sw.toString()); } @Test public void testEscapeBackslash3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("X\\\r"); } assertEquals("'X\\\r'", sw.toString()); } @Test public void testEscapeBackslash4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeBackslash5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeNull2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\r"); } assertEquals("\"\\\r\"", sw.toString()); } @Test public void testEscapeNull3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("X\\\r"); } assertEquals("\"X\\\r\"", sw.toString()); } @Test public void testEscapeNull4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testExcelPrintAllArrayOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testHeader() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testHeaderCommentExcel() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.EXCEL; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", sw.toString()); } } @Test public void testHeaderCommentTdf() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.TDF; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", sw.toString()); } } @Test public void testHeaderNotSet() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception { final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), invalidFormat)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); } } assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection();) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { printer.printRecords(resultSet); } } assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { printer.printRecords(resultSet); assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } } } @Test @Ignore public void testJira135_part1() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); printer.printRecord(list); } final String expected = "\"\\\"\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part2() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\n"); printer.printRecord(list); } final String expected = "\"\\n\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part3() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135All() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); list.add("\n"); list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test public void testMultiLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment\non multiple lines"); assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); } } @Test public void testMySqlNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test @Ignore public void testPostgreSqlCsvNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.POSTGRESQL_CSV.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\",NULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_CSV.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.POSTGRESQL_CSV; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test @Ignore public void testPostgreSqlCsvTextOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.POSTGRESQL_TEXT.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_TEXT.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.POSTGRESQL_TEXT; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test public void testMySqlNullStringDefault() { assertEquals("\\N", CSVFormat.MYSQL.getNullString()); } @Test public void testPostgreSQLNullStringDefaultCsv() { assertEquals("", CSVFormat.POSTGRESQL_CSV.getNullString()); } @Test public void testPostgreSQLNullStringDefaultText() { assertEquals("\\N", CSVFormat.POSTGRESQL_TEXT.getNullString()); } @Test(expected = IllegalArgumentException.class) public void testNewCsvPrinterAppendableNullFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), null)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVPrinterNullAppendableFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.printRecord("a", null, "b"); } final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); try (final CSVParser iterable = format.parse(new StringReader(csvString))) { final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } } @Test public void testPlainEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("abc"); assertEquals("abc", sw.toString()); } } @Test public void testPrint() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { printer.printRecord("a", null, "b"); assertEquals("a,NULL,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testDontQuoteEuroFirstChar() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { printer.printRecord(EURO_CH, "Deux"); assertEquals(EURO_CH + ",Deux" + recordSeparator, sw.toString()); } } @Test public void testQuoteCommaFirstChar() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { printer.printRecord(","); assertEquals("\",\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testPrinter3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a, b", "b "); assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); } } @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\nc"); assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter6() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\r\nc"); assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter7() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", null, "b"); assertEquals("a,,b" + recordSeparator, sw.toString()); } } @Test public void testPrintOnePositiveInteger() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { printer.print(Integer.MAX_VALUE); assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); } } @Test public void testPrintToFileWithCharsetUtf16Be() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); } @Test public void testPrintToFileWithDefaultCharset() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testPrintToPathWithDefaultCharset() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testQuoteAll() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { printer.printRecord("a", "b\nc", "d"); assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); } } @Test public void testQuoteNonNumeric() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { printer.printRecord("a", "b\nc", Integer.valueOf(1)); assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); } } @Test public void testRandomDefault() throws Exception { doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomExcel() throws Exception { doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomMySql() throws Exception { doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); } @Test @Ignore public void testRandomPostgreSqlCsv() throws Exception { doRandom(CSVFormat.POSTGRESQL_CSV, ITERATIONS_FOR_RANDOM_TEST); } @Test @Ignore public void testRandomPostgreSqlText() throws Exception { doRandom(CSVFormat.POSTGRESQL_TEXT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomRfc4180() throws Exception { doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomTdf() throws Exception { doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testSingleLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment"); assertEquals("# This is a comment" + recordSeparator, sw.toString()); } } @Test public void testSingleQuoteQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a'b'c"); printer.print("xyz"); assertEquals("'a''b''c',xyz", sw.toString()); } } @Test public void testSkipHeaderRecordFalse() throws IOException { // functionally identical to testHeader, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testSkipHeaderRecordTrue() throws IOException { // functionally identical to testHeaderNotSet, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testTrailingDelimiterOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { printer.printRecord("A", "B"); assertEquals("A,B,\r\n", sw.toString()); } } @Test public void testTrimOffOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { printer.print(" A "); assertEquals("\" A \"", sw.toString()); } } @Test public void testTrimOnOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); assertEquals("A", sw.toString()); } } @Test public void testTrimOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); printer.print(" B "); assertEquals("A,B", sw.toString()); } } private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { return CSVParser.parse(expected, format).getRecords().get(0).values(); } @Test public void testPrintRecordsWithResultSetOneRow() throws IOException, SQLException { try (CSVPrinter csvPrinter = CSVFormat.MYSQL.printer()) { final Value[] valueArray = new Value[0]; final ValueArray valueArrayTwo = ValueArray.get(valueArray); try (ResultSet resultSet = valueArrayTwo.getResultSet()) { csvPrinter.printRecords(resultSet); assertEquals(0, resultSet.getRow()); } } } @Test public void testPrintRecordsWithObjectArray() throws IOException { final CharArrayWriter charArrayWriter = new CharArrayWriter(0); try (CSVPrinter csvPrinter = CSVFormat.INFORMIX_UNLOAD.print(charArrayWriter)) { final HashSet<BatchUpdateException> hashSet = new HashSet<>(); final Object[] objectArray = new Object[6]; objectArray[3] = hashSet; csvPrinter.printRecords(objectArray); } assertEquals(6, charArrayWriter.size()); assertEquals("\n\n\n\n\n\n", charArrayWriter.toString()); } @Test public void testPrintRecordsWithEmptyVector() throws IOException { try (CSVPrinter csvPrinter = CSVFormat.POSTGRESQL_TEXT.printer()) { final Vector<CSVFormatTest.EmptyEnum> vector = new Vector<>(); final int expectedCapacity = 23; vector.setSize(expectedCapacity); csvPrinter.printRecords(vector); assertEquals(expectedCapacity, vector.capacity()); } } @Test public void testCloseWithFlushOn() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT; final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); csvPrinter.close(true); verify(writer, times(1)).flush(); } @Test public void testCloseWithFlushOff() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT; final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); csvPrinter.close(false); verify(writer, never()).flush(); verify(writer, times(1)).close(); } @Test public void testCloseBackwardCompatibility() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT; try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { } verify(writer, never()).flush(); verify(writer, times(1)).close(); } @Test public void testCloseWithCsvFormatAutoFlushOn() throws IOException { // System.out.println("start method"); final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(true); try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { } verify(writer, times(1)).flush(); verify(writer, times(1)).close(); } @Test public void testCloseWithCsvFormatAutoFlushOff() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(false); try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { } verify(writer, never()).flush(); verify(writer, times(1)).close(); } }
@Test public void testNewStringNullInput_CODEC229() { Assert.assertNull(StringUtils.newStringUtf8(null)); Assert.assertNull(StringUtils.newStringIso8859_1(null)); Assert.assertNull(StringUtils.newStringUsAscii(null)); Assert.assertNull(StringUtils.newStringUtf16(null)); Assert.assertNull(StringUtils.newStringUtf16Be(null)); Assert.assertNull(StringUtils.newStringUtf16Le(null)); }
org.apache.commons.codec.binary.StringUtilsTest::testNewStringNullInput_CODEC229
src/test/java/org/apache/commons/codec/binary/StringUtilsTest.java
155
src/test/java/org/apache/commons/codec/binary/StringUtilsTest.java
testNewStringNullInput_CODEC229
/* * 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 java.io.UnsupportedEncodingException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; /** * Tests {@link StringUtils} * * @version $Id$ */ public class StringUtilsTest { private static final byte[] BYTES_FIXTURE = {'a','b','c'}; // This is valid input for UTF-16BE private static final byte[] BYTES_FIXTURE_16BE = {0, 'a', 0, 'b', 0, 'c'}; // This is valid for UTF-16LE private static final byte[] BYTES_FIXTURE_16LE = {'a', 0, 'b', 0, 'c', 0}; private static final String STRING_FIXTURE = "ABC"; /** * We could make the constructor private but there does not seem to be a point to jumping through extra code hoops * to restrict instantiation right now. */ @Test public void testConstructor() { new StringUtils(); } @Test public void testGetBytesIso8859_1() throws UnsupportedEncodingException { final String charsetName = "ISO-8859-1"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesIso8859_1(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } private void testGetBytesUnchecked(final String charsetName) throws UnsupportedEncodingException { final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUnchecked(STRING_FIXTURE, charsetName); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUsAscii() throws UnsupportedEncodingException { final String charsetName = "US-ASCII"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUsAscii(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf16() throws UnsupportedEncodingException { final String charsetName = "UTF-16"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf16Be() throws UnsupportedEncodingException { final String charsetName = "UTF-16BE"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16Be(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf16Le() throws UnsupportedEncodingException { final String charsetName = "UTF-16LE"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16Le(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf8() throws UnsupportedEncodingException { final String charsetName = "UTF-8"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf8(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUncheckedBadName() { try { StringUtils.getBytesUnchecked(STRING_FIXTURE, "UNKNOWN"); Assert.fail("Expected " + IllegalStateException.class.getName()); } catch (final IllegalStateException e) { // Expected } } @Test public void testGetBytesUncheckedNullInput() { Assert.assertNull(StringUtils.getBytesUnchecked(null, "UNKNOWN")); } private void testNewString(final String charsetName) throws UnsupportedEncodingException { final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newString(BYTES_FIXTURE, charsetName); Assert.assertEquals(expected, actual); } @Test public void testNewStringBadEnc() { try { StringUtils.newString(BYTES_FIXTURE, "UNKNOWN"); Assert.fail("Expected " + IllegalStateException.class.getName()); } catch (final IllegalStateException e) { // Expected } } @Test public void testNewStringNullInput() { Assert.assertNull(StringUtils.newString(null, "UNKNOWN")); } @Test public void testNewStringNullInput_CODEC229() { Assert.assertNull(StringUtils.newStringUtf8(null)); Assert.assertNull(StringUtils.newStringIso8859_1(null)); Assert.assertNull(StringUtils.newStringUsAscii(null)); Assert.assertNull(StringUtils.newStringUtf16(null)); Assert.assertNull(StringUtils.newStringUtf16Be(null)); Assert.assertNull(StringUtils.newStringUtf16Le(null)); } @Test public void testNewStringIso8859_1() throws UnsupportedEncodingException { final String charsetName = "ISO-8859-1"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringIso8859_1(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUsAscii() throws UnsupportedEncodingException { final String charsetName = "US-ASCII"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUsAscii(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf16() throws UnsupportedEncodingException { final String charsetName = "UTF-16"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf16(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf16Be() throws UnsupportedEncodingException { final String charsetName = "UTF-16BE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16BE, charsetName); final String actual = StringUtils.newStringUtf16Be(BYTES_FIXTURE_16BE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf16Le() throws UnsupportedEncodingException { final String charsetName = "UTF-16LE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16LE, charsetName); final String actual = StringUtils.newStringUtf16Le(BYTES_FIXTURE_16LE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf8() throws UnsupportedEncodingException { final String charsetName = "UTF-8"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf8(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } }
// You are a professional Java test case writer, please create a test case named `testNewStringNullInput_CODEC229` for the issue `Codec-CODEC-229`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-229 // // ## Issue-Title: // StringUtils.newStringxxx(null) should return null, not NPE // // ## Issue-Description: // // Method calls such as StringUtils.newStringIso8859\_1(null) should return null, not NPE. // // // It looks like this capability was lost with the fix for [~~CODEC-136~~](https://issues.apache.org/jira/browse/CODEC-136 "Use Charset objects when possible, create Charsets class for required character encodings"), i.e. // // <http://svn.apache.org/viewvc?rev=1306366&view=rev> // // // Several methods were changed from // // // // // ``` // return StringUtils.newString(bytes, CharEncoding.xxx); // to // return new String(bytes, Charsets.xxx); // // ``` // // // The new code should have been: // // // // // ``` // return newString(bytes, Charsets.xxx); // // ``` // // // The newString method handles null input. // // // There were no tests for null input so the change in behaviour was missed. // // // // // @Test public void testNewStringNullInput_CODEC229() {
155
17
147
src/test/java/org/apache/commons/codec/binary/StringUtilsTest.java
src/test/java
```markdown ## Issue-ID: Codec-CODEC-229 ## Issue-Title: StringUtils.newStringxxx(null) should return null, not NPE ## Issue-Description: Method calls such as StringUtils.newStringIso8859\_1(null) should return null, not NPE. It looks like this capability was lost with the fix for [~~CODEC-136~~](https://issues.apache.org/jira/browse/CODEC-136 "Use Charset objects when possible, create Charsets class for required character encodings"), i.e. <http://svn.apache.org/viewvc?rev=1306366&view=rev> Several methods were changed from ``` return StringUtils.newString(bytes, CharEncoding.xxx); to return new String(bytes, Charsets.xxx); ``` The new code should have been: ``` return newString(bytes, Charsets.xxx); ``` The newString method handles null input. There were no tests for null input so the change in behaviour was missed. ``` You are a professional Java test case writer, please create a test case named `testNewStringNullInput_CODEC229` for the issue `Codec-CODEC-229`, utilizing the provided issue report information and the following function signature. ```java @Test public void testNewStringNullInput_CODEC229() { ```
147
[ "org.apache.commons.codec.binary.StringUtils" ]
a8da23162d77049002b3a847448e931bb6e3ea0f11bc8d1fb97963906a686d87
@Test public void testNewStringNullInput_CODEC229()
// You are a professional Java test case writer, please create a test case named `testNewStringNullInput_CODEC229` for the issue `Codec-CODEC-229`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Codec-CODEC-229 // // ## Issue-Title: // StringUtils.newStringxxx(null) should return null, not NPE // // ## Issue-Description: // // Method calls such as StringUtils.newStringIso8859\_1(null) should return null, not NPE. // // // It looks like this capability was lost with the fix for [~~CODEC-136~~](https://issues.apache.org/jira/browse/CODEC-136 "Use Charset objects when possible, create Charsets class for required character encodings"), i.e. // // <http://svn.apache.org/viewvc?rev=1306366&view=rev> // // // Several methods were changed from // // // // // ``` // return StringUtils.newString(bytes, CharEncoding.xxx); // to // return new String(bytes, Charsets.xxx); // // ``` // // // The new code should have been: // // // // // ``` // return newString(bytes, Charsets.xxx); // // ``` // // // The newString method handles null input. // // // There were no tests for null input so the change in behaviour was missed. // // // // //
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 java.io.UnsupportedEncodingException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; /** * Tests {@link StringUtils} * * @version $Id$ */ public class StringUtilsTest { private static final byte[] BYTES_FIXTURE = {'a','b','c'}; // This is valid input for UTF-16BE private static final byte[] BYTES_FIXTURE_16BE = {0, 'a', 0, 'b', 0, 'c'}; // This is valid for UTF-16LE private static final byte[] BYTES_FIXTURE_16LE = {'a', 0, 'b', 0, 'c', 0}; private static final String STRING_FIXTURE = "ABC"; /** * We could make the constructor private but there does not seem to be a point to jumping through extra code hoops * to restrict instantiation right now. */ @Test public void testConstructor() { new StringUtils(); } @Test public void testGetBytesIso8859_1() throws UnsupportedEncodingException { final String charsetName = "ISO-8859-1"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesIso8859_1(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } private void testGetBytesUnchecked(final String charsetName) throws UnsupportedEncodingException { final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUnchecked(STRING_FIXTURE, charsetName); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUsAscii() throws UnsupportedEncodingException { final String charsetName = "US-ASCII"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUsAscii(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf16() throws UnsupportedEncodingException { final String charsetName = "UTF-16"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf16Be() throws UnsupportedEncodingException { final String charsetName = "UTF-16BE"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16Be(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf16Le() throws UnsupportedEncodingException { final String charsetName = "UTF-16LE"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf16Le(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUtf8() throws UnsupportedEncodingException { final String charsetName = "UTF-8"; testGetBytesUnchecked(charsetName); final byte[] expected = STRING_FIXTURE.getBytes(charsetName); final byte[] actual = StringUtils.getBytesUtf8(STRING_FIXTURE); Assert.assertTrue(Arrays.equals(expected, actual)); } @Test public void testGetBytesUncheckedBadName() { try { StringUtils.getBytesUnchecked(STRING_FIXTURE, "UNKNOWN"); Assert.fail("Expected " + IllegalStateException.class.getName()); } catch (final IllegalStateException e) { // Expected } } @Test public void testGetBytesUncheckedNullInput() { Assert.assertNull(StringUtils.getBytesUnchecked(null, "UNKNOWN")); } private void testNewString(final String charsetName) throws UnsupportedEncodingException { final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newString(BYTES_FIXTURE, charsetName); Assert.assertEquals(expected, actual); } @Test public void testNewStringBadEnc() { try { StringUtils.newString(BYTES_FIXTURE, "UNKNOWN"); Assert.fail("Expected " + IllegalStateException.class.getName()); } catch (final IllegalStateException e) { // Expected } } @Test public void testNewStringNullInput() { Assert.assertNull(StringUtils.newString(null, "UNKNOWN")); } @Test public void testNewStringNullInput_CODEC229() { Assert.assertNull(StringUtils.newStringUtf8(null)); Assert.assertNull(StringUtils.newStringIso8859_1(null)); Assert.assertNull(StringUtils.newStringUsAscii(null)); Assert.assertNull(StringUtils.newStringUtf16(null)); Assert.assertNull(StringUtils.newStringUtf16Be(null)); Assert.assertNull(StringUtils.newStringUtf16Le(null)); } @Test public void testNewStringIso8859_1() throws UnsupportedEncodingException { final String charsetName = "ISO-8859-1"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringIso8859_1(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUsAscii() throws UnsupportedEncodingException { final String charsetName = "US-ASCII"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUsAscii(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf16() throws UnsupportedEncodingException { final String charsetName = "UTF-16"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf16(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf16Be() throws UnsupportedEncodingException { final String charsetName = "UTF-16BE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16BE, charsetName); final String actual = StringUtils.newStringUtf16Be(BYTES_FIXTURE_16BE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf16Le() throws UnsupportedEncodingException { final String charsetName = "UTF-16LE"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE_16LE, charsetName); final String actual = StringUtils.newStringUtf16Le(BYTES_FIXTURE_16LE); Assert.assertEquals(expected, actual); } @Test public void testNewStringUtf8() throws UnsupportedEncodingException { final String charsetName = "UTF-8"; testNewString(charsetName); final String expected = new String(BYTES_FIXTURE, charsetName); final String actual = StringUtils.newStringUtf8(BYTES_FIXTURE); Assert.assertEquals(expected, actual); } }
public void testCaseInsensitiveUnwrap() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); Person p = mapper.readValue("{ }", Person.class); assertNotNull(p); }
com.fasterxml.jackson.databind.struct.TestUnwrapped::testCaseInsensitiveUnwrap
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
216
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
testCaseInsensitiveUnwrap
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; /** * Unit tests for verifying that basic {@link JsonUnwrapped} annotation * handling works as expected; some more advanced tests are separated out * to more specific test classes (like prefix/suffix handling). */ public class TestUnwrapped extends BaseMapTest { static class Unwrapping { public String name; @JsonUnwrapped public Location location; public Unwrapping() { } public Unwrapping(String str, int x, int y) { name = str; location = new Location(x, y); } } static class DeepUnwrapping { @JsonUnwrapped public Unwrapping unwrapped; public DeepUnwrapping() { } public DeepUnwrapping(String str, int x, int y) { unwrapped = new Unwrapping(str, x, y); } } static class UnwrappingWithCreator { public String name; @JsonUnwrapped public Location location; @JsonCreator public UnwrappingWithCreator(@JsonProperty("name") String n) { name = n; } } final static class Location { public int x; public int y; public Location() { } public Location(int x, int y) { this.x = x; this.y = y; } } // Class with two unwrapped properties static class TwoUnwrappedProperties { @JsonUnwrapped public Location location; @JsonUnwrapped public Name name; public TwoUnwrappedProperties() { } } static class Name { public String first, last; } // [databind#615] static class Parent { @JsonUnwrapped public Child c1; public Parent() { } public Parent(String str) { c1 = new Child(str); } } static class Child { public String field; public Child() { } public Child(String f) { field = f; } } static class Inner { public String animal; } static class Outer { // @JsonProperty @JsonUnwrapped private Inner inner; } // [databind#1493]: case-insensitive handling static class Person { @JsonUnwrapped(prefix = "businessAddress.") public Address businessAddress; } static class Address { public String street; public String addon; public String zip; public String town; public String country; } /* /********************************************************** /* Tests, serialization /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new Unwrapping("Tatu", 1, 2))); } public void testDeepUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new DeepUnwrapping("Tatu", 1, 2))); } /* /********************************************************** /* Tests, deserialization /********************************************************** */ public void testSimpleUnwrappedDeserialize() throws Exception { Unwrapping bean = MAPPER.readValue("{\"name\":\"Tatu\",\"y\":7,\"x\":-13}", Unwrapping.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); } public void testDoubleUnwrapping() throws Exception { TwoUnwrappedProperties bean = MAPPER.readValue("{\"first\":\"Joe\",\"y\":7,\"last\":\"Smith\",\"x\":-13}", TwoUnwrappedProperties.class); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); Name name = bean.name; assertNotNull(name); assertEquals("Joe", name.first); assertEquals("Smith", name.last); } public void testDeepUnwrapping() throws Exception { DeepUnwrapping bean = MAPPER.readValue("{\"x\":3,\"name\":\"Bob\",\"y\":27}", DeepUnwrapping.class); Unwrapping uw = bean.unwrapped; assertNotNull(uw); assertEquals("Bob", uw.name); Location loc = uw.location; assertNotNull(loc); assertEquals(3, loc.x); assertEquals(27, loc.y); } public void testUnwrappedDeserializeWithCreator() throws Exception { UnwrappingWithCreator bean = MAPPER.readValue("{\"x\":1,\"y\":2,\"name\":\"Tatu\"}", UnwrappingWithCreator.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(1, loc.x); assertEquals(2, loc.y); } public void testIssue615() throws Exception { Parent input = new Parent("name"); String json = MAPPER.writeValueAsString(input); Parent output = MAPPER.readValue(json, Parent.class); assertEquals("name", output.c1.field); } public void testUnwrappedAsPropertyIndicator() throws Exception { Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; String actual = MAPPER.writeValueAsString(outer); assertTrue(actual.contains("animal")); assertTrue(actual.contains("Zebra")); assertFalse(actual.contains("inner")); } // [databind#1493]: case-insensitive handling public void testCaseInsensitiveUnwrap() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); Person p = mapper.readValue("{ }", Person.class); assertNotNull(p); } }
// You are a professional Java test case writer, please create a test case named `testCaseInsensitiveUnwrap` for the issue `JacksonDatabind-1493`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1493 // // ## Issue-Title: // ACCEPT_CASE_INSENSITIVE_PROPERTIES fails with @JsonUnwrapped // // ## Issue-Description: // (note: moved from [FasterXML/jackson-dataformat-csv#133](https://github.com/FasterXML/jackson-dataformat-csv/issues/133)) // // // When trying to deserialize type like: // // // // ``` // public class Person { // @JsonUnwrapped(prefix = "businessAddress.") // public Address businessAddress; // } // // public class Address { // public String street; // public String addon; // public String zip = ""; // public String town; // public String country; // } // ``` // // with case-insensitive mapper (`mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);`) I get exception: // // // // ``` // java.util.NoSuchElementException: No entry 'businessAddress' found, can't remove // at com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap.remove(BeanPropertyMap.java:447) // at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:534) // at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293) // ... // // ``` // // // public void testCaseInsensitiveUnwrap() throws Exception {
216
// [databind#1493]: case-insensitive handling
70
210
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1493 ## Issue-Title: ACCEPT_CASE_INSENSITIVE_PROPERTIES fails with @JsonUnwrapped ## Issue-Description: (note: moved from [FasterXML/jackson-dataformat-csv#133](https://github.com/FasterXML/jackson-dataformat-csv/issues/133)) When trying to deserialize type like: ``` public class Person { @JsonUnwrapped(prefix = "businessAddress.") public Address businessAddress; } public class Address { public String street; public String addon; public String zip = ""; public String town; public String country; } ``` with case-insensitive mapper (`mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);`) I get exception: ``` java.util.NoSuchElementException: No entry 'businessAddress' found, can't remove at com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap.remove(BeanPropertyMap.java:447) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:534) at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293) ... ``` ``` You are a professional Java test case writer, please create a test case named `testCaseInsensitiveUnwrap` for the issue `JacksonDatabind-1493`, utilizing the provided issue report information and the following function signature. ```java public void testCaseInsensitiveUnwrap() throws Exception { ```
210
[ "com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap" ]
a946e4fe1679d4899bb78afb37e5cc6edce4e887efebc76ae3dd8216d32186c9
public void testCaseInsensitiveUnwrap() throws Exception
// You are a professional Java test case writer, please create a test case named `testCaseInsensitiveUnwrap` for the issue `JacksonDatabind-1493`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1493 // // ## Issue-Title: // ACCEPT_CASE_INSENSITIVE_PROPERTIES fails with @JsonUnwrapped // // ## Issue-Description: // (note: moved from [FasterXML/jackson-dataformat-csv#133](https://github.com/FasterXML/jackson-dataformat-csv/issues/133)) // // // When trying to deserialize type like: // // // // ``` // public class Person { // @JsonUnwrapped(prefix = "businessAddress.") // public Address businessAddress; // } // // public class Address { // public String street; // public String addon; // public String zip = ""; // public String town; // public String country; // } // ``` // // with case-insensitive mapper (`mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);`) I get exception: // // // // ``` // java.util.NoSuchElementException: No entry 'businessAddress' found, can't remove // at com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap.remove(BeanPropertyMap.java:447) // at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:534) // at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293) // ... // // ``` // // //
JacksonDatabind
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; /** * Unit tests for verifying that basic {@link JsonUnwrapped} annotation * handling works as expected; some more advanced tests are separated out * to more specific test classes (like prefix/suffix handling). */ public class TestUnwrapped extends BaseMapTest { static class Unwrapping { public String name; @JsonUnwrapped public Location location; public Unwrapping() { } public Unwrapping(String str, int x, int y) { name = str; location = new Location(x, y); } } static class DeepUnwrapping { @JsonUnwrapped public Unwrapping unwrapped; public DeepUnwrapping() { } public DeepUnwrapping(String str, int x, int y) { unwrapped = new Unwrapping(str, x, y); } } static class UnwrappingWithCreator { public String name; @JsonUnwrapped public Location location; @JsonCreator public UnwrappingWithCreator(@JsonProperty("name") String n) { name = n; } } final static class Location { public int x; public int y; public Location() { } public Location(int x, int y) { this.x = x; this.y = y; } } // Class with two unwrapped properties static class TwoUnwrappedProperties { @JsonUnwrapped public Location location; @JsonUnwrapped public Name name; public TwoUnwrappedProperties() { } } static class Name { public String first, last; } // [databind#615] static class Parent { @JsonUnwrapped public Child c1; public Parent() { } public Parent(String str) { c1 = new Child(str); } } static class Child { public String field; public Child() { } public Child(String f) { field = f; } } static class Inner { public String animal; } static class Outer { // @JsonProperty @JsonUnwrapped private Inner inner; } // [databind#1493]: case-insensitive handling static class Person { @JsonUnwrapped(prefix = "businessAddress.") public Address businessAddress; } static class Address { public String street; public String addon; public String zip; public String town; public String country; } /* /********************************************************** /* Tests, serialization /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new Unwrapping("Tatu", 1, 2))); } public void testDeepUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new DeepUnwrapping("Tatu", 1, 2))); } /* /********************************************************** /* Tests, deserialization /********************************************************** */ public void testSimpleUnwrappedDeserialize() throws Exception { Unwrapping bean = MAPPER.readValue("{\"name\":\"Tatu\",\"y\":7,\"x\":-13}", Unwrapping.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); } public void testDoubleUnwrapping() throws Exception { TwoUnwrappedProperties bean = MAPPER.readValue("{\"first\":\"Joe\",\"y\":7,\"last\":\"Smith\",\"x\":-13}", TwoUnwrappedProperties.class); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); Name name = bean.name; assertNotNull(name); assertEquals("Joe", name.first); assertEquals("Smith", name.last); } public void testDeepUnwrapping() throws Exception { DeepUnwrapping bean = MAPPER.readValue("{\"x\":3,\"name\":\"Bob\",\"y\":27}", DeepUnwrapping.class); Unwrapping uw = bean.unwrapped; assertNotNull(uw); assertEquals("Bob", uw.name); Location loc = uw.location; assertNotNull(loc); assertEquals(3, loc.x); assertEquals(27, loc.y); } public void testUnwrappedDeserializeWithCreator() throws Exception { UnwrappingWithCreator bean = MAPPER.readValue("{\"x\":1,\"y\":2,\"name\":\"Tatu\"}", UnwrappingWithCreator.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(1, loc.x); assertEquals(2, loc.y); } public void testIssue615() throws Exception { Parent input = new Parent("name"); String json = MAPPER.writeValueAsString(input); Parent output = MAPPER.readValue(json, Parent.class); assertEquals("name", output.c1.field); } public void testUnwrappedAsPropertyIndicator() throws Exception { Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; String actual = MAPPER.writeValueAsString(outer); assertTrue(actual.contains("animal")); assertTrue(actual.contains("Zebra")); assertFalse(actual.contains("inner")); } // [databind#1493]: case-insensitive handling public void testCaseInsensitiveUnwrap() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); Person p = mapper.readValue("{ }", Person.class); assertNotNull(p); } }
public void testNan() { assertXPathValue(context, "$nan > $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = $nan", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$nan > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 1", Boolean.FALSE, Boolean.class); }
org.apache.commons.jxpath.ri.compiler.CoreOperationTest::testNan
src/test/org/apache/commons/jxpath/ri/compiler/CoreOperationTest.java
124
src/test/org/apache/commons/jxpath/ri/compiler/CoreOperationTest.java
testNan
/* * 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.jxpath.ri.compiler; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.Variables; /** * Test basic functionality of JXPath - infoset types, * operations. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public class CoreOperationTest extends JXPathTestCase { private JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public CoreOperationTest(String name) { super(name); } public void setUp() { if (context == null) { context = JXPathContext.newContext(null); Variables vars = context.getVariables(); vars.declareVariable("integer", new Integer(1)); vars.declareVariable("array", new double[] { 0.25, 0.5, 0.75 }); vars.declareVariable("nan", new Double(Double.NaN)); } } public void testInfoSetTypes() { // Numbers assertXPathValue(context, "1", new Double(1.0)); assertXPathPointer(context, "1", "1"); assertXPathValueIterator(context, "1", list(new Double(1.0))); assertXPathPointerIterator(context, "1", list("1")); assertXPathValue(context, "-1", new Double(-1.0)); assertXPathValue(context, "2 + 2", new Double(4.0)); assertXPathValue(context, "3 - 2", new Double(1.0)); assertXPathValue(context, "1 + 2 + 3 - 4 + 5", new Double(7.0)); assertXPathValue(context, "3 * 2", new Double(3.0 * 2.0)); assertXPathValue(context, "3 div 2", new Double(3.0 / 2.0)); assertXPathValue(context, "5 mod 2", new Double(1.0)); // This test produces a different result with Xalan? assertXPathValue(context, "5.9 mod 2.1", new Double(1.0)); assertXPathValue(context, "5 mod -2", new Double(1.0)); assertXPathValue(context, "-5 mod 2", new Double(-1.0)); assertXPathValue(context, "-5 mod -2", new Double(-1.0)); assertXPathValue(context, "1 < 2", Boolean.TRUE); assertXPathValue(context, "1 > 2", Boolean.FALSE); assertXPathValue(context, "1 <= 1", Boolean.TRUE); assertXPathValue(context, "1 >= 2", Boolean.FALSE); assertXPathValue(context, "3 > 2 > 1", Boolean.FALSE); assertXPathValue(context, "3 > 2 and 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 > 2 and 2 < 1", Boolean.FALSE); assertXPathValue(context, "3 < 2 or 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 < 2 or 2 < 1", Boolean.FALSE); assertXPathValue(context, "1 = 1", Boolean.TRUE); assertXPathValue(context, "1 = '1'", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 2 > 3", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 0", Boolean.TRUE); assertXPathValue(context, "1 = 2", Boolean.FALSE); assertXPathValue(context, "$integer", new Double(1), Double.class); assertXPathValue(context, "2 + 3", "5.0", String.class); assertXPathValue(context, "2 + 3", Boolean.TRUE, boolean.class); assertXPathValue(context, "'true'", Boolean.TRUE, Boolean.class); } public void testNodeSetOperations() { assertXPathValue(context, "$array > 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array >= 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array = 0.25", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.5", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.50000", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.75", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array < 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array <= 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array < 0", Boolean.FALSE, Boolean.class); } public void testNan() { assertXPathValue(context, "$nan > $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = $nan", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$nan > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 1", Boolean.FALSE, Boolean.class); } }
// You are a professional Java test case writer, please create a test case named `testNan` for the issue `JxPath-JXPATH-95`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JxPath-JXPATH-95 // // ## Issue-Title: // Comparing with NaN is incorrect // // ## Issue-Description: // // 'NaN' > 'NaN' is true, but should be FALSE // // // // // public void testNan() {
124
8
114
src/test/org/apache/commons/jxpath/ri/compiler/CoreOperationTest.java
src/test
```markdown ## Issue-ID: JxPath-JXPATH-95 ## Issue-Title: Comparing with NaN is incorrect ## Issue-Description: 'NaN' > 'NaN' is true, but should be FALSE ``` You are a professional Java test case writer, please create a test case named `testNan` for the issue `JxPath-JXPATH-95`, utilizing the provided issue report information and the following function signature. ```java public void testNan() { ```
114
[ "org.apache.commons.jxpath.ri.compiler.CoreOperationRelationalExpression" ]
aa92c17cf84aba9051ea17a49235d92e0fbf76da585c4584c36beff583b78298
public void testNan()
// You are a professional Java test case writer, please create a test case named `testNan` for the issue `JxPath-JXPATH-95`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JxPath-JXPATH-95 // // ## Issue-Title: // Comparing with NaN is incorrect // // ## Issue-Description: // // 'NaN' > 'NaN' is true, but should be FALSE // // // // //
JxPath
/* * 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.jxpath.ri.compiler; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.Variables; /** * Test basic functionality of JXPath - infoset types, * operations. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public class CoreOperationTest extends JXPathTestCase { private JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public CoreOperationTest(String name) { super(name); } public void setUp() { if (context == null) { context = JXPathContext.newContext(null); Variables vars = context.getVariables(); vars.declareVariable("integer", new Integer(1)); vars.declareVariable("array", new double[] { 0.25, 0.5, 0.75 }); vars.declareVariable("nan", new Double(Double.NaN)); } } public void testInfoSetTypes() { // Numbers assertXPathValue(context, "1", new Double(1.0)); assertXPathPointer(context, "1", "1"); assertXPathValueIterator(context, "1", list(new Double(1.0))); assertXPathPointerIterator(context, "1", list("1")); assertXPathValue(context, "-1", new Double(-1.0)); assertXPathValue(context, "2 + 2", new Double(4.0)); assertXPathValue(context, "3 - 2", new Double(1.0)); assertXPathValue(context, "1 + 2 + 3 - 4 + 5", new Double(7.0)); assertXPathValue(context, "3 * 2", new Double(3.0 * 2.0)); assertXPathValue(context, "3 div 2", new Double(3.0 / 2.0)); assertXPathValue(context, "5 mod 2", new Double(1.0)); // This test produces a different result with Xalan? assertXPathValue(context, "5.9 mod 2.1", new Double(1.0)); assertXPathValue(context, "5 mod -2", new Double(1.0)); assertXPathValue(context, "-5 mod 2", new Double(-1.0)); assertXPathValue(context, "-5 mod -2", new Double(-1.0)); assertXPathValue(context, "1 < 2", Boolean.TRUE); assertXPathValue(context, "1 > 2", Boolean.FALSE); assertXPathValue(context, "1 <= 1", Boolean.TRUE); assertXPathValue(context, "1 >= 2", Boolean.FALSE); assertXPathValue(context, "3 > 2 > 1", Boolean.FALSE); assertXPathValue(context, "3 > 2 and 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 > 2 and 2 < 1", Boolean.FALSE); assertXPathValue(context, "3 < 2 or 2 > 1", Boolean.TRUE); assertXPathValue(context, "3 < 2 or 2 < 1", Boolean.FALSE); assertXPathValue(context, "1 = 1", Boolean.TRUE); assertXPathValue(context, "1 = '1'", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 2 > 3", Boolean.TRUE); assertXPathValue(context, "1 > 2 = 0", Boolean.TRUE); assertXPathValue(context, "1 = 2", Boolean.FALSE); assertXPathValue(context, "$integer", new Double(1), Double.class); assertXPathValue(context, "2 + 3", "5.0", String.class); assertXPathValue(context, "2 + 3", Boolean.TRUE, boolean.class); assertXPathValue(context, "'true'", Boolean.TRUE, Boolean.class); } public void testNodeSetOperations() { assertXPathValue(context, "$array > 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array >= 0", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array = 0.25", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.5", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.50000", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 0.75", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array < 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array <= 1", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$array = 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$array < 0", Boolean.FALSE, Boolean.class); } public void testNan() { assertXPathValue(context, "$nan > $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < $nan", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = $nan", Boolean.TRUE, Boolean.class); assertXPathValue(context, "$nan > 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 0", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan > 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan < 1", Boolean.FALSE, Boolean.class); assertXPathValue(context, "$nan = 1", Boolean.FALSE, Boolean.class); } }
@Test public void attributeWithBrackets() { String html = "<div data='End]'>One</div> <div data='[Another)]]'>Two</div>"; Document doc = Jsoup.parse(html); assertEquals("One", doc.select("div[data='End]'").first().text()); assertEquals("Two", doc.select("div[data='[Another)]]'").first().text()); }
org.jsoup.select.SelectorTest::attributeWithBrackets
src/test/java/org/jsoup/select/SelectorTest.java
669
src/test/java/org/jsoup/select/SelectorTest.java
attributeWithBrackets
package org.jsoup.select; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.junit.Test; import static org.junit.Assert.*; /** * Tests that the selector selects correctly. * * @author Jonathan Hedley, [email protected] */ public class SelectorTest { @Test public void testByTag() { Elements els = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("div"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("3", els.get(2).id()); Elements none = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("span"); assertEquals(0, none.size()); } @Test public void testById() { Elements els = Jsoup.parse("<div><p id=foo>Hello</p><p id=foo>Foo two!</p></div>").select("#foo"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("Foo two!", els.get(1).text()); Elements none = Jsoup.parse("<div id=1></div>").select("#foo"); assertEquals(0, none.size()); } @Test public void testByClass() { Elements els = Jsoup.parse("<p id=0 class='one two'><p id=1 class='one'><p id=2 class='two'>").select("p.one"); assertEquals(2, els.size()); assertEquals("0", els.get(0).id()); assertEquals("1", els.get(1).id()); Elements none = Jsoup.parse("<div class='one'></div>").select(".foo"); assertEquals(0, none.size()); Elements els2 = Jsoup.parse("<div class='One-Two'></div>").select(".one-two"); assertEquals(1, els2.size()); } @Test public void testByAttribute() { String h = "<div Title=Foo /><div Title=Bar /><div Style=Qux /><div title=Bam /><div title=SLAM />" + "<div data-name='with spaces'/>"; Document doc = Jsoup.parse(h); Elements withTitle = doc.select("[title]"); assertEquals(4, withTitle.size()); Elements foo = doc.select("[title=foo]"); assertEquals(1, foo.size()); Elements foo2 = doc.select("[title=\"foo\"]"); assertEquals(1, foo2.size()); Elements foo3 = doc.select("[title=\"Foo\"]"); assertEquals(1, foo3.size()); Elements dataName = doc.select("[data-name=\"with spaces\"]"); assertEquals(1, dataName.size()); assertEquals("with spaces", dataName.first().attr("data-name")); Elements not = doc.select("div[title!=bar]"); assertEquals(5, not.size()); assertEquals("Foo", not.first().attr("title")); Elements starts = doc.select("[title^=ba]"); assertEquals(2, starts.size()); assertEquals("Bar", starts.first().attr("title")); assertEquals("Bam", starts.last().attr("title")); Elements ends = doc.select("[title$=am]"); assertEquals(2, ends.size()); assertEquals("Bam", ends.first().attr("title")); assertEquals("SLAM", ends.last().attr("title")); Elements contains = doc.select("[title*=a]"); assertEquals(3, contains.size()); assertEquals("Bar", contains.first().attr("title")); assertEquals("SLAM", contains.last().attr("title")); } @Test public void testNamespacedTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div> <abc:def class=bold id=2>There</abc:def>"); Elements byTag = doc.select("abc|def"); assertEquals(2, byTag.size()); assertEquals("1", byTag.first().id()); assertEquals("2", byTag.last().id()); Elements byAttr = doc.select(".bold"); assertEquals(1, byAttr.size()); assertEquals("2", byAttr.last().id()); Elements byTagAttr = doc.select("abc|def.bold"); assertEquals(1, byTagAttr.size()); assertEquals("2", byTagAttr.last().id()); Elements byContains = doc.select("abc|def:contains(e)"); assertEquals(2, byContains.size()); assertEquals("1", byContains.first().id()); assertEquals("2", byContains.last().id()); } @Test public void testByAttributeStarting() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup>Hello</div><p data-val=5 id=2>There</p><p id=3>No</p>"); Elements withData = doc.select("[^data-]"); assertEquals(2, withData.size()); assertEquals("1", withData.first().id()); assertEquals("2", withData.last().id()); withData = doc.select("p[^data-]"); assertEquals(1, withData.size()); assertEquals("2", withData.first().id()); } @Test public void testByAttributeRegex() { Document doc = Jsoup.parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif><img></p>"); Elements imgs = doc.select("img[src~=(?i)\\.(png|jpe?g)]"); assertEquals(3, imgs.size()); assertEquals("1", imgs.get(0).id()); assertEquals("2", imgs.get(1).id()); assertEquals("3", imgs.get(2).id()); } @Test public void testByAttributeRegexCharacterClass() { Document doc = Jsoup.parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif id=4></p>"); Elements imgs = doc.select("img[src~=[o]]"); assertEquals(2, imgs.size()); assertEquals("1", imgs.get(0).id()); assertEquals("4", imgs.get(1).id()); } @Test public void testByAttributeRegexCombined() { Document doc = Jsoup.parse("<div><table class=x><td>Hello</td></table></div>"); Elements els = doc.select("div table[class~=x|y]"); assertEquals(1, els.size()); assertEquals("Hello", els.text()); } @Test public void testCombinedWithContains() { Document doc = Jsoup.parse("<p id=1>One</p><p>Two +</p><p>Three +</p>"); Elements els = doc.select("p#1 + :contains(+)"); assertEquals(1, els.size()); assertEquals("Two +", els.text()); assertEquals("p", els.first().tagName()); } @Test public void testAllElements() { String h = "<div><p>Hello</p><p><b>there</b></p></div>"; Document doc = Jsoup.parse(h); Elements allDoc = doc.select("*"); Elements allUnderDiv = doc.select("div *"); assertEquals(8, allDoc.size()); assertEquals(3, allUnderDiv.size()); assertEquals("p", allUnderDiv.first().tagName()); } @Test public void testAllWithClass() { String h = "<p class=first>One<p class=first>Two<p>Three"; Document doc = Jsoup.parse(h); Elements ps = doc.select("*.first"); assertEquals(2, ps.size()); } @Test public void testGroupOr() { String h = "<div title=foo /><div title=bar /><div /><p></p><img /><span title=qux>"; Document doc = Jsoup.parse(h); Elements els = doc.select("p,div,[title]"); assertEquals(5, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("foo", els.get(0).attr("title")); assertEquals("div", els.get(1).tagName()); assertEquals("bar", els.get(1).attr("title")); assertEquals("div", els.get(2).tagName()); assertTrue(els.get(2).attr("title").length() == 0); // missing attributes come back as empty string assertFalse(els.get(2).hasAttr("title")); assertEquals("p", els.get(3).tagName()); assertEquals("span", els.get(4).tagName()); } @Test public void testGroupOrAttribute() { String h = "<div id=1 /><div id=2 /><div title=foo /><div title=bar />"; Elements els = Jsoup.parse(h).select("[id],[title=foo]"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("foo", els.get(2).attr("title")); } @Test public void descendant() { String h = "<div class=head><p class=first>Hello</p><p>There</p></div><p>None</p>"; Document doc = Jsoup.parse(h); Element root = doc.getElementsByClass("head").first(); Elements els = root.select(".head p"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("There", els.get(1).text()); Elements p = root.select("p.first"); assertEquals(1, p.size()); assertEquals("Hello", p.get(0).text()); Elements empty = root.select("p .first"); // self, not descend, should not match assertEquals(0, empty.size()); Elements aboveRoot = root.select("body div.head"); assertEquals(0, aboveRoot.size()); } @Test public void and() { String h = "<div id=1 class='foo bar' title=bar name=qux><p class=foo title=bar>Hello</p></div"; Document doc = Jsoup.parse(h); Elements div = doc.select("div.foo"); assertEquals(1, div.size()); assertEquals("div", div.first().tagName()); Elements p = doc.select("div .foo"); // space indicates like "div *.foo" assertEquals(1, p.size()); assertEquals("p", p.first().tagName()); Elements div2 = doc.select("div#1.foo.bar[title=bar][name=qux]"); // very specific! assertEquals(1, div2.size()); assertEquals("div", div2.first().tagName()); Elements p2 = doc.select("div *.foo"); // space indicates like "div *.foo" assertEquals(1, p2.size()); assertEquals("p", p2.first().tagName()); } @Test public void deeperDescendant() { String h = "<div class=head><p><span class=first>Hello</div><div class=head><p class=first><span>Another</span><p>Again</div>"; Document doc = Jsoup.parse(h); Element root = doc.getElementsByClass("head").first(); Elements els = root.select("div p .first"); assertEquals(1, els.size()); assertEquals("Hello", els.first().text()); assertEquals("span", els.first().tagName()); Elements aboveRoot = root.select("body p .first"); assertEquals(0, aboveRoot.size()); } @Test public void parentChildElement() { String h = "<div id=1><div id=2><div id = 3></div></div></div><div id=4></div>"; Document doc = Jsoup.parse(h); Elements divs = doc.select("div > div"); assertEquals(2, divs.size()); assertEquals("2", divs.get(0).id()); // 2 is child of 1 assertEquals("3", divs.get(1).id()); // 3 is child of 2 Elements div2 = doc.select("div#1 > div"); assertEquals(1, div2.size()); assertEquals("2", div2.get(0).id()); } @Test public void parentWithClassChild() { String h = "<h1 class=foo><a href=1 /></h1><h1 class=foo><a href=2 class=bar /></h1><h1><a href=3 /></h1>"; Document doc = Jsoup.parse(h); Elements allAs = doc.select("h1 > a"); assertEquals(3, allAs.size()); assertEquals("a", allAs.first().tagName()); Elements fooAs = doc.select("h1.foo > a"); assertEquals(2, fooAs.size()); assertEquals("a", fooAs.first().tagName()); Elements barAs = doc.select("h1.foo > a.bar"); assertEquals(1, barAs.size()); } @Test public void parentChildStar() { String h = "<div id=1><p>Hello<p><b>there</b></p></div><div id=2><span>Hi</span></div>"; Document doc = Jsoup.parse(h); Elements divChilds = doc.select("div > *"); assertEquals(3, divChilds.size()); assertEquals("p", divChilds.get(0).tagName()); assertEquals("p", divChilds.get(1).tagName()); assertEquals("span", divChilds.get(2).tagName()); } @Test public void multiChildDescent() { String h = "<div id=foo><h1 class=bar><a href=http://example.com/>One</a></h1></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select("div#foo > h1.bar > a[href*=example]"); assertEquals(1, els.size()); assertEquals("a", els.first().tagName()); } @Test public void caseInsensitive() { String h = "<dIv tItle=bAr><div>"; // mixed case so a simple toLowerCase() on value doesn't catch Document doc = Jsoup.parse(h); assertEquals(2, doc.select("DIV").size()); assertEquals(1, doc.select("DIV[TITLE]").size()); assertEquals(1, doc.select("DIV[TITLE=BAR]").size()); assertEquals(0, doc.select("DIV[TITLE=BARBARELLA").size()); } @Test public void adjacentSiblings() { String h = "<ol><li>One<li>Two<li>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li + li"); assertEquals(2, sibs.size()); assertEquals("Two", sibs.get(0).text()); assertEquals("Three", sibs.get(1).text()); } @Test public void adjacentSiblingsWithId() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li#1 + li#2"); assertEquals(1, sibs.size()); assertEquals("Two", sibs.get(0).text()); } @Test public void notAdjacent() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li#1 + li#3"); assertEquals(0, sibs.size()); } @Test public void mixCombinator() { String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("body > div.foo li + li"); assertEquals(2, sibs.size()); assertEquals("Two", sibs.get(0).text()); assertEquals("Three", sibs.get(1).text()); } @Test public void mixCombinatorGroup() { String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".foo > ol, ol > li + li"); assertEquals(3, els.size()); assertEquals("ol", els.get(0).tagName()); assertEquals("Two", els.get(1).text()); assertEquals("Three", els.get(2).text()); } @Test public void generalSiblings() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements els = doc.select("#1 ~ #3"); assertEquals(1, els.size()); assertEquals("Three", els.first().text()); } // for http://github.com/jhy/jsoup/issues#issue/10 @Test public void testCharactersInIdAndClass() { // using CSS spec for identifiers (id and class): a-z0-9, -, _. NOT . (which is OK in html spec, but not css) String h = "<div><p id='a1-foo_bar'>One</p><p class='b2-qux_bif'>Two</p></div>"; Document doc = Jsoup.parse(h); Element el1 = doc.getElementById("a1-foo_bar"); assertEquals("One", el1.text()); Element el2 = doc.getElementsByClass("b2-qux_bif").first(); assertEquals("Two", el2.text()); Element el3 = doc.select("#a1-foo_bar").first(); assertEquals("One", el3.text()); Element el4 = doc.select(".b2-qux_bif").first(); assertEquals("Two", el4.text()); } // for http://github.com/jhy/jsoup/issues#issue/13 @Test public void testSupportsLeadingCombinator() { String h = "<div><p><span>One</span><span>Two</span></p></div>"; Document doc = Jsoup.parse(h); Element p = doc.select("div > p").first(); Elements spans = p.select("> span"); assertEquals(2, spans.size()); assertEquals("One", spans.first().text()); // make sure doesn't get nested h = "<div id=1><div id=2><div id=3></div></div></div>"; doc = Jsoup.parse(h); Element div = doc.select("div").select(" > div").first(); assertEquals("2", div.id()); } @Test public void testPseudoLessThan() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:lt(2)"); assertEquals(3, ps.size()); assertEquals("One", ps.get(0).text()); assertEquals("Two", ps.get(1).text()); assertEquals("Four", ps.get(2).text()); } @Test public void testPseudoGreaterThan() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</p></div><div><p>Four</p>"); Elements ps = doc.select("div p:gt(0)"); assertEquals(2, ps.size()); assertEquals("Two", ps.get(0).text()); assertEquals("Three", ps.get(1).text()); } @Test public void testPseudoEquals() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:eq(0)"); assertEquals(2, ps.size()); assertEquals("One", ps.get(0).text()); assertEquals("Four", ps.get(1).text()); Elements ps2 = doc.select("div:eq(0) p:eq(0)"); assertEquals(1, ps2.size()); assertEquals("One", ps2.get(0).text()); assertEquals("p", ps2.get(0).tagName()); } @Test public void testPseudoBetween() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:gt(0):lt(2)"); assertEquals(1, ps.size()); assertEquals("Two", ps.get(0).text()); } @Test public void testPseudoCombined() { Document doc = Jsoup.parse("<div class='foo'><p>One</p><p>Two</p></div><div><p>Three</p><p>Four</p></div>"); Elements ps = doc.select("div.foo p:gt(0)"); assertEquals(1, ps.size()); assertEquals("Two", ps.get(0).text()); } @Test public void testPseudoHas() { Document doc = Jsoup.parse("<div id=0><p><span>Hello</span></p></div> <div id=1><span class=foo>There</span></div> <div id=2><p>Not</p></div>"); Elements divs1 = doc.select("div:has(span)"); assertEquals(2, divs1.size()); assertEquals("0", divs1.get(0).id()); assertEquals("1", divs1.get(1).id()); Elements divs2 = doc.select("div:has([class]"); assertEquals(1, divs2.size()); assertEquals("1", divs2.get(0).id()); Elements divs3 = doc.select("div:has(span, p)"); assertEquals(3, divs3.size()); assertEquals("0", divs3.get(0).id()); assertEquals("1", divs3.get(1).id()); assertEquals("2", divs3.get(2).id()); Elements els1 = doc.body().select(":has(p)"); assertEquals(3, els1.size()); // body, div, dib assertEquals("body", els1.first().tagName()); assertEquals("0", els1.get(1).id()); assertEquals("2", els1.get(2).id()); } @Test public void testNestedHas() { Document doc = Jsoup.parse("<div><p><span>One</span></p></div> <div><p>Two</p></div>"); Elements divs = doc.select("div:has(p:has(span))"); assertEquals(1, divs.size()); assertEquals("One", divs.first().text()); // test matches in has divs = doc.select("div:has(p:matches((?i)two))"); assertEquals(1, divs.size()); assertEquals("div", divs.first().tagName()); assertEquals("Two", divs.first().text()); // test contains in has divs = doc.select("div:has(p:contains(two))"); assertEquals(1, divs.size()); assertEquals("div", divs.first().tagName()); assertEquals("Two", divs.first().text()); } @Test public void testPseudoContains() { Document doc = Jsoup.parse("<div><p>The Rain.</p> <p class=light>The <i>rain</i>.</p> <p>Rain, the.</p></div>"); Elements ps1 = doc.select("p:contains(Rain)"); assertEquals(3, ps1.size()); Elements ps2 = doc.select("p:contains(the rain)"); assertEquals(2, ps2.size()); assertEquals("The Rain.", ps2.first().html()); assertEquals("The <i>rain</i>.", ps2.last().html()); Elements ps3 = doc.select("p:contains(the Rain):has(i)"); assertEquals(1, ps3.size()); assertEquals("light", ps3.first().className()); Elements ps4 = doc.select(".light:contains(rain)"); assertEquals(1, ps4.size()); assertEquals("light", ps3.first().className()); Elements ps5 = doc.select(":contains(rain)"); assertEquals(8, ps5.size()); // html, body, div,... } @Test public void testPsuedoContainsWithParentheses() { Document doc = Jsoup.parse("<div><p id=1>This (is good)</p><p id=2>This is bad)</p>"); Elements ps1 = doc.select("p:contains(this (is good))"); assertEquals(1, ps1.size()); assertEquals("1", ps1.first().id()); Elements ps2 = doc.select("p:contains(this is bad\\))"); assertEquals(1, ps2.size()); assertEquals("2", ps2.first().id()); } @Test public void containsOwn() { Document doc = Jsoup.parse("<p id=1>Hello <b>there</b> now</p>"); Elements ps = doc.select("p:containsOwn(Hello now)"); assertEquals(1, ps.size()); assertEquals("1", ps.first().id()); assertEquals(0, doc.select("p:containsOwn(there)").size()); } @Test public void testMatches() { Document doc = Jsoup.parse("<p id=1>The <i>Rain</i></p> <p id=2>There are 99 bottles.</p> <p id=3>Harder (this)</p> <p id=4>Rain</p>"); Elements p1 = doc.select("p:matches(The rain)"); // no match, case sensitive assertEquals(0, p1.size()); Elements p2 = doc.select("p:matches((?i)the rain)"); // case insense. should include root, html, body assertEquals(1, p2.size()); assertEquals("1", p2.first().id()); Elements p4 = doc.select("p:matches((?i)^rain$)"); // bounding assertEquals(1, p4.size()); assertEquals("4", p4.first().id()); Elements p5 = doc.select("p:matches(\\d+)"); assertEquals(1, p5.size()); assertEquals("2", p5.first().id()); Elements p6 = doc.select("p:matches(\\w+\\s+\\(\\w+\\))"); // test bracket matching assertEquals(1, p6.size()); assertEquals("3", p6.first().id()); Elements p7 = doc.select("p:matches((?i)the):has(i)"); // multi assertEquals(1, p7.size()); assertEquals("1", p7.first().id()); } @Test public void matchesOwn() { Document doc = Jsoup.parse("<p id=1>Hello <b>there</b> now</p>"); Elements p1 = doc.select("p:matchesOwn((?i)hello now)"); assertEquals(1, p1.size()); assertEquals("1", p1.first().id()); assertEquals(0, doc.select("p:matchesOwn(there)").size()); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def id=2>There</abc-def>"); Elements el1 = doc.select("abc_def"); assertEquals(1, el1.size()); assertEquals("1", el1.first().id()); Elements el2 = doc.select("abc-def"); assertEquals(1, el2.size()); assertEquals("2", el2.first().id()); } @Test public void notParas() { Document doc = Jsoup.parse("<p id=1>One</p> <p>Two</p> <p><span>Three</span></p>"); Elements el1 = doc.select("p:not([id=1])"); assertEquals(2, el1.size()); assertEquals("Two", el1.first().text()); assertEquals("Three", el1.last().text()); Elements el2 = doc.select("p:not(:has(span))"); assertEquals(2, el2.size()); assertEquals("One", el2.first().text()); assertEquals("Two", el2.last().text()); } @Test public void notAll() { Document doc = Jsoup.parse("<p>Two</p> <p><span>Three</span></p>"); Elements el1 = doc.body().select(":not(p)"); // should just be the span assertEquals(2, el1.size()); assertEquals("body", el1.first().tagName()); assertEquals("span", el1.last().tagName()); } @Test public void notClass() { Document doc = Jsoup.parse("<div class=left>One</div><div class=right id=1><p>Two</p></div>"); Elements el1 = doc.select("div:not(.left)"); assertEquals(1, el1.size()); assertEquals("1", el1.first().id()); } @Test public void handlesCommasInSelector() { Document doc = Jsoup.parse("<p name='1,2'>One</p><div>Two</div><ol><li>123</li><li>Text</li></ol>"); Elements ps = doc.select("[name=1,2]"); assertEquals(1, ps.size()); Elements containers = doc.select("div, li:matches([0-9,]+)"); assertEquals(2, containers.size()); assertEquals("div", containers.get(0).tagName()); assertEquals("li", containers.get(1).tagName()); assertEquals("123", containers.get(1).text()); } @Test public void selectSupplementaryCharacter() { String s = new String(Character.toChars(135361)); Document doc = Jsoup.parse("<div k" + s + "='" + s + "'>^" + s +"$/div>"); assertEquals("div", doc.select("div[k" + s + "]").first().tagName()); assertEquals("div", doc.select("div:containsOwn(" + s + ")").first().tagName()); } @Test public void selectClassWithSpace() { final String html = "<div class=\"value\">class without space</div>\n" + "<div class=\"value \">class with space</div>"; Document doc = Jsoup.parse(html); Elements found = doc.select("div[class=value ]"); assertEquals(2, found.size()); assertEquals("class without space", found.get(0).text()); assertEquals("class with space", found.get(1).text()); found = doc.select("div[class=\"value \"]"); assertEquals(2, found.size()); assertEquals("class without space", found.get(0).text()); assertEquals("class with space", found.get(1).text()); found = doc.select("div[class=\"value\\ \"]"); assertEquals(0, found.size()); } @Test public void selectSameElements() { final String html = "<div>one</div><div>one</div>"; Document doc = Jsoup.parse(html); Elements els = doc.select("div"); assertEquals(2, els.size()); Elements subSelect = els.select(":contains(one)"); assertEquals(2, subSelect.size()); } @Test public void attributeWithBrackets() { String html = "<div data='End]'>One</div> <div data='[Another)]]'>Two</div>"; Document doc = Jsoup.parse(html); assertEquals("One", doc.select("div[data='End]'").first().text()); assertEquals("Two", doc.select("div[data='[Another)]]'").first().text()); } }
// You are a professional Java test case writer, please create a test case named `attributeWithBrackets` for the issue `Jsoup-611`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-611 // // ## Issue-Title: // Parse failed with org.jsoup.select.Selector$SelectorParseException when selector has unbalanced '(' or '[' or ')' or ']' // // ## Issue-Description: // Selector I am having as following div.card-content2:has(a.subtitle[title= MySubTitle:)]) OR a.title[title=MyTitle :] ] // // // // @Test public void attributeWithBrackets() {
669
53
664
src/test/java/org/jsoup/select/SelectorTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-611 ## Issue-Title: Parse failed with org.jsoup.select.Selector$SelectorParseException when selector has unbalanced '(' or '[' or ')' or ']' ## Issue-Description: Selector I am having as following div.card-content2:has(a.subtitle[title= MySubTitle:)]) OR a.title[title=MyTitle :] ] ``` You are a professional Java test case writer, please create a test case named `attributeWithBrackets` for the issue `Jsoup-611`, utilizing the provided issue report information and the following function signature. ```java @Test public void attributeWithBrackets() { ```
664
[ "org.jsoup.parser.TokenQueue" ]
ab9bbc253c31183bf48c7b3bdca95f95c8d2666b3bf13d974f58fcf082ecedc5
@Test public void attributeWithBrackets()
// You are a professional Java test case writer, please create a test case named `attributeWithBrackets` for the issue `Jsoup-611`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-611 // // ## Issue-Title: // Parse failed with org.jsoup.select.Selector$SelectorParseException when selector has unbalanced '(' or '[' or ')' or ']' // // ## Issue-Description: // Selector I am having as following div.card-content2:has(a.subtitle[title= MySubTitle:)]) OR a.title[title=MyTitle :] ] // // // //
Jsoup
package org.jsoup.select; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.junit.Test; import static org.junit.Assert.*; /** * Tests that the selector selects correctly. * * @author Jonathan Hedley, [email protected] */ public class SelectorTest { @Test public void testByTag() { Elements els = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("div"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("3", els.get(2).id()); Elements none = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("span"); assertEquals(0, none.size()); } @Test public void testById() { Elements els = Jsoup.parse("<div><p id=foo>Hello</p><p id=foo>Foo two!</p></div>").select("#foo"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("Foo two!", els.get(1).text()); Elements none = Jsoup.parse("<div id=1></div>").select("#foo"); assertEquals(0, none.size()); } @Test public void testByClass() { Elements els = Jsoup.parse("<p id=0 class='one two'><p id=1 class='one'><p id=2 class='two'>").select("p.one"); assertEquals(2, els.size()); assertEquals("0", els.get(0).id()); assertEquals("1", els.get(1).id()); Elements none = Jsoup.parse("<div class='one'></div>").select(".foo"); assertEquals(0, none.size()); Elements els2 = Jsoup.parse("<div class='One-Two'></div>").select(".one-two"); assertEquals(1, els2.size()); } @Test public void testByAttribute() { String h = "<div Title=Foo /><div Title=Bar /><div Style=Qux /><div title=Bam /><div title=SLAM />" + "<div data-name='with spaces'/>"; Document doc = Jsoup.parse(h); Elements withTitle = doc.select("[title]"); assertEquals(4, withTitle.size()); Elements foo = doc.select("[title=foo]"); assertEquals(1, foo.size()); Elements foo2 = doc.select("[title=\"foo\"]"); assertEquals(1, foo2.size()); Elements foo3 = doc.select("[title=\"Foo\"]"); assertEquals(1, foo3.size()); Elements dataName = doc.select("[data-name=\"with spaces\"]"); assertEquals(1, dataName.size()); assertEquals("with spaces", dataName.first().attr("data-name")); Elements not = doc.select("div[title!=bar]"); assertEquals(5, not.size()); assertEquals("Foo", not.first().attr("title")); Elements starts = doc.select("[title^=ba]"); assertEquals(2, starts.size()); assertEquals("Bar", starts.first().attr("title")); assertEquals("Bam", starts.last().attr("title")); Elements ends = doc.select("[title$=am]"); assertEquals(2, ends.size()); assertEquals("Bam", ends.first().attr("title")); assertEquals("SLAM", ends.last().attr("title")); Elements contains = doc.select("[title*=a]"); assertEquals(3, contains.size()); assertEquals("Bar", contains.first().attr("title")); assertEquals("SLAM", contains.last().attr("title")); } @Test public void testNamespacedTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div> <abc:def class=bold id=2>There</abc:def>"); Elements byTag = doc.select("abc|def"); assertEquals(2, byTag.size()); assertEquals("1", byTag.first().id()); assertEquals("2", byTag.last().id()); Elements byAttr = doc.select(".bold"); assertEquals(1, byAttr.size()); assertEquals("2", byAttr.last().id()); Elements byTagAttr = doc.select("abc|def.bold"); assertEquals(1, byTagAttr.size()); assertEquals("2", byTagAttr.last().id()); Elements byContains = doc.select("abc|def:contains(e)"); assertEquals(2, byContains.size()); assertEquals("1", byContains.first().id()); assertEquals("2", byContains.last().id()); } @Test public void testByAttributeStarting() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup>Hello</div><p data-val=5 id=2>There</p><p id=3>No</p>"); Elements withData = doc.select("[^data-]"); assertEquals(2, withData.size()); assertEquals("1", withData.first().id()); assertEquals("2", withData.last().id()); withData = doc.select("p[^data-]"); assertEquals(1, withData.size()); assertEquals("2", withData.first().id()); } @Test public void testByAttributeRegex() { Document doc = Jsoup.parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif><img></p>"); Elements imgs = doc.select("img[src~=(?i)\\.(png|jpe?g)]"); assertEquals(3, imgs.size()); assertEquals("1", imgs.get(0).id()); assertEquals("2", imgs.get(1).id()); assertEquals("3", imgs.get(2).id()); } @Test public void testByAttributeRegexCharacterClass() { Document doc = Jsoup.parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif id=4></p>"); Elements imgs = doc.select("img[src~=[o]]"); assertEquals(2, imgs.size()); assertEquals("1", imgs.get(0).id()); assertEquals("4", imgs.get(1).id()); } @Test public void testByAttributeRegexCombined() { Document doc = Jsoup.parse("<div><table class=x><td>Hello</td></table></div>"); Elements els = doc.select("div table[class~=x|y]"); assertEquals(1, els.size()); assertEquals("Hello", els.text()); } @Test public void testCombinedWithContains() { Document doc = Jsoup.parse("<p id=1>One</p><p>Two +</p><p>Three +</p>"); Elements els = doc.select("p#1 + :contains(+)"); assertEquals(1, els.size()); assertEquals("Two +", els.text()); assertEquals("p", els.first().tagName()); } @Test public void testAllElements() { String h = "<div><p>Hello</p><p><b>there</b></p></div>"; Document doc = Jsoup.parse(h); Elements allDoc = doc.select("*"); Elements allUnderDiv = doc.select("div *"); assertEquals(8, allDoc.size()); assertEquals(3, allUnderDiv.size()); assertEquals("p", allUnderDiv.first().tagName()); } @Test public void testAllWithClass() { String h = "<p class=first>One<p class=first>Two<p>Three"; Document doc = Jsoup.parse(h); Elements ps = doc.select("*.first"); assertEquals(2, ps.size()); } @Test public void testGroupOr() { String h = "<div title=foo /><div title=bar /><div /><p></p><img /><span title=qux>"; Document doc = Jsoup.parse(h); Elements els = doc.select("p,div,[title]"); assertEquals(5, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("foo", els.get(0).attr("title")); assertEquals("div", els.get(1).tagName()); assertEquals("bar", els.get(1).attr("title")); assertEquals("div", els.get(2).tagName()); assertTrue(els.get(2).attr("title").length() == 0); // missing attributes come back as empty string assertFalse(els.get(2).hasAttr("title")); assertEquals("p", els.get(3).tagName()); assertEquals("span", els.get(4).tagName()); } @Test public void testGroupOrAttribute() { String h = "<div id=1 /><div id=2 /><div title=foo /><div title=bar />"; Elements els = Jsoup.parse(h).select("[id],[title=foo]"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("foo", els.get(2).attr("title")); } @Test public void descendant() { String h = "<div class=head><p class=first>Hello</p><p>There</p></div><p>None</p>"; Document doc = Jsoup.parse(h); Element root = doc.getElementsByClass("head").first(); Elements els = root.select(".head p"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("There", els.get(1).text()); Elements p = root.select("p.first"); assertEquals(1, p.size()); assertEquals("Hello", p.get(0).text()); Elements empty = root.select("p .first"); // self, not descend, should not match assertEquals(0, empty.size()); Elements aboveRoot = root.select("body div.head"); assertEquals(0, aboveRoot.size()); } @Test public void and() { String h = "<div id=1 class='foo bar' title=bar name=qux><p class=foo title=bar>Hello</p></div"; Document doc = Jsoup.parse(h); Elements div = doc.select("div.foo"); assertEquals(1, div.size()); assertEquals("div", div.first().tagName()); Elements p = doc.select("div .foo"); // space indicates like "div *.foo" assertEquals(1, p.size()); assertEquals("p", p.first().tagName()); Elements div2 = doc.select("div#1.foo.bar[title=bar][name=qux]"); // very specific! assertEquals(1, div2.size()); assertEquals("div", div2.first().tagName()); Elements p2 = doc.select("div *.foo"); // space indicates like "div *.foo" assertEquals(1, p2.size()); assertEquals("p", p2.first().tagName()); } @Test public void deeperDescendant() { String h = "<div class=head><p><span class=first>Hello</div><div class=head><p class=first><span>Another</span><p>Again</div>"; Document doc = Jsoup.parse(h); Element root = doc.getElementsByClass("head").first(); Elements els = root.select("div p .first"); assertEquals(1, els.size()); assertEquals("Hello", els.first().text()); assertEquals("span", els.first().tagName()); Elements aboveRoot = root.select("body p .first"); assertEquals(0, aboveRoot.size()); } @Test public void parentChildElement() { String h = "<div id=1><div id=2><div id = 3></div></div></div><div id=4></div>"; Document doc = Jsoup.parse(h); Elements divs = doc.select("div > div"); assertEquals(2, divs.size()); assertEquals("2", divs.get(0).id()); // 2 is child of 1 assertEquals("3", divs.get(1).id()); // 3 is child of 2 Elements div2 = doc.select("div#1 > div"); assertEquals(1, div2.size()); assertEquals("2", div2.get(0).id()); } @Test public void parentWithClassChild() { String h = "<h1 class=foo><a href=1 /></h1><h1 class=foo><a href=2 class=bar /></h1><h1><a href=3 /></h1>"; Document doc = Jsoup.parse(h); Elements allAs = doc.select("h1 > a"); assertEquals(3, allAs.size()); assertEquals("a", allAs.first().tagName()); Elements fooAs = doc.select("h1.foo > a"); assertEquals(2, fooAs.size()); assertEquals("a", fooAs.first().tagName()); Elements barAs = doc.select("h1.foo > a.bar"); assertEquals(1, barAs.size()); } @Test public void parentChildStar() { String h = "<div id=1><p>Hello<p><b>there</b></p></div><div id=2><span>Hi</span></div>"; Document doc = Jsoup.parse(h); Elements divChilds = doc.select("div > *"); assertEquals(3, divChilds.size()); assertEquals("p", divChilds.get(0).tagName()); assertEquals("p", divChilds.get(1).tagName()); assertEquals("span", divChilds.get(2).tagName()); } @Test public void multiChildDescent() { String h = "<div id=foo><h1 class=bar><a href=http://example.com/>One</a></h1></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select("div#foo > h1.bar > a[href*=example]"); assertEquals(1, els.size()); assertEquals("a", els.first().tagName()); } @Test public void caseInsensitive() { String h = "<dIv tItle=bAr><div>"; // mixed case so a simple toLowerCase() on value doesn't catch Document doc = Jsoup.parse(h); assertEquals(2, doc.select("DIV").size()); assertEquals(1, doc.select("DIV[TITLE]").size()); assertEquals(1, doc.select("DIV[TITLE=BAR]").size()); assertEquals(0, doc.select("DIV[TITLE=BARBARELLA").size()); } @Test public void adjacentSiblings() { String h = "<ol><li>One<li>Two<li>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li + li"); assertEquals(2, sibs.size()); assertEquals("Two", sibs.get(0).text()); assertEquals("Three", sibs.get(1).text()); } @Test public void adjacentSiblingsWithId() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li#1 + li#2"); assertEquals(1, sibs.size()); assertEquals("Two", sibs.get(0).text()); } @Test public void notAdjacent() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("li#1 + li#3"); assertEquals(0, sibs.size()); } @Test public void mixCombinator() { String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>"; Document doc = Jsoup.parse(h); Elements sibs = doc.select("body > div.foo li + li"); assertEquals(2, sibs.size()); assertEquals("Two", sibs.get(0).text()); assertEquals("Three", sibs.get(1).text()); } @Test public void mixCombinatorGroup() { String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".foo > ol, ol > li + li"); assertEquals(3, els.size()); assertEquals("ol", els.get(0).tagName()); assertEquals("Two", els.get(1).text()); assertEquals("Three", els.get(2).text()); } @Test public void generalSiblings() { String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>"; Document doc = Jsoup.parse(h); Elements els = doc.select("#1 ~ #3"); assertEquals(1, els.size()); assertEquals("Three", els.first().text()); } // for http://github.com/jhy/jsoup/issues#issue/10 @Test public void testCharactersInIdAndClass() { // using CSS spec for identifiers (id and class): a-z0-9, -, _. NOT . (which is OK in html spec, but not css) String h = "<div><p id='a1-foo_bar'>One</p><p class='b2-qux_bif'>Two</p></div>"; Document doc = Jsoup.parse(h); Element el1 = doc.getElementById("a1-foo_bar"); assertEquals("One", el1.text()); Element el2 = doc.getElementsByClass("b2-qux_bif").first(); assertEquals("Two", el2.text()); Element el3 = doc.select("#a1-foo_bar").first(); assertEquals("One", el3.text()); Element el4 = doc.select(".b2-qux_bif").first(); assertEquals("Two", el4.text()); } // for http://github.com/jhy/jsoup/issues#issue/13 @Test public void testSupportsLeadingCombinator() { String h = "<div><p><span>One</span><span>Two</span></p></div>"; Document doc = Jsoup.parse(h); Element p = doc.select("div > p").first(); Elements spans = p.select("> span"); assertEquals(2, spans.size()); assertEquals("One", spans.first().text()); // make sure doesn't get nested h = "<div id=1><div id=2><div id=3></div></div></div>"; doc = Jsoup.parse(h); Element div = doc.select("div").select(" > div").first(); assertEquals("2", div.id()); } @Test public void testPseudoLessThan() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:lt(2)"); assertEquals(3, ps.size()); assertEquals("One", ps.get(0).text()); assertEquals("Two", ps.get(1).text()); assertEquals("Four", ps.get(2).text()); } @Test public void testPseudoGreaterThan() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</p></div><div><p>Four</p>"); Elements ps = doc.select("div p:gt(0)"); assertEquals(2, ps.size()); assertEquals("Two", ps.get(0).text()); assertEquals("Three", ps.get(1).text()); } @Test public void testPseudoEquals() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:eq(0)"); assertEquals(2, ps.size()); assertEquals("One", ps.get(0).text()); assertEquals("Four", ps.get(1).text()); Elements ps2 = doc.select("div:eq(0) p:eq(0)"); assertEquals(1, ps2.size()); assertEquals("One", ps2.get(0).text()); assertEquals("p", ps2.get(0).tagName()); } @Test public void testPseudoBetween() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"); Elements ps = doc.select("div p:gt(0):lt(2)"); assertEquals(1, ps.size()); assertEquals("Two", ps.get(0).text()); } @Test public void testPseudoCombined() { Document doc = Jsoup.parse("<div class='foo'><p>One</p><p>Two</p></div><div><p>Three</p><p>Four</p></div>"); Elements ps = doc.select("div.foo p:gt(0)"); assertEquals(1, ps.size()); assertEquals("Two", ps.get(0).text()); } @Test public void testPseudoHas() { Document doc = Jsoup.parse("<div id=0><p><span>Hello</span></p></div> <div id=1><span class=foo>There</span></div> <div id=2><p>Not</p></div>"); Elements divs1 = doc.select("div:has(span)"); assertEquals(2, divs1.size()); assertEquals("0", divs1.get(0).id()); assertEquals("1", divs1.get(1).id()); Elements divs2 = doc.select("div:has([class]"); assertEquals(1, divs2.size()); assertEquals("1", divs2.get(0).id()); Elements divs3 = doc.select("div:has(span, p)"); assertEquals(3, divs3.size()); assertEquals("0", divs3.get(0).id()); assertEquals("1", divs3.get(1).id()); assertEquals("2", divs3.get(2).id()); Elements els1 = doc.body().select(":has(p)"); assertEquals(3, els1.size()); // body, div, dib assertEquals("body", els1.first().tagName()); assertEquals("0", els1.get(1).id()); assertEquals("2", els1.get(2).id()); } @Test public void testNestedHas() { Document doc = Jsoup.parse("<div><p><span>One</span></p></div> <div><p>Two</p></div>"); Elements divs = doc.select("div:has(p:has(span))"); assertEquals(1, divs.size()); assertEquals("One", divs.first().text()); // test matches in has divs = doc.select("div:has(p:matches((?i)two))"); assertEquals(1, divs.size()); assertEquals("div", divs.first().tagName()); assertEquals("Two", divs.first().text()); // test contains in has divs = doc.select("div:has(p:contains(two))"); assertEquals(1, divs.size()); assertEquals("div", divs.first().tagName()); assertEquals("Two", divs.first().text()); } @Test public void testPseudoContains() { Document doc = Jsoup.parse("<div><p>The Rain.</p> <p class=light>The <i>rain</i>.</p> <p>Rain, the.</p></div>"); Elements ps1 = doc.select("p:contains(Rain)"); assertEquals(3, ps1.size()); Elements ps2 = doc.select("p:contains(the rain)"); assertEquals(2, ps2.size()); assertEquals("The Rain.", ps2.first().html()); assertEquals("The <i>rain</i>.", ps2.last().html()); Elements ps3 = doc.select("p:contains(the Rain):has(i)"); assertEquals(1, ps3.size()); assertEquals("light", ps3.first().className()); Elements ps4 = doc.select(".light:contains(rain)"); assertEquals(1, ps4.size()); assertEquals("light", ps3.first().className()); Elements ps5 = doc.select(":contains(rain)"); assertEquals(8, ps5.size()); // html, body, div,... } @Test public void testPsuedoContainsWithParentheses() { Document doc = Jsoup.parse("<div><p id=1>This (is good)</p><p id=2>This is bad)</p>"); Elements ps1 = doc.select("p:contains(this (is good))"); assertEquals(1, ps1.size()); assertEquals("1", ps1.first().id()); Elements ps2 = doc.select("p:contains(this is bad\\))"); assertEquals(1, ps2.size()); assertEquals("2", ps2.first().id()); } @Test public void containsOwn() { Document doc = Jsoup.parse("<p id=1>Hello <b>there</b> now</p>"); Elements ps = doc.select("p:containsOwn(Hello now)"); assertEquals(1, ps.size()); assertEquals("1", ps.first().id()); assertEquals(0, doc.select("p:containsOwn(there)").size()); } @Test public void testMatches() { Document doc = Jsoup.parse("<p id=1>The <i>Rain</i></p> <p id=2>There are 99 bottles.</p> <p id=3>Harder (this)</p> <p id=4>Rain</p>"); Elements p1 = doc.select("p:matches(The rain)"); // no match, case sensitive assertEquals(0, p1.size()); Elements p2 = doc.select("p:matches((?i)the rain)"); // case insense. should include root, html, body assertEquals(1, p2.size()); assertEquals("1", p2.first().id()); Elements p4 = doc.select("p:matches((?i)^rain$)"); // bounding assertEquals(1, p4.size()); assertEquals("4", p4.first().id()); Elements p5 = doc.select("p:matches(\\d+)"); assertEquals(1, p5.size()); assertEquals("2", p5.first().id()); Elements p6 = doc.select("p:matches(\\w+\\s+\\(\\w+\\))"); // test bracket matching assertEquals(1, p6.size()); assertEquals("3", p6.first().id()); Elements p7 = doc.select("p:matches((?i)the):has(i)"); // multi assertEquals(1, p7.size()); assertEquals("1", p7.first().id()); } @Test public void matchesOwn() { Document doc = Jsoup.parse("<p id=1>Hello <b>there</b> now</p>"); Elements p1 = doc.select("p:matchesOwn((?i)hello now)"); assertEquals(1, p1.size()); assertEquals("1", p1.first().id()); assertEquals(0, doc.select("p:matchesOwn(there)").size()); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def id=2>There</abc-def>"); Elements el1 = doc.select("abc_def"); assertEquals(1, el1.size()); assertEquals("1", el1.first().id()); Elements el2 = doc.select("abc-def"); assertEquals(1, el2.size()); assertEquals("2", el2.first().id()); } @Test public void notParas() { Document doc = Jsoup.parse("<p id=1>One</p> <p>Two</p> <p><span>Three</span></p>"); Elements el1 = doc.select("p:not([id=1])"); assertEquals(2, el1.size()); assertEquals("Two", el1.first().text()); assertEquals("Three", el1.last().text()); Elements el2 = doc.select("p:not(:has(span))"); assertEquals(2, el2.size()); assertEquals("One", el2.first().text()); assertEquals("Two", el2.last().text()); } @Test public void notAll() { Document doc = Jsoup.parse("<p>Two</p> <p><span>Three</span></p>"); Elements el1 = doc.body().select(":not(p)"); // should just be the span assertEquals(2, el1.size()); assertEquals("body", el1.first().tagName()); assertEquals("span", el1.last().tagName()); } @Test public void notClass() { Document doc = Jsoup.parse("<div class=left>One</div><div class=right id=1><p>Two</p></div>"); Elements el1 = doc.select("div:not(.left)"); assertEquals(1, el1.size()); assertEquals("1", el1.first().id()); } @Test public void handlesCommasInSelector() { Document doc = Jsoup.parse("<p name='1,2'>One</p><div>Two</div><ol><li>123</li><li>Text</li></ol>"); Elements ps = doc.select("[name=1,2]"); assertEquals(1, ps.size()); Elements containers = doc.select("div, li:matches([0-9,]+)"); assertEquals(2, containers.size()); assertEquals("div", containers.get(0).tagName()); assertEquals("li", containers.get(1).tagName()); assertEquals("123", containers.get(1).text()); } @Test public void selectSupplementaryCharacter() { String s = new String(Character.toChars(135361)); Document doc = Jsoup.parse("<div k" + s + "='" + s + "'>^" + s +"$/div>"); assertEquals("div", doc.select("div[k" + s + "]").first().tagName()); assertEquals("div", doc.select("div:containsOwn(" + s + ")").first().tagName()); } @Test public void selectClassWithSpace() { final String html = "<div class=\"value\">class without space</div>\n" + "<div class=\"value \">class with space</div>"; Document doc = Jsoup.parse(html); Elements found = doc.select("div[class=value ]"); assertEquals(2, found.size()); assertEquals("class without space", found.get(0).text()); assertEquals("class with space", found.get(1).text()); found = doc.select("div[class=\"value \"]"); assertEquals(2, found.size()); assertEquals("class without space", found.get(0).text()); assertEquals("class with space", found.get(1).text()); found = doc.select("div[class=\"value\\ \"]"); assertEquals(0, found.size()); } @Test public void selectSameElements() { final String html = "<div>one</div><div>one</div>"; Document doc = Jsoup.parse(html); Elements els = doc.select("div"); assertEquals(2, els.size()); Elements subSelect = els.select(":contains(one)"); assertEquals(2, subSelect.size()); } @Test public void attributeWithBrackets() { String html = "<div data='End]'>One</div> <div data='[Another)]]'>Two</div>"; Document doc = Jsoup.parse(html); assertEquals("One", doc.select("div[data='End]'").first().text()); assertEquals("Two", doc.select("div[data='[Another)]]'").first().text()); } }
@Test public void testAddNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.add(Complex.NaN); Assert.assertTrue(z.isNaN()); z = new Complex(1, nan); Complex w = x.add(z); Assert.assertTrue(Double.isNaN(w.getReal())); Assert.assertTrue(Double.isNaN(w.getImaginary())); }
org.apache.commons.math.complex.ComplexTest::testAddNaN
src/test/java/org/apache/commons/math/complex/ComplexTest.java
117
src/test/java/org/apache/commons/math/complex/ComplexTest.java
testAddNaN
/* * 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.complex; import org.apache.commons.math.TestUtils; import org.apache.commons.math.exception.NullArgumentException; import org.apache.commons.math.util.FastMath; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * @version $Id$ */ public class ComplexTest { private double inf = Double.POSITIVE_INFINITY; private double neginf = Double.NEGATIVE_INFINITY; private double nan = Double.NaN; private double pi = FastMath.PI; private Complex oneInf = new Complex(1, inf); private Complex oneNegInf = new Complex(1, neginf); private Complex infOne = new Complex(inf, 1); private Complex infZero = new Complex(inf, 0); private Complex infNaN = new Complex(inf, nan); private Complex infNegInf = new Complex(inf, neginf); private Complex infInf = new Complex(inf, inf); private Complex negInfInf = new Complex(neginf, inf); private Complex negInfZero = new Complex(neginf, 0); private Complex negInfOne = new Complex(neginf, 1); private Complex negInfNaN = new Complex(neginf, nan); private Complex negInfNegInf = new Complex(neginf, neginf); private Complex oneNaN = new Complex(1, nan); private Complex zeroInf = new Complex(0, inf); private Complex zeroNaN = new Complex(0, nan); private Complex nanInf = new Complex(nan, inf); private Complex nanNegInf = new Complex(nan, neginf); private Complex nanZero = new Complex(nan, 0); @Test public void testConstructor() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(3.0, z.getReal(), 1.0e-5); Assert.assertEquals(4.0, z.getImaginary(), 1.0e-5); } @Test public void testConstructorNaN() { Complex z = new Complex(3.0, Double.NaN); Assert.assertTrue(z.isNaN()); z = new Complex(nan, 4.0); Assert.assertTrue(z.isNaN()); z = new Complex(3.0, 4.0); Assert.assertFalse(z.isNaN()); } @Test public void testAbs() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(5.0, z.abs(), 1.0e-5); } @Test public void testAbsNaN() { Assert.assertTrue(Double.isNaN(Complex.NaN.abs())); Complex z = new Complex(inf, nan); Assert.assertTrue(Double.isNaN(z.abs())); } @Test public void testAbsInfinite() { Complex z = new Complex(inf, 0); Assert.assertEquals(inf, z.abs(), 0); z = new Complex(0, neginf); Assert.assertEquals(inf, z.abs(), 0); z = new Complex(inf, neginf); Assert.assertEquals(inf, z.abs(), 0); } @Test public void testAdd() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.add(y); Assert.assertEquals(8.0, z.getReal(), 1.0e-5); Assert.assertEquals(10.0, z.getImaginary(), 1.0e-5); } @Test public void testAddNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.add(Complex.NaN); Assert.assertTrue(z.isNaN()); z = new Complex(1, nan); Complex w = x.add(z); Assert.assertTrue(Double.isNaN(w.getReal())); Assert.assertTrue(Double.isNaN(w.getImaginary())); } @Test public void testAddInfinite() { Complex x = new Complex(1, 1); Complex z = new Complex(inf, 0); Complex w = x.add(z); Assert.assertEquals(w.getImaginary(), 1, 0); Assert.assertEquals(inf, w.getReal(), 0); x = new Complex(neginf, 0); Assert.assertTrue(Double.isNaN(x.add(z).getReal())); } @Test public void testConjugate() { Complex x = new Complex(3.0, 4.0); Complex z = x.conjugate(); Assert.assertEquals(3.0, z.getReal(), 1.0e-5); Assert.assertEquals(-4.0, z.getImaginary(), 1.0e-5); } @Test public void testConjugateNaN() { Complex z = Complex.NaN.conjugate(); Assert.assertTrue(z.isNaN()); } @Test public void testConjugateInfiinite() { Complex z = new Complex(0, inf); Assert.assertEquals(neginf, z.conjugate().getImaginary(), 0); z = new Complex(0, neginf); Assert.assertEquals(inf, z.conjugate().getImaginary(), 0); } @Test public void testDivide() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.divide(y); Assert.assertEquals(39.0 / 61.0, z.getReal(), 1.0e-5); Assert.assertEquals(2.0 / 61.0, z.getImaginary(), 1.0e-5); } @Test public void testDivideReal() { Complex x = new Complex(2d, 3d); Complex y = new Complex(2d, 0d); Assert.assertEquals(new Complex(1d, 1.5), x.divide(y)); } @Test public void testDivideImaginary() { Complex x = new Complex(2d, 3d); Complex y = new Complex(0d, 2d); Assert.assertEquals(new Complex(1.5d, -1d), x.divide(y)); } @Test public void testDivideInfinite() { Complex x = new Complex(3, 4); Complex w = new Complex(neginf, inf); Assert.assertTrue(x.divide(w).equals(Complex.ZERO)); Complex z = w.divide(x); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertEquals(inf, z.getImaginary(), 0); w = new Complex(inf, inf); z = w.divide(x); Assert.assertTrue(Double.isNaN(z.getImaginary())); Assert.assertEquals(inf, z.getReal(), 0); w = new Complex(1, inf); z = w.divide(w); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); } @Test public void testDivideZero() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.ZERO); Assert.assertEquals(z, Complex.NaN); } @Test public void testDivideNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testDivideNaNInf() { Complex z = oneInf.divide(Complex.ONE); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertEquals(inf, z.getImaginary(), 0); z = negInfNegInf.divide(oneNaN); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); z = negInfInf.divide(Complex.ONE); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); } @Test public void testMultiply() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.multiply(y); Assert.assertEquals(-9.0, z.getReal(), 1.0e-5); Assert.assertEquals(38.0, z.getImaginary(), 1.0e-5); } @Test public void testMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Complex.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testMultiplyNaNInf() { Complex z = new Complex(1,1); Complex w = z.multiply(infOne); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); // [MATH-164] Assert.assertTrue(new Complex( 1,0).multiply(infInf).equals(Complex.INF)); Assert.assertTrue(new Complex(-1,0).multiply(infInf).equals(Complex.INF)); Assert.assertTrue(new Complex( 1,0).multiply(negInfZero).equals(Complex.INF)); w = oneInf.multiply(oneNegInf); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); w = negInfNegInf.multiply(oneNaN); Assert.assertTrue(Double.isNaN(w.getReal())); Assert.assertTrue(Double.isNaN(w.getImaginary())); } @Test public void testScalarMultiply() { Complex x = new Complex(3.0, 4.0); double y = 2.0; Complex z = x.multiply(y); Assert.assertEquals(6.0, z.getReal(), 1.0e-5); Assert.assertEquals(8.0, z.getImaginary(), 1.0e-5); } @Test public void testScalarMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Double.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testScalarMultiplyInf() { Complex z = new Complex(1,1); Complex w = z.multiply(Double.POSITIVE_INFINITY); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); w = z.multiply(Double.NEGATIVE_INFINITY); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); } @Test public void testNegate() { Complex x = new Complex(3.0, 4.0); Complex z = x.negate(); Assert.assertEquals(-3.0, z.getReal(), 1.0e-5); Assert.assertEquals(-4.0, z.getImaginary(), 1.0e-5); } @Test public void testNegateNaN() { Complex z = Complex.NaN.negate(); Assert.assertTrue(z.isNaN()); } @Test public void testSubtract() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.subtract(y); Assert.assertEquals(-2.0, z.getReal(), 1.0e-5); Assert.assertEquals(-2.0, z.getImaginary(), 1.0e-5); } @Test public void testSubtractNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.subtract(Complex.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testEqualsNull() { Complex x = new Complex(3.0, 4.0); Assert.assertFalse(x.equals(null)); } @Test public void testEqualsClass() { Complex x = new Complex(3.0, 4.0); Assert.assertFalse(x.equals(this)); } @Test public void testEqualsSame() { Complex x = new Complex(3.0, 4.0); Assert.assertTrue(x.equals(x)); } @Test public void testEqualsTrue() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(3.0, 4.0); Assert.assertTrue(x.equals(y)); } @Test public void testEqualsRealDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0 + Double.MIN_VALUE, 0.0); Assert.assertFalse(x.equals(y)); } @Test public void testEqualsImaginaryDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); Assert.assertFalse(x.equals(y)); } @Test public void testEqualsNaN() { Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Complex complexNaN = Complex.NaN; Assert.assertTrue(realNaN.equals(imaginaryNaN)); Assert.assertTrue(imaginaryNaN.equals(complexNaN)); Assert.assertTrue(realNaN.equals(complexNaN)); } @Test public void testHashCode() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); Assert.assertFalse(x.hashCode()==y.hashCode()); y = new Complex(0.0 + Double.MIN_VALUE, 0.0); Assert.assertFalse(x.hashCode()==y.hashCode()); Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Assert.assertEquals(realNaN.hashCode(), imaginaryNaN.hashCode()); Assert.assertEquals(imaginaryNaN.hashCode(), Complex.NaN.hashCode()); } @Test public void testAcos() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.936812, -2.30551); TestUtils.assertEquals(expected, z.acos(), 1.0e-5); TestUtils.assertEquals(new Complex(FastMath.acos(0), 0), Complex.ZERO.acos(), 1.0e-12); } @Test public void testAcosInf() { TestUtils.assertSame(Complex.NaN, oneInf.acos()); TestUtils.assertSame(Complex.NaN, oneNegInf.acos()); TestUtils.assertSame(Complex.NaN, infOne.acos()); TestUtils.assertSame(Complex.NaN, negInfOne.acos()); TestUtils.assertSame(Complex.NaN, infInf.acos()); TestUtils.assertSame(Complex.NaN, infNegInf.acos()); TestUtils.assertSame(Complex.NaN, negInfInf.acos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.acos()); } @Test public void testAcosNaN() { Assert.assertTrue(Complex.NaN.acos().isNaN()); } @Test public void testAsin() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.633984, 2.30551); TestUtils.assertEquals(expected, z.asin(), 1.0e-5); } @Test public void testAsinNaN() { Assert.assertTrue(Complex.NaN.asin().isNaN()); } @Test public void testAsinInf() { TestUtils.assertSame(Complex.NaN, oneInf.asin()); TestUtils.assertSame(Complex.NaN, oneNegInf.asin()); TestUtils.assertSame(Complex.NaN, infOne.asin()); TestUtils.assertSame(Complex.NaN, negInfOne.asin()); TestUtils.assertSame(Complex.NaN, infInf.asin()); TestUtils.assertSame(Complex.NaN, infNegInf.asin()); TestUtils.assertSame(Complex.NaN, negInfInf.asin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.asin()); } @Test public void testAtan() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.44831, 0.158997); TestUtils.assertEquals(expected, z.atan(), 1.0e-5); } @Test public void testAtanInf() { TestUtils.assertSame(Complex.NaN, oneInf.atan()); TestUtils.assertSame(Complex.NaN, oneNegInf.atan()); TestUtils.assertSame(Complex.NaN, infOne.atan()); TestUtils.assertSame(Complex.NaN, negInfOne.atan()); TestUtils.assertSame(Complex.NaN, infInf.atan()); TestUtils.assertSame(Complex.NaN, infNegInf.atan()); TestUtils.assertSame(Complex.NaN, negInfInf.atan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.atan()); } @Test public void testAtanNaN() { Assert.assertTrue(Complex.NaN.atan().isNaN()); Assert.assertTrue(Complex.I.atan().isNaN()); } @Test public void testCos() { Complex z = new Complex(3, 4); Complex expected = new Complex(-27.03495, -3.851153); TestUtils.assertEquals(expected, z.cos(), 1.0e-5); } @Test public void testCosNaN() { Assert.assertTrue(Complex.NaN.cos().isNaN()); } @Test public void testCosInf() { TestUtils.assertSame(infNegInf, oneInf.cos()); TestUtils.assertSame(infInf, oneNegInf.cos()); TestUtils.assertSame(Complex.NaN, infOne.cos()); TestUtils.assertSame(Complex.NaN, negInfOne.cos()); TestUtils.assertSame(Complex.NaN, infInf.cos()); TestUtils.assertSame(Complex.NaN, infNegInf.cos()); TestUtils.assertSame(Complex.NaN, negInfInf.cos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cos()); } @Test public void testCosh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.58066, -7.58155); TestUtils.assertEquals(expected, z.cosh(), 1.0e-5); } @Test public void testCoshNaN() { Assert.assertTrue(Complex.NaN.cosh().isNaN()); } @Test public void testCoshInf() { TestUtils.assertSame(Complex.NaN, oneInf.cosh()); TestUtils.assertSame(Complex.NaN, oneNegInf.cosh()); TestUtils.assertSame(infInf, infOne.cosh()); TestUtils.assertSame(infNegInf, negInfOne.cosh()); TestUtils.assertSame(Complex.NaN, infInf.cosh()); TestUtils.assertSame(Complex.NaN, infNegInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cosh()); } @Test public void testExp() { Complex z = new Complex(3, 4); Complex expected = new Complex(-13.12878, -15.20078); TestUtils.assertEquals(expected, z.exp(), 1.0e-5); TestUtils.assertEquals(Complex.ONE, Complex.ZERO.exp(), 10e-12); Complex iPi = Complex.I.multiply(new Complex(pi,0)); TestUtils.assertEquals(Complex.ONE.negate(), iPi.exp(), 10e-12); } @Test public void testExpNaN() { Assert.assertTrue(Complex.NaN.exp().isNaN()); } @Test public void testExpInf() { TestUtils.assertSame(Complex.NaN, oneInf.exp()); TestUtils.assertSame(Complex.NaN, oneNegInf.exp()); TestUtils.assertSame(infInf, infOne.exp()); TestUtils.assertSame(Complex.ZERO, negInfOne.exp()); TestUtils.assertSame(Complex.NaN, infInf.exp()); TestUtils.assertSame(Complex.NaN, infNegInf.exp()); TestUtils.assertSame(Complex.NaN, negInfInf.exp()); TestUtils.assertSame(Complex.NaN, negInfNegInf.exp()); } @Test public void testLog() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.60944, 0.927295); TestUtils.assertEquals(expected, z.log(), 1.0e-5); } @Test public void testLogNaN() { Assert.assertTrue(Complex.NaN.log().isNaN()); } @Test public void testLogInf() { TestUtils.assertEquals(new Complex(inf, pi / 2), oneInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 2), oneNegInf.log(), 10e-12); TestUtils.assertEquals(infZero, infOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi), negInfOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi / 4), infInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 4), infNegInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, 3d * pi / 4), negInfInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, - 3d * pi / 4), negInfNegInf.log(), 10e-12); } @Test public void testLogZero() { TestUtils.assertSame(negInfZero, Complex.ZERO.log()); } @Test public void testPow() { Complex x = new Complex(3, 4); Complex y = new Complex(5, 6); Complex expected = new Complex(-1.860893, 11.83677); TestUtils.assertEquals(expected, x.pow(y), 1.0e-5); } @Test public void testPowNaNBase() { Complex x = new Complex(3, 4); Assert.assertTrue(Complex.NaN.pow(x).isNaN()); } @Test public void testPowNaNExponent() { Complex x = new Complex(3, 4); Assert.assertTrue(x.pow(Complex.NaN).isNaN()); } @Test public void testPowInf() { TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infOne)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infInf)); } @Test public void testPowZero() { TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ZERO)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.I)); TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, Complex.I.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(Complex.ZERO), 10e-12); } @Test(expected=NullArgumentException.class) public void testpowNull() { Complex.ONE.pow(null); } @Test public void testSin() { Complex z = new Complex(3, 4); Complex expected = new Complex(3.853738, -27.01681); TestUtils.assertEquals(expected, z.sin(), 1.0e-5); } @Test public void testSinInf() { TestUtils.assertSame(infInf, oneInf.sin()); TestUtils.assertSame(infNegInf, oneNegInf.sin()); TestUtils.assertSame(Complex.NaN, infOne.sin()); TestUtils.assertSame(Complex.NaN, negInfOne.sin()); TestUtils.assertSame(Complex.NaN, infInf.sin()); TestUtils.assertSame(Complex.NaN, infNegInf.sin()); TestUtils.assertSame(Complex.NaN, negInfInf.sin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sin()); } @Test public void testSinNaN() { Assert.assertTrue(Complex.NaN.sin().isNaN()); } @Test public void testSinh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.54812, -7.61923); TestUtils.assertEquals(expected, z.sinh(), 1.0e-5); } @Test public void testSinhNaN() { Assert.assertTrue(Complex.NaN.sinh().isNaN()); } @Test public void testSinhInf() { TestUtils.assertSame(Complex.NaN, oneInf.sinh()); TestUtils.assertSame(Complex.NaN, oneNegInf.sinh()); TestUtils.assertSame(infInf, infOne.sinh()); TestUtils.assertSame(negInfInf, negInfOne.sinh()); TestUtils.assertSame(Complex.NaN, infInf.sinh()); TestUtils.assertSame(Complex.NaN, infNegInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sinh()); } @Test public void testSqrtRealPositive() { Complex z = new Complex(3, 4); Complex expected = new Complex(2, 1); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtRealZero() { Complex z = new Complex(0.0, 4); Complex expected = new Complex(1.41421, 1.41421); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtRealNegative() { Complex z = new Complex(-3.0, 4); Complex expected = new Complex(1, 2); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtImaginaryZero() { Complex z = new Complex(-3.0, 0.0); Complex expected = new Complex(0.0, 1.73205); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtImaginaryNegative() { Complex z = new Complex(-3.0, -4.0); Complex expected = new Complex(1.0, -2.0); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtPolar() { double r = 1; for (int i = 0; i < 5; i++) { r += i; double theta = 0; for (int j =0; j < 11; j++) { theta += pi /12; Complex z = ComplexUtils.polar2Complex(r, theta); Complex sqrtz = ComplexUtils.polar2Complex(FastMath.sqrt(r), theta / 2); TestUtils.assertEquals(sqrtz, z.sqrt(), 10e-12); } } } @Test public void testSqrtNaN() { Assert.assertTrue(Complex.NaN.sqrt().isNaN()); } @Test public void testSqrtInf() { TestUtils.assertSame(infNaN, oneInf.sqrt()); TestUtils.assertSame(infNaN, oneNegInf.sqrt()); TestUtils.assertSame(infZero, infOne.sqrt()); TestUtils.assertSame(zeroInf, negInfOne.sqrt()); TestUtils.assertSame(infNaN, infInf.sqrt()); TestUtils.assertSame(infNaN, infNegInf.sqrt()); TestUtils.assertSame(nanInf, negInfInf.sqrt()); TestUtils.assertSame(nanNegInf, negInfNegInf.sqrt()); } @Test public void testSqrt1z() { Complex z = new Complex(3, 4); Complex expected = new Complex(4.08033, -2.94094); TestUtils.assertEquals(expected, z.sqrt1z(), 1.0e-5); } @Test public void testSqrt1zNaN() { Assert.assertTrue(Complex.NaN.sqrt1z().isNaN()); } @Test public void testTan() { Complex z = new Complex(3, 4); Complex expected = new Complex(-0.000187346, 0.999356); TestUtils.assertEquals(expected, z.tan(), 1.0e-5); } @Test public void testTanNaN() { Assert.assertTrue(Complex.NaN.tan().isNaN()); } @Test public void testTanInf() { TestUtils.assertSame(zeroNaN, oneInf.tan()); TestUtils.assertSame(zeroNaN, oneNegInf.tan()); TestUtils.assertSame(Complex.NaN, infOne.tan()); TestUtils.assertSame(Complex.NaN, negInfOne.tan()); TestUtils.assertSame(Complex.NaN, infInf.tan()); TestUtils.assertSame(Complex.NaN, infNegInf.tan()); TestUtils.assertSame(Complex.NaN, negInfInf.tan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tan()); } @Test public void testTanCritical() { TestUtils.assertSame(infNaN, new Complex(pi/2, 0).tan()); TestUtils.assertSame(negInfNaN, new Complex(-pi/2, 0).tan()); } @Test public void testTanh() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.00071, 0.00490826); TestUtils.assertEquals(expected, z.tanh(), 1.0e-5); } @Test public void testTanhNaN() { Assert.assertTrue(Complex.NaN.tanh().isNaN()); } @Test public void testTanhInf() { TestUtils.assertSame(Complex.NaN, oneInf.tanh()); TestUtils.assertSame(Complex.NaN, oneNegInf.tanh()); TestUtils.assertSame(nanZero, infOne.tanh()); TestUtils.assertSame(nanZero, negInfOne.tanh()); TestUtils.assertSame(Complex.NaN, infInf.tanh()); TestUtils.assertSame(Complex.NaN, infNegInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tanh()); } @Test public void testTanhCritical() { TestUtils.assertSame(nanInf, new Complex(0, pi/2).tanh()); } /** test issue MATH-221 */ @Test public void testMath221() { Assert.assertEquals(new Complex(0,-1), new Complex(0,1).multiply(new Complex(-1,0))); } /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = -2 + 2 * i</b> * => z_0 = 1 + i * => z_1 = -1.3660 + 0.3660 * i * => z_2 = 0.3660 - 1.3660 * i * </code> * </pre> */ @Test public void testNthRoot_normal_thirdRoot() { // The complex number we want to compute all third-roots for. Complex z = new Complex(-2,2); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(1.0, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(1.0, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.3660254037844386, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(0.36602540378443843, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(0.366025403784439, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.3660254037844384, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test: computing <b>fourth roots</b> of z. * <pre> * <code> * <b>z = 5 - 2 * i</b> * => z_0 = 1.5164 - 0.1446 * i * => z_1 = 0.1446 + 1.5164 * i * => z_2 = -1.5164 + 0.1446 * i * => z_3 = -1.5164 - 0.1446 * i * </code> * </pre> */ @Test public void testNthRoot_normal_fourthRoot() { // The complex number we want to compute all third-roots for. Complex z = new Complex(5,-2); // The List holding all fourth roots Complex[] fourthRootsOfZ = z.nthRoot(4).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(4, fourthRootsOfZ.length); // test z_0 Assert.assertEquals(1.5164629308487783, fourthRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(-0.14469266210702247, fourthRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(0.14469266210702256, fourthRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(1.5164629308487783, fourthRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-1.5164629308487783, fourthRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(0.14469266210702267, fourthRootsOfZ[2].getImaginary(), 1.0e-5); // test z_3 Assert.assertEquals(-0.14469266210702275, fourthRootsOfZ[3].getReal(), 1.0e-5); Assert.assertEquals(-1.5164629308487783, fourthRootsOfZ[3].getImaginary(), 1.0e-5); } /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty() { // The number 8 has three third roots. One we all already know is the number 2. // But there are two more complex roots. Complex z = new Complex(8,0); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(2.0, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(0.0, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.0, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(1.7320508075688774, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-1.0, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.732050807568877, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test: computing <b>third roots</b> of z with real part 0. * <pre> * <code> * <b>z = 2 * i</b> * => z_0 = 1.0911 + 0.6299 * i * => z_1 = -1.0911 + 0.6299 * i * => z_2 = -2.3144 - 1.2599 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_realPartZero() { // complex number with only imaginary part Complex z = new Complex(0,2); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(1.0911236359717216, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(0.6299605249474365, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.0911236359717216, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(0.6299605249474365, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-2.3144374213981936E-16, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.2599210498948732, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test cornercases with NaN and Infinity. */ @Test public void testNthRoot_cornercase_NAN_Inf() { // NaN + finite -> NaN List<Complex> roots = oneNaN.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); roots = nanZero.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); // NaN + infinite -> NaN roots = nanInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); // finite + infinite -> Inf roots = oneInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.INF, roots.get(0)); // infinite + infinite -> Inf roots = negInfInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.INF, roots.get(0)); } /** * Test standard values */ @Test public void testGetArgument() { Complex z = new Complex(1, 0); Assert.assertEquals(0.0, z.getArgument(), 1.0e-12); z = new Complex(1, 1); Assert.assertEquals(FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(0, 1); Assert.assertEquals(FastMath.PI/2, z.getArgument(), 1.0e-12); z = new Complex(-1, 1); Assert.assertEquals(3 * FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(-1, 0); Assert.assertEquals(FastMath.PI, z.getArgument(), 1.0e-12); z = new Complex(-1, -1); Assert.assertEquals(-3 * FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(0, -1); Assert.assertEquals(-FastMath.PI/2, z.getArgument(), 1.0e-12); z = new Complex(1, -1); Assert.assertEquals(-FastMath.PI/4, z.getArgument(), 1.0e-12); } /** * Verify atan2-style handling of infinite parts */ @Test public void testGetArgumentInf() { Assert.assertEquals(FastMath.PI/4, infInf.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI/2, oneInf.getArgument(), 1.0e-12); Assert.assertEquals(0.0, infOne.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI/2, zeroInf.getArgument(), 1.0e-12); Assert.assertEquals(0.0, infZero.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI, negInfOne.getArgument(), 1.0e-12); Assert.assertEquals(-3.0*FastMath.PI/4, negInfNegInf.getArgument(), 1.0e-12); Assert.assertEquals(-FastMath.PI/2, oneNegInf.getArgument(), 1.0e-12); } /** * Verify that either part NaN results in NaN */ @Test public void testGetArgumentNaN() { Assert.assertTrue(Double.isNaN(nanZero.getArgument())); Assert.assertTrue(Double.isNaN(zeroNaN.getArgument())); Assert.assertTrue(Double.isNaN(Complex.NaN.getArgument())); } @Test public void testSerial() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(z, TestUtils.serializeAndRecover(z)); Complex ncmplx = (Complex)TestUtils.serializeAndRecover(oneNaN); Assert.assertEquals(nanZero, ncmplx); Assert.assertTrue(ncmplx.isNaN()); Complex infcmplx = (Complex)TestUtils.serializeAndRecover(infInf); Assert.assertEquals(infInf, infcmplx); Assert.assertTrue(infcmplx.isInfinite()); TestComplex tz = new TestComplex(3.0, 4.0); Assert.assertEquals(tz, TestUtils.serializeAndRecover(tz)); TestComplex ntcmplx = (TestComplex)TestUtils.serializeAndRecover(new TestComplex(oneNaN)); Assert.assertEquals(nanZero, ntcmplx); Assert.assertTrue(ntcmplx.isNaN()); TestComplex inftcmplx = (TestComplex)TestUtils.serializeAndRecover(new TestComplex(infInf)); Assert.assertEquals(infInf, inftcmplx); Assert.assertTrue(inftcmplx.isInfinite()); } /** * Class to test extending Complex */ public static class TestComplex extends Complex { /** * Serialization identifier. */ private static final long serialVersionUID = 3268726724160389237L; public TestComplex(double real, double imaginary) { super(real, imaginary); } public TestComplex(Complex other){ this(other.getReal(), other.getImaginary()); } @Override protected TestComplex createComplex(double real, double imaginary){ return new TestComplex(real, imaginary); } } }
// You are a professional Java test case writer, please create a test case named `testAddNaN` for the issue `Math-MATH-618`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-618 // // ## Issue-Title: // Complex Add and Subtract handle NaN arguments differently, but javadoc contracts are the same // // ## Issue-Description: // // For both Complex add and subtract, the javadoc states that // // // // // ``` // * If either this or <code>rhs</code> has a NaN value in either part, // * {@link #NaN} is returned; otherwise Inifinite and NaN values are // * returned in the parts of the result according to the rules for // * {@link java.lang.Double} arithmetic // // ``` // // // Subtract includes an isNaN test and returns Complex.NaN if either complex argument isNaN; but add omits this test. The test should be added to the add implementation (actually restored, since this looks like a code merge problem going back to 1.1). // // // // // @Test public void testAddNaN() {
117
53
108
src/test/java/org/apache/commons/math/complex/ComplexTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-618 ## Issue-Title: Complex Add and Subtract handle NaN arguments differently, but javadoc contracts are the same ## Issue-Description: For both Complex add and subtract, the javadoc states that ``` * If either this or <code>rhs</code> has a NaN value in either part, * {@link #NaN} is returned; otherwise Inifinite and NaN values are * returned in the parts of the result according to the rules for * {@link java.lang.Double} arithmetic ``` Subtract includes an isNaN test and returns Complex.NaN if either complex argument isNaN; but add omits this test. The test should be added to the add implementation (actually restored, since this looks like a code merge problem going back to 1.1). ``` You are a professional Java test case writer, please create a test case named `testAddNaN` for the issue `Math-MATH-618`, utilizing the provided issue report information and the following function signature. ```java @Test public void testAddNaN() { ```
108
[ "org.apache.commons.math.complex.Complex" ]
abb23865a79c14162730e3cee3bef34dd1fbce8fa43fecd8b74d50ccdc1e137c
@Test public void testAddNaN()
// You are a professional Java test case writer, please create a test case named `testAddNaN` for the issue `Math-MATH-618`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-618 // // ## Issue-Title: // Complex Add and Subtract handle NaN arguments differently, but javadoc contracts are the same // // ## Issue-Description: // // For both Complex add and subtract, the javadoc states that // // // // // ``` // * If either this or <code>rhs</code> has a NaN value in either part, // * {@link #NaN} is returned; otherwise Inifinite and NaN values are // * returned in the parts of the result according to the rules for // * {@link java.lang.Double} arithmetic // // ``` // // // Subtract includes an isNaN test and returns Complex.NaN if either complex argument isNaN; but add omits this test. The test should be added to the add implementation (actually restored, since this looks like a code merge problem going back to 1.1). // // // // //
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.complex; import org.apache.commons.math.TestUtils; import org.apache.commons.math.exception.NullArgumentException; import org.apache.commons.math.util.FastMath; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * @version $Id$ */ public class ComplexTest { private double inf = Double.POSITIVE_INFINITY; private double neginf = Double.NEGATIVE_INFINITY; private double nan = Double.NaN; private double pi = FastMath.PI; private Complex oneInf = new Complex(1, inf); private Complex oneNegInf = new Complex(1, neginf); private Complex infOne = new Complex(inf, 1); private Complex infZero = new Complex(inf, 0); private Complex infNaN = new Complex(inf, nan); private Complex infNegInf = new Complex(inf, neginf); private Complex infInf = new Complex(inf, inf); private Complex negInfInf = new Complex(neginf, inf); private Complex negInfZero = new Complex(neginf, 0); private Complex negInfOne = new Complex(neginf, 1); private Complex negInfNaN = new Complex(neginf, nan); private Complex negInfNegInf = new Complex(neginf, neginf); private Complex oneNaN = new Complex(1, nan); private Complex zeroInf = new Complex(0, inf); private Complex zeroNaN = new Complex(0, nan); private Complex nanInf = new Complex(nan, inf); private Complex nanNegInf = new Complex(nan, neginf); private Complex nanZero = new Complex(nan, 0); @Test public void testConstructor() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(3.0, z.getReal(), 1.0e-5); Assert.assertEquals(4.0, z.getImaginary(), 1.0e-5); } @Test public void testConstructorNaN() { Complex z = new Complex(3.0, Double.NaN); Assert.assertTrue(z.isNaN()); z = new Complex(nan, 4.0); Assert.assertTrue(z.isNaN()); z = new Complex(3.0, 4.0); Assert.assertFalse(z.isNaN()); } @Test public void testAbs() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(5.0, z.abs(), 1.0e-5); } @Test public void testAbsNaN() { Assert.assertTrue(Double.isNaN(Complex.NaN.abs())); Complex z = new Complex(inf, nan); Assert.assertTrue(Double.isNaN(z.abs())); } @Test public void testAbsInfinite() { Complex z = new Complex(inf, 0); Assert.assertEquals(inf, z.abs(), 0); z = new Complex(0, neginf); Assert.assertEquals(inf, z.abs(), 0); z = new Complex(inf, neginf); Assert.assertEquals(inf, z.abs(), 0); } @Test public void testAdd() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.add(y); Assert.assertEquals(8.0, z.getReal(), 1.0e-5); Assert.assertEquals(10.0, z.getImaginary(), 1.0e-5); } @Test public void testAddNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.add(Complex.NaN); Assert.assertTrue(z.isNaN()); z = new Complex(1, nan); Complex w = x.add(z); Assert.assertTrue(Double.isNaN(w.getReal())); Assert.assertTrue(Double.isNaN(w.getImaginary())); } @Test public void testAddInfinite() { Complex x = new Complex(1, 1); Complex z = new Complex(inf, 0); Complex w = x.add(z); Assert.assertEquals(w.getImaginary(), 1, 0); Assert.assertEquals(inf, w.getReal(), 0); x = new Complex(neginf, 0); Assert.assertTrue(Double.isNaN(x.add(z).getReal())); } @Test public void testConjugate() { Complex x = new Complex(3.0, 4.0); Complex z = x.conjugate(); Assert.assertEquals(3.0, z.getReal(), 1.0e-5); Assert.assertEquals(-4.0, z.getImaginary(), 1.0e-5); } @Test public void testConjugateNaN() { Complex z = Complex.NaN.conjugate(); Assert.assertTrue(z.isNaN()); } @Test public void testConjugateInfiinite() { Complex z = new Complex(0, inf); Assert.assertEquals(neginf, z.conjugate().getImaginary(), 0); z = new Complex(0, neginf); Assert.assertEquals(inf, z.conjugate().getImaginary(), 0); } @Test public void testDivide() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.divide(y); Assert.assertEquals(39.0 / 61.0, z.getReal(), 1.0e-5); Assert.assertEquals(2.0 / 61.0, z.getImaginary(), 1.0e-5); } @Test public void testDivideReal() { Complex x = new Complex(2d, 3d); Complex y = new Complex(2d, 0d); Assert.assertEquals(new Complex(1d, 1.5), x.divide(y)); } @Test public void testDivideImaginary() { Complex x = new Complex(2d, 3d); Complex y = new Complex(0d, 2d); Assert.assertEquals(new Complex(1.5d, -1d), x.divide(y)); } @Test public void testDivideInfinite() { Complex x = new Complex(3, 4); Complex w = new Complex(neginf, inf); Assert.assertTrue(x.divide(w).equals(Complex.ZERO)); Complex z = w.divide(x); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertEquals(inf, z.getImaginary(), 0); w = new Complex(inf, inf); z = w.divide(x); Assert.assertTrue(Double.isNaN(z.getImaginary())); Assert.assertEquals(inf, z.getReal(), 0); w = new Complex(1, inf); z = w.divide(w); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); } @Test public void testDivideZero() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.ZERO); Assert.assertEquals(z, Complex.NaN); } @Test public void testDivideNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testDivideNaNInf() { Complex z = oneInf.divide(Complex.ONE); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertEquals(inf, z.getImaginary(), 0); z = negInfNegInf.divide(oneNaN); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); z = negInfInf.divide(Complex.ONE); Assert.assertTrue(Double.isNaN(z.getReal())); Assert.assertTrue(Double.isNaN(z.getImaginary())); } @Test public void testMultiply() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.multiply(y); Assert.assertEquals(-9.0, z.getReal(), 1.0e-5); Assert.assertEquals(38.0, z.getImaginary(), 1.0e-5); } @Test public void testMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Complex.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testMultiplyNaNInf() { Complex z = new Complex(1,1); Complex w = z.multiply(infOne); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); // [MATH-164] Assert.assertTrue(new Complex( 1,0).multiply(infInf).equals(Complex.INF)); Assert.assertTrue(new Complex(-1,0).multiply(infInf).equals(Complex.INF)); Assert.assertTrue(new Complex( 1,0).multiply(negInfZero).equals(Complex.INF)); w = oneInf.multiply(oneNegInf); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); w = negInfNegInf.multiply(oneNaN); Assert.assertTrue(Double.isNaN(w.getReal())); Assert.assertTrue(Double.isNaN(w.getImaginary())); } @Test public void testScalarMultiply() { Complex x = new Complex(3.0, 4.0); double y = 2.0; Complex z = x.multiply(y); Assert.assertEquals(6.0, z.getReal(), 1.0e-5); Assert.assertEquals(8.0, z.getImaginary(), 1.0e-5); } @Test public void testScalarMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Double.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testScalarMultiplyInf() { Complex z = new Complex(1,1); Complex w = z.multiply(Double.POSITIVE_INFINITY); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); w = z.multiply(Double.NEGATIVE_INFINITY); Assert.assertEquals(w.getReal(), inf, 0); Assert.assertEquals(w.getImaginary(), inf, 0); } @Test public void testNegate() { Complex x = new Complex(3.0, 4.0); Complex z = x.negate(); Assert.assertEquals(-3.0, z.getReal(), 1.0e-5); Assert.assertEquals(-4.0, z.getImaginary(), 1.0e-5); } @Test public void testNegateNaN() { Complex z = Complex.NaN.negate(); Assert.assertTrue(z.isNaN()); } @Test public void testSubtract() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.subtract(y); Assert.assertEquals(-2.0, z.getReal(), 1.0e-5); Assert.assertEquals(-2.0, z.getImaginary(), 1.0e-5); } @Test public void testSubtractNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.subtract(Complex.NaN); Assert.assertTrue(z.isNaN()); } @Test public void testEqualsNull() { Complex x = new Complex(3.0, 4.0); Assert.assertFalse(x.equals(null)); } @Test public void testEqualsClass() { Complex x = new Complex(3.0, 4.0); Assert.assertFalse(x.equals(this)); } @Test public void testEqualsSame() { Complex x = new Complex(3.0, 4.0); Assert.assertTrue(x.equals(x)); } @Test public void testEqualsTrue() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(3.0, 4.0); Assert.assertTrue(x.equals(y)); } @Test public void testEqualsRealDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0 + Double.MIN_VALUE, 0.0); Assert.assertFalse(x.equals(y)); } @Test public void testEqualsImaginaryDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); Assert.assertFalse(x.equals(y)); } @Test public void testEqualsNaN() { Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Complex complexNaN = Complex.NaN; Assert.assertTrue(realNaN.equals(imaginaryNaN)); Assert.assertTrue(imaginaryNaN.equals(complexNaN)); Assert.assertTrue(realNaN.equals(complexNaN)); } @Test public void testHashCode() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); Assert.assertFalse(x.hashCode()==y.hashCode()); y = new Complex(0.0 + Double.MIN_VALUE, 0.0); Assert.assertFalse(x.hashCode()==y.hashCode()); Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Assert.assertEquals(realNaN.hashCode(), imaginaryNaN.hashCode()); Assert.assertEquals(imaginaryNaN.hashCode(), Complex.NaN.hashCode()); } @Test public void testAcos() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.936812, -2.30551); TestUtils.assertEquals(expected, z.acos(), 1.0e-5); TestUtils.assertEquals(new Complex(FastMath.acos(0), 0), Complex.ZERO.acos(), 1.0e-12); } @Test public void testAcosInf() { TestUtils.assertSame(Complex.NaN, oneInf.acos()); TestUtils.assertSame(Complex.NaN, oneNegInf.acos()); TestUtils.assertSame(Complex.NaN, infOne.acos()); TestUtils.assertSame(Complex.NaN, negInfOne.acos()); TestUtils.assertSame(Complex.NaN, infInf.acos()); TestUtils.assertSame(Complex.NaN, infNegInf.acos()); TestUtils.assertSame(Complex.NaN, negInfInf.acos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.acos()); } @Test public void testAcosNaN() { Assert.assertTrue(Complex.NaN.acos().isNaN()); } @Test public void testAsin() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.633984, 2.30551); TestUtils.assertEquals(expected, z.asin(), 1.0e-5); } @Test public void testAsinNaN() { Assert.assertTrue(Complex.NaN.asin().isNaN()); } @Test public void testAsinInf() { TestUtils.assertSame(Complex.NaN, oneInf.asin()); TestUtils.assertSame(Complex.NaN, oneNegInf.asin()); TestUtils.assertSame(Complex.NaN, infOne.asin()); TestUtils.assertSame(Complex.NaN, negInfOne.asin()); TestUtils.assertSame(Complex.NaN, infInf.asin()); TestUtils.assertSame(Complex.NaN, infNegInf.asin()); TestUtils.assertSame(Complex.NaN, negInfInf.asin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.asin()); } @Test public void testAtan() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.44831, 0.158997); TestUtils.assertEquals(expected, z.atan(), 1.0e-5); } @Test public void testAtanInf() { TestUtils.assertSame(Complex.NaN, oneInf.atan()); TestUtils.assertSame(Complex.NaN, oneNegInf.atan()); TestUtils.assertSame(Complex.NaN, infOne.atan()); TestUtils.assertSame(Complex.NaN, negInfOne.atan()); TestUtils.assertSame(Complex.NaN, infInf.atan()); TestUtils.assertSame(Complex.NaN, infNegInf.atan()); TestUtils.assertSame(Complex.NaN, negInfInf.atan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.atan()); } @Test public void testAtanNaN() { Assert.assertTrue(Complex.NaN.atan().isNaN()); Assert.assertTrue(Complex.I.atan().isNaN()); } @Test public void testCos() { Complex z = new Complex(3, 4); Complex expected = new Complex(-27.03495, -3.851153); TestUtils.assertEquals(expected, z.cos(), 1.0e-5); } @Test public void testCosNaN() { Assert.assertTrue(Complex.NaN.cos().isNaN()); } @Test public void testCosInf() { TestUtils.assertSame(infNegInf, oneInf.cos()); TestUtils.assertSame(infInf, oneNegInf.cos()); TestUtils.assertSame(Complex.NaN, infOne.cos()); TestUtils.assertSame(Complex.NaN, negInfOne.cos()); TestUtils.assertSame(Complex.NaN, infInf.cos()); TestUtils.assertSame(Complex.NaN, infNegInf.cos()); TestUtils.assertSame(Complex.NaN, negInfInf.cos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cos()); } @Test public void testCosh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.58066, -7.58155); TestUtils.assertEquals(expected, z.cosh(), 1.0e-5); } @Test public void testCoshNaN() { Assert.assertTrue(Complex.NaN.cosh().isNaN()); } @Test public void testCoshInf() { TestUtils.assertSame(Complex.NaN, oneInf.cosh()); TestUtils.assertSame(Complex.NaN, oneNegInf.cosh()); TestUtils.assertSame(infInf, infOne.cosh()); TestUtils.assertSame(infNegInf, negInfOne.cosh()); TestUtils.assertSame(Complex.NaN, infInf.cosh()); TestUtils.assertSame(Complex.NaN, infNegInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cosh()); } @Test public void testExp() { Complex z = new Complex(3, 4); Complex expected = new Complex(-13.12878, -15.20078); TestUtils.assertEquals(expected, z.exp(), 1.0e-5); TestUtils.assertEquals(Complex.ONE, Complex.ZERO.exp(), 10e-12); Complex iPi = Complex.I.multiply(new Complex(pi,0)); TestUtils.assertEquals(Complex.ONE.negate(), iPi.exp(), 10e-12); } @Test public void testExpNaN() { Assert.assertTrue(Complex.NaN.exp().isNaN()); } @Test public void testExpInf() { TestUtils.assertSame(Complex.NaN, oneInf.exp()); TestUtils.assertSame(Complex.NaN, oneNegInf.exp()); TestUtils.assertSame(infInf, infOne.exp()); TestUtils.assertSame(Complex.ZERO, negInfOne.exp()); TestUtils.assertSame(Complex.NaN, infInf.exp()); TestUtils.assertSame(Complex.NaN, infNegInf.exp()); TestUtils.assertSame(Complex.NaN, negInfInf.exp()); TestUtils.assertSame(Complex.NaN, negInfNegInf.exp()); } @Test public void testLog() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.60944, 0.927295); TestUtils.assertEquals(expected, z.log(), 1.0e-5); } @Test public void testLogNaN() { Assert.assertTrue(Complex.NaN.log().isNaN()); } @Test public void testLogInf() { TestUtils.assertEquals(new Complex(inf, pi / 2), oneInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 2), oneNegInf.log(), 10e-12); TestUtils.assertEquals(infZero, infOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi), negInfOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi / 4), infInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 4), infNegInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, 3d * pi / 4), negInfInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, - 3d * pi / 4), negInfNegInf.log(), 10e-12); } @Test public void testLogZero() { TestUtils.assertSame(negInfZero, Complex.ZERO.log()); } @Test public void testPow() { Complex x = new Complex(3, 4); Complex y = new Complex(5, 6); Complex expected = new Complex(-1.860893, 11.83677); TestUtils.assertEquals(expected, x.pow(y), 1.0e-5); } @Test public void testPowNaNBase() { Complex x = new Complex(3, 4); Assert.assertTrue(Complex.NaN.pow(x).isNaN()); } @Test public void testPowNaNExponent() { Complex x = new Complex(3, 4); Assert.assertTrue(x.pow(Complex.NaN).isNaN()); } @Test public void testPowInf() { TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infOne)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infInf)); } @Test public void testPowZero() { TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ZERO)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.I)); TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, Complex.I.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(Complex.ZERO), 10e-12); } @Test(expected=NullArgumentException.class) public void testpowNull() { Complex.ONE.pow(null); } @Test public void testSin() { Complex z = new Complex(3, 4); Complex expected = new Complex(3.853738, -27.01681); TestUtils.assertEquals(expected, z.sin(), 1.0e-5); } @Test public void testSinInf() { TestUtils.assertSame(infInf, oneInf.sin()); TestUtils.assertSame(infNegInf, oneNegInf.sin()); TestUtils.assertSame(Complex.NaN, infOne.sin()); TestUtils.assertSame(Complex.NaN, negInfOne.sin()); TestUtils.assertSame(Complex.NaN, infInf.sin()); TestUtils.assertSame(Complex.NaN, infNegInf.sin()); TestUtils.assertSame(Complex.NaN, negInfInf.sin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sin()); } @Test public void testSinNaN() { Assert.assertTrue(Complex.NaN.sin().isNaN()); } @Test public void testSinh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.54812, -7.61923); TestUtils.assertEquals(expected, z.sinh(), 1.0e-5); } @Test public void testSinhNaN() { Assert.assertTrue(Complex.NaN.sinh().isNaN()); } @Test public void testSinhInf() { TestUtils.assertSame(Complex.NaN, oneInf.sinh()); TestUtils.assertSame(Complex.NaN, oneNegInf.sinh()); TestUtils.assertSame(infInf, infOne.sinh()); TestUtils.assertSame(negInfInf, negInfOne.sinh()); TestUtils.assertSame(Complex.NaN, infInf.sinh()); TestUtils.assertSame(Complex.NaN, infNegInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sinh()); } @Test public void testSqrtRealPositive() { Complex z = new Complex(3, 4); Complex expected = new Complex(2, 1); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtRealZero() { Complex z = new Complex(0.0, 4); Complex expected = new Complex(1.41421, 1.41421); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtRealNegative() { Complex z = new Complex(-3.0, 4); Complex expected = new Complex(1, 2); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtImaginaryZero() { Complex z = new Complex(-3.0, 0.0); Complex expected = new Complex(0.0, 1.73205); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtImaginaryNegative() { Complex z = new Complex(-3.0, -4.0); Complex expected = new Complex(1.0, -2.0); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } @Test public void testSqrtPolar() { double r = 1; for (int i = 0; i < 5; i++) { r += i; double theta = 0; for (int j =0; j < 11; j++) { theta += pi /12; Complex z = ComplexUtils.polar2Complex(r, theta); Complex sqrtz = ComplexUtils.polar2Complex(FastMath.sqrt(r), theta / 2); TestUtils.assertEquals(sqrtz, z.sqrt(), 10e-12); } } } @Test public void testSqrtNaN() { Assert.assertTrue(Complex.NaN.sqrt().isNaN()); } @Test public void testSqrtInf() { TestUtils.assertSame(infNaN, oneInf.sqrt()); TestUtils.assertSame(infNaN, oneNegInf.sqrt()); TestUtils.assertSame(infZero, infOne.sqrt()); TestUtils.assertSame(zeroInf, negInfOne.sqrt()); TestUtils.assertSame(infNaN, infInf.sqrt()); TestUtils.assertSame(infNaN, infNegInf.sqrt()); TestUtils.assertSame(nanInf, negInfInf.sqrt()); TestUtils.assertSame(nanNegInf, negInfNegInf.sqrt()); } @Test public void testSqrt1z() { Complex z = new Complex(3, 4); Complex expected = new Complex(4.08033, -2.94094); TestUtils.assertEquals(expected, z.sqrt1z(), 1.0e-5); } @Test public void testSqrt1zNaN() { Assert.assertTrue(Complex.NaN.sqrt1z().isNaN()); } @Test public void testTan() { Complex z = new Complex(3, 4); Complex expected = new Complex(-0.000187346, 0.999356); TestUtils.assertEquals(expected, z.tan(), 1.0e-5); } @Test public void testTanNaN() { Assert.assertTrue(Complex.NaN.tan().isNaN()); } @Test public void testTanInf() { TestUtils.assertSame(zeroNaN, oneInf.tan()); TestUtils.assertSame(zeroNaN, oneNegInf.tan()); TestUtils.assertSame(Complex.NaN, infOne.tan()); TestUtils.assertSame(Complex.NaN, negInfOne.tan()); TestUtils.assertSame(Complex.NaN, infInf.tan()); TestUtils.assertSame(Complex.NaN, infNegInf.tan()); TestUtils.assertSame(Complex.NaN, negInfInf.tan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tan()); } @Test public void testTanCritical() { TestUtils.assertSame(infNaN, new Complex(pi/2, 0).tan()); TestUtils.assertSame(negInfNaN, new Complex(-pi/2, 0).tan()); } @Test public void testTanh() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.00071, 0.00490826); TestUtils.assertEquals(expected, z.tanh(), 1.0e-5); } @Test public void testTanhNaN() { Assert.assertTrue(Complex.NaN.tanh().isNaN()); } @Test public void testTanhInf() { TestUtils.assertSame(Complex.NaN, oneInf.tanh()); TestUtils.assertSame(Complex.NaN, oneNegInf.tanh()); TestUtils.assertSame(nanZero, infOne.tanh()); TestUtils.assertSame(nanZero, negInfOne.tanh()); TestUtils.assertSame(Complex.NaN, infInf.tanh()); TestUtils.assertSame(Complex.NaN, infNegInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tanh()); } @Test public void testTanhCritical() { TestUtils.assertSame(nanInf, new Complex(0, pi/2).tanh()); } /** test issue MATH-221 */ @Test public void testMath221() { Assert.assertEquals(new Complex(0,-1), new Complex(0,1).multiply(new Complex(-1,0))); } /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = -2 + 2 * i</b> * => z_0 = 1 + i * => z_1 = -1.3660 + 0.3660 * i * => z_2 = 0.3660 - 1.3660 * i * </code> * </pre> */ @Test public void testNthRoot_normal_thirdRoot() { // The complex number we want to compute all third-roots for. Complex z = new Complex(-2,2); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(1.0, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(1.0, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.3660254037844386, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(0.36602540378443843, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(0.366025403784439, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.3660254037844384, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test: computing <b>fourth roots</b> of z. * <pre> * <code> * <b>z = 5 - 2 * i</b> * => z_0 = 1.5164 - 0.1446 * i * => z_1 = 0.1446 + 1.5164 * i * => z_2 = -1.5164 + 0.1446 * i * => z_3 = -1.5164 - 0.1446 * i * </code> * </pre> */ @Test public void testNthRoot_normal_fourthRoot() { // The complex number we want to compute all third-roots for. Complex z = new Complex(5,-2); // The List holding all fourth roots Complex[] fourthRootsOfZ = z.nthRoot(4).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(4, fourthRootsOfZ.length); // test z_0 Assert.assertEquals(1.5164629308487783, fourthRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(-0.14469266210702247, fourthRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(0.14469266210702256, fourthRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(1.5164629308487783, fourthRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-1.5164629308487783, fourthRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(0.14469266210702267, fourthRootsOfZ[2].getImaginary(), 1.0e-5); // test z_3 Assert.assertEquals(-0.14469266210702275, fourthRootsOfZ[3].getReal(), 1.0e-5); Assert.assertEquals(-1.5164629308487783, fourthRootsOfZ[3].getImaginary(), 1.0e-5); } /** * Test: computing <b>third roots</b> of z. * <pre> * <code> * <b>z = 8</b> * => z_0 = 2 * => z_1 = -1 + 1.73205 * i * => z_2 = -1 - 1.73205 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_imaginaryPartEmpty() { // The number 8 has three third roots. One we all already know is the number 2. // But there are two more complex roots. Complex z = new Complex(8,0); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(2.0, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(0.0, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.0, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(1.7320508075688774, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-1.0, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.732050807568877, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test: computing <b>third roots</b> of z with real part 0. * <pre> * <code> * <b>z = 2 * i</b> * => z_0 = 1.0911 + 0.6299 * i * => z_1 = -1.0911 + 0.6299 * i * => z_2 = -2.3144 - 1.2599 * i * </code> * </pre> */ @Test public void testNthRoot_cornercase_thirdRoot_realPartZero() { // complex number with only imaginary part Complex z = new Complex(0,2); // The List holding all third roots Complex[] thirdRootsOfZ = z.nthRoot(3).toArray(new Complex[0]); // Returned Collection must not be empty! Assert.assertEquals(3, thirdRootsOfZ.length); // test z_0 Assert.assertEquals(1.0911236359717216, thirdRootsOfZ[0].getReal(), 1.0e-5); Assert.assertEquals(0.6299605249474365, thirdRootsOfZ[0].getImaginary(), 1.0e-5); // test z_1 Assert.assertEquals(-1.0911236359717216, thirdRootsOfZ[1].getReal(), 1.0e-5); Assert.assertEquals(0.6299605249474365, thirdRootsOfZ[1].getImaginary(), 1.0e-5); // test z_2 Assert.assertEquals(-2.3144374213981936E-16, thirdRootsOfZ[2].getReal(), 1.0e-5); Assert.assertEquals(-1.2599210498948732, thirdRootsOfZ[2].getImaginary(), 1.0e-5); } /** * Test cornercases with NaN and Infinity. */ @Test public void testNthRoot_cornercase_NAN_Inf() { // NaN + finite -> NaN List<Complex> roots = oneNaN.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); roots = nanZero.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); // NaN + infinite -> NaN roots = nanInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.NaN, roots.get(0)); // finite + infinite -> Inf roots = oneInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.INF, roots.get(0)); // infinite + infinite -> Inf roots = negInfInf.nthRoot(3); Assert.assertEquals(1,roots.size()); Assert.assertEquals(Complex.INF, roots.get(0)); } /** * Test standard values */ @Test public void testGetArgument() { Complex z = new Complex(1, 0); Assert.assertEquals(0.0, z.getArgument(), 1.0e-12); z = new Complex(1, 1); Assert.assertEquals(FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(0, 1); Assert.assertEquals(FastMath.PI/2, z.getArgument(), 1.0e-12); z = new Complex(-1, 1); Assert.assertEquals(3 * FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(-1, 0); Assert.assertEquals(FastMath.PI, z.getArgument(), 1.0e-12); z = new Complex(-1, -1); Assert.assertEquals(-3 * FastMath.PI/4, z.getArgument(), 1.0e-12); z = new Complex(0, -1); Assert.assertEquals(-FastMath.PI/2, z.getArgument(), 1.0e-12); z = new Complex(1, -1); Assert.assertEquals(-FastMath.PI/4, z.getArgument(), 1.0e-12); } /** * Verify atan2-style handling of infinite parts */ @Test public void testGetArgumentInf() { Assert.assertEquals(FastMath.PI/4, infInf.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI/2, oneInf.getArgument(), 1.0e-12); Assert.assertEquals(0.0, infOne.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI/2, zeroInf.getArgument(), 1.0e-12); Assert.assertEquals(0.0, infZero.getArgument(), 1.0e-12); Assert.assertEquals(FastMath.PI, negInfOne.getArgument(), 1.0e-12); Assert.assertEquals(-3.0*FastMath.PI/4, negInfNegInf.getArgument(), 1.0e-12); Assert.assertEquals(-FastMath.PI/2, oneNegInf.getArgument(), 1.0e-12); } /** * Verify that either part NaN results in NaN */ @Test public void testGetArgumentNaN() { Assert.assertTrue(Double.isNaN(nanZero.getArgument())); Assert.assertTrue(Double.isNaN(zeroNaN.getArgument())); Assert.assertTrue(Double.isNaN(Complex.NaN.getArgument())); } @Test public void testSerial() { Complex z = new Complex(3.0, 4.0); Assert.assertEquals(z, TestUtils.serializeAndRecover(z)); Complex ncmplx = (Complex)TestUtils.serializeAndRecover(oneNaN); Assert.assertEquals(nanZero, ncmplx); Assert.assertTrue(ncmplx.isNaN()); Complex infcmplx = (Complex)TestUtils.serializeAndRecover(infInf); Assert.assertEquals(infInf, infcmplx); Assert.assertTrue(infcmplx.isInfinite()); TestComplex tz = new TestComplex(3.0, 4.0); Assert.assertEquals(tz, TestUtils.serializeAndRecover(tz)); TestComplex ntcmplx = (TestComplex)TestUtils.serializeAndRecover(new TestComplex(oneNaN)); Assert.assertEquals(nanZero, ntcmplx); Assert.assertTrue(ntcmplx.isNaN()); TestComplex inftcmplx = (TestComplex)TestUtils.serializeAndRecover(new TestComplex(infInf)); Assert.assertEquals(infInf, inftcmplx); Assert.assertTrue(inftcmplx.isInfinite()); } /** * Class to test extending Complex */ public static class TestComplex extends Complex { /** * Serialization identifier. */ private static final long serialVersionUID = 3268726724160389237L; public TestComplex(double real, double imaginary) { super(real, imaginary); } public TestComplex(Complex other){ this(other.getReal(), other.getImaginary()); } @Override protected TestComplex createComplex(double real, double imaginary){ return new TestComplex(real, imaginary); } } }
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); }
com.google.javascript.jscomp.TypeCheckTest::testBadInterfaceExtendsNonExistentInterfaces
test/com/google/javascript/jscomp/TypeCheckTest.java
3,780
test/com/google/javascript/jscomp/TypeCheckTest.java
testBadInterfaceExtendsNonExistentInterfaces
/* * 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; @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 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 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.<number>\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 testParameterizedObject5() 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 = 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=): 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 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 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 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 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 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; };\n", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot add a property to a struct instance " + "after it is constructed."); } 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" + "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 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 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 = '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)); 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; }", "Bad type annotation. Unknown type namespace.Ctor"); } 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 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 {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 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"); } /** * 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 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 { // We may need to reshuffle name resolution order so that the @param // type resolves correctly. 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( "Bad type annotation. Unknown type ns.Foo", "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 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 Object\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 testCast18() throws Exception { // Mostly verifying that legacy annotations are applied // despite the parser warning. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})", "Type annotations are not allowed here. " + "Are you missing parentheses?"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}", "Type annotations are not allowed here. " + "Are you missing parentheses?"); } 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 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();"); } 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(); 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; Scope s = ns.scope; 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 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 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, 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 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 { 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 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 testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "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 testParameterized1() 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 testParameterized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testParameterized3() 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 testParameterized4() 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 testParameterized5() 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 testParameterizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createParameterizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createParameterizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } 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) .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 { 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(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, 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 `testBadInterfaceExtendsNonExistentInterfaces` for the issue `Closure-884`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-884 // // ## Issue-Title: // combining @interface and multiple @extends can crash compiler // // ## Issue-Description: // Compile this: // --------------------------------- // // ==ClosureCompiler== // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @warning\_level VERBOSE // // @output\_file\_name default.js // // ==/ClosureCompiler== // // /\*\* // \* @interface // \* @extends {unknown\_1} // \* @extends {unknown\_2} // \*/ // function Foo() {} // --------------------------------- // // => Get this.. // --------------------------------------- // 23: java.lang.NullPointerException // at com.google.javascript.jscomp.TypeCheck.checkInterfaceConflictProperties(TypeCheck.java:1544) // at com.google.javascript.jscomp.TypeCheck.visitFunction(TypeCheck.java:1635) // at com.google.javascript.jscomp.TypeCheck.visit(TypeCheck.java:761) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:509) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:502) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:502) // at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:347) // at com.google.javascript.jscomp.TypeCheck.check(TypeCheck.java:400) // at com.google.javascript.jscomp.TypeCheck.process(TypeCheck.java:371) // at com.google.javascript.jscomp.DefaultPassConfig$29$1.process(DefaultPassConfig.java:1209) // at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(PhaseOptimizer.java:303) // at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(PhaseOptimizer.java:279) // at com.google.javascript.jscomp.PhaseOptimizer.process(PhaseOptimizer.java:191) // at com.google.javascript.jscomp.Compiler.check(Compiler.java:814) // at com.google.javascript.jscomp.Compiler.compileInternal(Compiler.java:729) // at com.google.javascript.jscomp.Compiler.access$000(Compiler.java:85) // at com.google.javascript.jscomp.Compiler$2.call(Compiler.java:637) // at com.google.javascript.jscomp.Compiler$2.call(Compiler.java:634) // at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:694) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:634) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:590) // at com.google.javascript.jscomp.webservice.backend.CompilerInvokerImpl.compile(CompilerInvokerImpl.java:47) // at com.google.javascript.jscomp.webservice.backend.ServerController.executeRequest(ServerController.java:177) // at com.google.javascript.jscomp.webservice.backend.CompilationRequestHandler.serviceParsedRequest(CompilationRequestHandler.java:180) // at com.google.javascript.jscomp.webservice.backend.CompilationRequestHandler.service(CompilationRequestHandler.java:162) // at com.google.javascript.jscomp.webservice.frontend.CompilationServlet.doPost(CompilationServlet.java:83) // at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) // at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) // at org.mortbay.jet public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception {
3,780
2
3,770
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-884 ## Issue-Title: combining @interface and multiple @extends can crash compiler ## Issue-Description: Compile this: --------------------------------- // ==ClosureCompiler== // @compilation\_level SIMPLE\_OPTIMIZATIONS // @warning\_level VERBOSE // @output\_file\_name default.js // ==/ClosureCompiler== /\*\* \* @interface \* @extends {unknown\_1} \* @extends {unknown\_2} \*/ function Foo() {} --------------------------------- => Get this.. --------------------------------------- 23: java.lang.NullPointerException at com.google.javascript.jscomp.TypeCheck.checkInterfaceConflictProperties(TypeCheck.java:1544) at com.google.javascript.jscomp.TypeCheck.visitFunction(TypeCheck.java:1635) at com.google.javascript.jscomp.TypeCheck.visit(TypeCheck.java:761) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:509) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:502) at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:502) at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:347) at com.google.javascript.jscomp.TypeCheck.check(TypeCheck.java:400) at com.google.javascript.jscomp.TypeCheck.process(TypeCheck.java:371) at com.google.javascript.jscomp.DefaultPassConfig$29$1.process(DefaultPassConfig.java:1209) at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(PhaseOptimizer.java:303) at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(PhaseOptimizer.java:279) at com.google.javascript.jscomp.PhaseOptimizer.process(PhaseOptimizer.java:191) at com.google.javascript.jscomp.Compiler.check(Compiler.java:814) at com.google.javascript.jscomp.Compiler.compileInternal(Compiler.java:729) at com.google.javascript.jscomp.Compiler.access$000(Compiler.java:85) at com.google.javascript.jscomp.Compiler$2.call(Compiler.java:637) at com.google.javascript.jscomp.Compiler$2.call(Compiler.java:634) at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:694) at com.google.javascript.jscomp.Compiler.compile(Compiler.java:634) at com.google.javascript.jscomp.Compiler.compile(Compiler.java:590) at com.google.javascript.jscomp.webservice.backend.CompilerInvokerImpl.compile(CompilerInvokerImpl.java:47) at com.google.javascript.jscomp.webservice.backend.ServerController.executeRequest(ServerController.java:177) at com.google.javascript.jscomp.webservice.backend.CompilationRequestHandler.serviceParsedRequest(CompilationRequestHandler.java:180) at com.google.javascript.jscomp.webservice.backend.CompilationRequestHandler.service(CompilationRequestHandler.java:162) at com.google.javascript.jscomp.webservice.frontend.CompilationServlet.doPost(CompilationServlet.java:83) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jet ``` You are a professional Java test case writer, please create a test case named `testBadInterfaceExtendsNonExistentInterfaces` for the issue `Closure-884`, utilizing the provided issue report information and the following function signature. ```java public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception { ```
3,770
[ "com.google.javascript.jscomp.TypeCheck" ]
ad7ec3be40ca1b9241491fb1706fb3e062c517fb0ba406f4fa54b022c7efe863
public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception
// You are a professional Java test case writer, please create a test case named `testBadInterfaceExtendsNonExistentInterfaces` for the issue `Closure-884`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-884 // // ## Issue-Title: // combining @interface and multiple @extends can crash compiler // // ## Issue-Description: // Compile this: // --------------------------------- // // ==ClosureCompiler== // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @warning\_level VERBOSE // // @output\_file\_name default.js // // ==/ClosureCompiler== // // /\*\* // \* @interface // \* @extends {unknown\_1} // \* @extends {unknown\_2} // \*/ // function Foo() {} // --------------------------------- // // => Get this.. // --------------------------------------- // 23: java.lang.NullPointerException // at com.google.javascript.jscomp.TypeCheck.checkInterfaceConflictProperties(TypeCheck.java:1544) // at com.google.javascript.jscomp.TypeCheck.visitFunction(TypeCheck.java:1635) // at com.google.javascript.jscomp.TypeCheck.visit(TypeCheck.java:761) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:509) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:502) // at com.google.javascript.jscomp.NodeTraversal.traverseBranch(NodeTraversal.java:502) // at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:347) // at com.google.javascript.jscomp.TypeCheck.check(TypeCheck.java:400) // at com.google.javascript.jscomp.TypeCheck.process(TypeCheck.java:371) // at com.google.javascript.jscomp.DefaultPassConfig$29$1.process(DefaultPassConfig.java:1209) // at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(PhaseOptimizer.java:303) // at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(PhaseOptimizer.java:279) // at com.google.javascript.jscomp.PhaseOptimizer.process(PhaseOptimizer.java:191) // at com.google.javascript.jscomp.Compiler.check(Compiler.java:814) // at com.google.javascript.jscomp.Compiler.compileInternal(Compiler.java:729) // at com.google.javascript.jscomp.Compiler.access$000(Compiler.java:85) // at com.google.javascript.jscomp.Compiler$2.call(Compiler.java:637) // at com.google.javascript.jscomp.Compiler$2.call(Compiler.java:634) // at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:694) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:634) // at com.google.javascript.jscomp.Compiler.compile(Compiler.java:590) // at com.google.javascript.jscomp.webservice.backend.CompilerInvokerImpl.compile(CompilerInvokerImpl.java:47) // at com.google.javascript.jscomp.webservice.backend.ServerController.executeRequest(ServerController.java:177) // at com.google.javascript.jscomp.webservice.backend.CompilationRequestHandler.serviceParsedRequest(CompilationRequestHandler.java:180) // at com.google.javascript.jscomp.webservice.backend.CompilationRequestHandler.service(CompilationRequestHandler.java:162) // at com.google.javascript.jscomp.webservice.frontend.CompilationServlet.doPost(CompilationServlet.java:83) // at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) // at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) // at org.mortbay.jet
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; @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 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 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.<number>\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 testParameterizedObject5() 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 = 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=): 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 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 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 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 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 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; };\n", "Cannot add a property to a struct instance " + "after it is constructed."); } public void testSetprop11() throws Exception { testTypes("/**\n" + " * @constructor\n" + " * @struct\n" + " */\n" + "function Foo() {}\n" + "function Bar() {}\n" + "Bar.prototype = new Foo();\n" + "Bar.prototype.someprop = 123;\n", "Cannot add a property to a struct instance " + "after it is constructed."); } 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" + "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 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 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 = '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)); 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; }", "Bad type annotation. Unknown type namespace.Ctor"); } 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 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 {{name2: string}} */ var RecordType2;" + "/** @param {RecordType1} rec */ function f(rec) {" + " alert(rec.name2);" + "}", "Property name2 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"); } /** * 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 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 { // We may need to reshuffle name resolution order so that the @param // type resolves correctly. 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( "Bad type annotation. Unknown type ns.Foo", "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 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 Object\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 testCast18() throws Exception { // Mostly verifying that legacy annotations are applied // despite the parser warning. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = (/** @type {Foo} */ {})", "Type annotations are not allowed here. " + "Are you missing parentheses?"); // Not really encourage because of possible ambiguity but it works. testTypes("/** @constructor */ function Foo() {} \n" + "/** @type {Foo} */ var x = /** @type {Foo} */ {}", "Type annotations are not allowed here. " + "Are you missing parentheses?"); } 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 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();"); } 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(); 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; Scope s = ns.scope; 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 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 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, 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 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 { 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 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 testGenerics1() throws Exception { String FN_DECL = "/** \n" + " * @param {T} x \n" + " * @param {function(T):T} y \n" + " * @template T\n" + " */ \n" + "function f(x,y) { return y(x); }\n"; testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "/** @type {string} */" + "var result = f('hi', function(x){ out = x; return x; });"); testTypes( FN_DECL + "/** @type {string} */" + "var out;" + "var result = f(0, function(x){ out = x; return x; });", "assignment\n" + "found : number\n" + "required: string"); testTypes( FN_DECL + "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 testParameterized1() 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 testParameterized2() throws Exception { testTypes( "/** @type {!Array.<string>} */" + "var arr1 = /** @type {!Array.<number>} */([]);\n", "initializing variable\n" + "found : Array.<number>\n" + "required: Array.<string>"); } public void testParameterized3() 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 testParameterized4() 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 testParameterized5() 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 testParameterizedTypeSubtypes2() throws Exception { JSType arrayOfNumber = createParameterizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfString = createParameterizedType( ARRAY_TYPE, STRING_TYPE); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } 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) .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 { 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(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, 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 testParseOctal() throws Exception{ long value; byte [] buffer; final long MAX_OCTAL = 077777777777L; // Allowed 11 digits final long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations final String maxOctal = "777777777777"; // Maximum valid octal buffer = maxOctal.getBytes(CharsetNames.UTF_8); value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL_OVERFLOW, value); buffer[buffer.length - 1] = ' '; 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); buffer=new byte[]{' ',0}; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(0, value); }
org.apache.commons.compress.archivers.tar.TarUtilsTest::testParseOctal
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
69
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
testParseOctal
/* * 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; import org.apache.commons.compress.archivers.zip.ZipEncoding; import org.apache.commons.compress.archivers.zip.ZipEncodingHelper; import org.apache.commons.compress.utils.CharsetNames; 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 long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations final String maxOctal = "777777777777"; // Maximum valid octal buffer = maxOctal.getBytes(CharsetNames.UTF_8); value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL_OVERFLOW, value); buffer[buffer.length - 1] = ' '; 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); 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 = "abcdef ".getBytes(CharsetNames.UTF_8); // Invalid input try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } buffer = " 0 07 ".getBytes(CharsetNames.UTF_8); // Invalid - embedded space try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded space"); } catch (IllegalArgumentException expected) { } buffer = " 0\00007 ".getBytes(CharsetNames.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, final int bufsize) { byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(value,parseValue); } private void checkRoundTripOctal(final long value) { checkRoundTripOctal(value, TarConstants.SIZELEN); } public void testRoundTripOctal() { checkRoundTripOctal(0); checkRoundTripOctal(1); // checkRoundTripOctal(-1); // TODO What should this do? checkRoundTripOctal(TarConstants.MAXSIZE); // checkRoundTripOctal(0100000000000L); // TODO What should this do? checkRoundTripOctal(0, TarConstants.UIDLEN); checkRoundTripOctal(1, TarConstants.UIDLEN); checkRoundTripOctal(TarConstants.MAXID, 8); } private void checkRoundTripOctalOrBinary(final long value, final int bufsize) { byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalOrBinaryBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctalOrBinary(buffer,0, buffer.length); assertEquals(value,parseValue); } public void testRoundTripOctalOrBinary8() { testRoundTripOctalOrBinary(8); } public void testRoundTripOctalOrBinary12() { testRoundTripOctalOrBinary(12); checkRoundTripOctalOrBinary(Long.MAX_VALUE, 12); checkRoundTripOctalOrBinary(Long.MIN_VALUE + 1, 12); } private void testRoundTripOctalOrBinary(int length) { checkRoundTripOctalOrBinary(0, length); checkRoundTripOctalOrBinary(1, length); checkRoundTripOctalOrBinary(TarConstants.MAXSIZE, length); // will need binary format checkRoundTripOctalOrBinary(-1, length); // will need binary format checkRoundTripOctalOrBinary(0xff00000000000001l, length); } // 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() throws Exception { byte [] buffer = new byte[22]; TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length); assertEquals("1777777777777777777777", new String(buffer, CharsetNames.UTF_8)); } public void testOverflow() throws Exception { 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, CharsetNames.UTF_8)); 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 } public void testRoundEncoding() throws Exception { // COMPRESS-114 ZipEncoding enc = ZipEncodingHelper.getZipEncoding(CharsetNames.ISO_8859_1); String s = "0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W220\u00b1ZB\u00b1LALALA\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1CAN\u00b1\u00b1DC\u00b1\u00b1\u00b104\u00b1060302\u00b1MOE.model"; byte buff[] = new byte[100]; int len = TarUtils.formatNameBytes(s, buff, 0, buff.length, enc); assertEquals(s, TarUtils.parseName(buff, 0, len, enc)); } 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)); } public void testReadNegativeBinary8Byte() { byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } public void testReadNegativeBinary12Byte() { byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 12)); } public void testWriteNegativeBinary8Byte() { byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } // https://issues.apache.org/jira/browse/COMPRESS-191 public void testVerifyHeaderCheckSum() { byte[] valid = { // from bla.tar 116, 101, 115, 116, 49, 46, 120, 109, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 48, 54, 52, 52, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 48, 48, 48, 49, 49, 52, 50, 0, 49, 48, 55, 49, 54, 53, 52, 53, 54, 50, 54, 0, 48, 49, 50, 50, 54, 48, 0, 32, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 117, 115, 116, 97, 114, 32, 32, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertTrue(TarUtils.verifyCheckSum(valid)); byte[] compress117 = { // from COMPRESS-117 116, 101, 115, 116, 49, 46, 120, 109, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 48, 54, 52, 52, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 48, 48, 48, 49, 49, 52, 50, 0, 49, 48, 55, 49, 54, 53, 52, 53, 54, 50, 54, 0, 48, 49, 50, 50, 54, 48, 0, 32, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertTrue(TarUtils.verifyCheckSum(compress117)); byte[] invalid = { // from the testAIFF.aif file in Tika 70, 79, 82, 77, 0, 0, 15, 46, 65, 73, 70, 70, 67, 79, 77, 77, 0, 0, 0, 18, 0, 2, 0, 0, 3, -64, 0, 16, 64, 14, -84, 68, 0, 0, 0, 0, 0, 0, 83, 83, 78, 68, 0, 0, 15, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -2, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; assertFalse(TarUtils.verifyCheckSum(invalid)); } }
// You are a professional Java test case writer, please create a test case named `testParseOctal` for the issue `Compress-COMPRESS-278`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-278 // // ## Issue-Title: // Incorrect handling of NUL username and group Tar.gz entries // // ## Issue-Description: // // With version 1.8 of commons-compress it's no longer possible to decompress files from an archive if the archive contains entries having null (or being empty?) set as username and/or usergroup. With version 1.7 this still worked now I get this exception: // // // // // ``` // java.io.IOException: Error detected parsing the header // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:249) // at TestBed.AppTest.extractNoFileOwner(AppTest.java:30) // Caused by: java.lang.IllegalArgumentException: Invalid byte 32 at offset 7 in ' {NUL}' len=8 // at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:134) // at org.apache.commons.compress.archivers.tar.TarUtils.parseOctalOrBinary(TarUtils.java:173) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:953) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:940) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:324) // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:247) // ... 27 more // // // ``` // // // This exception leads to my suspision that the regression was introduced with the fix for this ticket [~~COMPRESS-262~~](https://issues.apache.org/jira/browse/COMPRESS-262 "TarArchiveInputStream fails to read entry with big user-id value"), which has a nearly identical exception provided. // // // Some test code you can run to verify it: // // // // // ``` // package TestBed; // // import java.io.File; // import java.io.FileInputStream; // import java.io.FileNotFoundException; // import java.io.IOException; // // import org.apache.commons.compress.archivers.tar.TarArchiveEntry; // import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; // import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; // import org.junit.Test; // // /** // * Unit test for simple App. // */ // public class AppTest // { // // @Test // public void extractNoFileOwner() // { // TarArchiveInputStream tarInputStream = null; // // try // { // tarInputStream = // new TarArchiveInputStream( new GzipCompressorInputStream( new FileInputStream( new File( // "/home/pknobel/redis-dist-2.8.3\_1-linux.tar.gz" ) ) ) ); // TarArchiveEntry entry; // while ( ( entry = tarInputStream.getNextTarEntry() ) != null ) // { // System.out.println( entry.getName() ); // System.out.println(entry.getUserName()+"/"+entry.getGroupName()); // } // // } // catch ( FileNotFoundException e ) // { // e.print public void testParseOctal() throws Exception {
69
27
45
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-278 ## Issue-Title: Incorrect handling of NUL username and group Tar.gz entries ## Issue-Description: With version 1.8 of commons-compress it's no longer possible to decompress files from an archive if the archive contains entries having null (or being empty?) set as username and/or usergroup. With version 1.7 this still worked now I get this exception: ``` java.io.IOException: Error detected parsing the header at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:249) at TestBed.AppTest.extractNoFileOwner(AppTest.java:30) Caused by: java.lang.IllegalArgumentException: Invalid byte 32 at offset 7 in ' {NUL}' len=8 at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:134) at org.apache.commons.compress.archivers.tar.TarUtils.parseOctalOrBinary(TarUtils.java:173) at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:953) at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:940) at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:324) at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:247) ... 27 more ``` This exception leads to my suspision that the regression was introduced with the fix for this ticket [~~COMPRESS-262~~](https://issues.apache.org/jira/browse/COMPRESS-262 "TarArchiveInputStream fails to read entry with big user-id value"), which has a nearly identical exception provided. Some test code you can run to verify it: ``` package TestBed; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.junit.Test; /** * Unit test for simple App. */ public class AppTest { @Test public void extractNoFileOwner() { TarArchiveInputStream tarInputStream = null; try { tarInputStream = new TarArchiveInputStream( new GzipCompressorInputStream( new FileInputStream( new File( "/home/pknobel/redis-dist-2.8.3\_1-linux.tar.gz" ) ) ) ); TarArchiveEntry entry; while ( ( entry = tarInputStream.getNextTarEntry() ) != null ) { System.out.println( entry.getName() ); System.out.println(entry.getUserName()+"/"+entry.getGroupName()); } } catch ( FileNotFoundException e ) { e.print ``` You are a professional Java test case writer, please create a test case named `testParseOctal` for the issue `Compress-COMPRESS-278`, utilizing the provided issue report information and the following function signature. ```java public void testParseOctal() throws Exception { ```
45
[ "org.apache.commons.compress.archivers.tar.TarUtils" ]
ae561197f3ffd9aa1f92e02dd54e2a35ea104fe6ea6c574160aa74a9533eb92c
public void testParseOctal() throws Exception
// You are a professional Java test case writer, please create a test case named `testParseOctal` for the issue `Compress-COMPRESS-278`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-278 // // ## Issue-Title: // Incorrect handling of NUL username and group Tar.gz entries // // ## Issue-Description: // // With version 1.8 of commons-compress it's no longer possible to decompress files from an archive if the archive contains entries having null (or being empty?) set as username and/or usergroup. With version 1.7 this still worked now I get this exception: // // // // // ``` // java.io.IOException: Error detected parsing the header // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:249) // at TestBed.AppTest.extractNoFileOwner(AppTest.java:30) // Caused by: java.lang.IllegalArgumentException: Invalid byte 32 at offset 7 in ' {NUL}' len=8 // at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:134) // at org.apache.commons.compress.archivers.tar.TarUtils.parseOctalOrBinary(TarUtils.java:173) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:953) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:940) // at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:324) // at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:247) // ... 27 more // // // ``` // // // This exception leads to my suspision that the regression was introduced with the fix for this ticket [~~COMPRESS-262~~](https://issues.apache.org/jira/browse/COMPRESS-262 "TarArchiveInputStream fails to read entry with big user-id value"), which has a nearly identical exception provided. // // // Some test code you can run to verify it: // // // // // ``` // package TestBed; // // import java.io.File; // import java.io.FileInputStream; // import java.io.FileNotFoundException; // import java.io.IOException; // // import org.apache.commons.compress.archivers.tar.TarArchiveEntry; // import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; // import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; // import org.junit.Test; // // /** // * Unit test for simple App. // */ // public class AppTest // { // // @Test // public void extractNoFileOwner() // { // TarArchiveInputStream tarInputStream = null; // // try // { // tarInputStream = // new TarArchiveInputStream( new GzipCompressorInputStream( new FileInputStream( new File( // "/home/pknobel/redis-dist-2.8.3\_1-linux.tar.gz" ) ) ) ); // TarArchiveEntry entry; // while ( ( entry = tarInputStream.getNextTarEntry() ) != null ) // { // System.out.println( entry.getName() ); // System.out.println(entry.getUserName()+"/"+entry.getGroupName()); // } // // } // catch ( FileNotFoundException e ) // { // e.print
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; import org.apache.commons.compress.archivers.zip.ZipEncoding; import org.apache.commons.compress.archivers.zip.ZipEncodingHelper; import org.apache.commons.compress.utils.CharsetNames; 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 long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations final String maxOctal = "777777777777"; // Maximum valid octal buffer = maxOctal.getBytes(CharsetNames.UTF_8); value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL_OVERFLOW, value); buffer[buffer.length - 1] = ' '; 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); 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 = "abcdef ".getBytes(CharsetNames.UTF_8); // Invalid input try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } buffer = " 0 07 ".getBytes(CharsetNames.UTF_8); // Invalid - embedded space try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded space"); } catch (IllegalArgumentException expected) { } buffer = " 0\00007 ".getBytes(CharsetNames.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, final int bufsize) { byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(value,parseValue); } private void checkRoundTripOctal(final long value) { checkRoundTripOctal(value, TarConstants.SIZELEN); } public void testRoundTripOctal() { checkRoundTripOctal(0); checkRoundTripOctal(1); // checkRoundTripOctal(-1); // TODO What should this do? checkRoundTripOctal(TarConstants.MAXSIZE); // checkRoundTripOctal(0100000000000L); // TODO What should this do? checkRoundTripOctal(0, TarConstants.UIDLEN); checkRoundTripOctal(1, TarConstants.UIDLEN); checkRoundTripOctal(TarConstants.MAXID, 8); } private void checkRoundTripOctalOrBinary(final long value, final int bufsize) { byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalOrBinaryBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctalOrBinary(buffer,0, buffer.length); assertEquals(value,parseValue); } public void testRoundTripOctalOrBinary8() { testRoundTripOctalOrBinary(8); } public void testRoundTripOctalOrBinary12() { testRoundTripOctalOrBinary(12); checkRoundTripOctalOrBinary(Long.MAX_VALUE, 12); checkRoundTripOctalOrBinary(Long.MIN_VALUE + 1, 12); } private void testRoundTripOctalOrBinary(int length) { checkRoundTripOctalOrBinary(0, length); checkRoundTripOctalOrBinary(1, length); checkRoundTripOctalOrBinary(TarConstants.MAXSIZE, length); // will need binary format checkRoundTripOctalOrBinary(-1, length); // will need binary format checkRoundTripOctalOrBinary(0xff00000000000001l, length); } // 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() throws Exception { byte [] buffer = new byte[22]; TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length); assertEquals("1777777777777777777777", new String(buffer, CharsetNames.UTF_8)); } public void testOverflow() throws Exception { 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, CharsetNames.UTF_8)); 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 } public void testRoundEncoding() throws Exception { // COMPRESS-114 ZipEncoding enc = ZipEncodingHelper.getZipEncoding(CharsetNames.ISO_8859_1); String s = "0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W220\u00b1ZB\u00b1LALALA\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1CAN\u00b1\u00b1DC\u00b1\u00b1\u00b104\u00b1060302\u00b1MOE.model"; byte buff[] = new byte[100]; int len = TarUtils.formatNameBytes(s, buff, 0, buff.length, enc); assertEquals(s, TarUtils.parseName(buff, 0, len, enc)); } 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)); } public void testReadNegativeBinary8Byte() { byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } public void testReadNegativeBinary12Byte() { byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 12)); } public void testWriteNegativeBinary8Byte() { byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } // https://issues.apache.org/jira/browse/COMPRESS-191 public void testVerifyHeaderCheckSum() { byte[] valid = { // from bla.tar 116, 101, 115, 116, 49, 46, 120, 109, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 48, 54, 52, 52, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 48, 48, 48, 49, 49, 52, 50, 0, 49, 48, 55, 49, 54, 53, 52, 53, 54, 50, 54, 0, 48, 49, 50, 50, 54, 48, 0, 32, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 117, 115, 116, 97, 114, 32, 32, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertTrue(TarUtils.verifyCheckSum(valid)); byte[] compress117 = { // from COMPRESS-117 116, 101, 115, 116, 49, 46, 120, 109, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 48, 54, 52, 52, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 48, 48, 48, 49, 49, 52, 50, 0, 49, 48, 55, 49, 54, 53, 52, 53, 54, 50, 54, 0, 48, 49, 50, 50, 54, 48, 0, 32, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertTrue(TarUtils.verifyCheckSum(compress117)); byte[] invalid = { // from the testAIFF.aif file in Tika 70, 79, 82, 77, 0, 0, 15, 46, 65, 73, 70, 70, 67, 79, 77, 77, 0, 0, 0, 18, 0, 2, 0, 0, 3, -64, 0, 16, 64, 14, -84, 68, 0, 0, 0, 0, 0, 0, 83, 83, 78, 68, 0, 0, 15, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -2, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; assertFalse(TarUtils.verifyCheckSum(invalid)); } }
public void testSqlDateConfigOverride() throws Exception { ObjectMapper mapper = newObjectMapper(); mapper.configOverride(java.sql.Date.class) .setFormat(JsonFormat.Value.forPattern("yyyy+MM+dd")); assertEquals("\"1980+04+14\"", mapper.writeValueAsString(java.sql.Date.valueOf("1980-04-14"))); }
com.fasterxml.jackson.databind.ser.jdk.SqlDateSerializationTest::testSqlDateConfigOverride
src/test/java/com/fasterxml/jackson/databind/ser/jdk/SqlDateSerializationTest.java
105
src/test/java/com/fasterxml/jackson/databind/ser/jdk/SqlDateSerializationTest.java
testSqlDateConfigOverride
package com.fasterxml.jackson.databind.ser.jdk; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; // Tests for `java.sql.Date`, `java.sql.Time` and `java.sql.Timestamp` public class SqlDateSerializationTest extends BaseMapTest { 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); } } // for [databind#1407] static class Person { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy.MM.dd") public java.sql.Date dateOfBirth; } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); @SuppressWarnings("deprecation") public void testSqlDate() throws IOException { // use date 1999-04-01 (note: months are 0-based, use constant) final java.sql.Date date99 = new java.sql.Date(99, Calendar.APRIL, 1); final java.sql.Date date0 = new java.sql.Date(0); // 11-Oct-2016, tatu: As per [databind#219] we really should use global // defaults in 2.9, even if this changes behavior. assertEquals(String.valueOf(date99.getTime()), MAPPER.writeValueAsString(date99)); assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsDefaultBean(0L))); // but may explicitly force timestamp too assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsNumberBean(0L))); // And also should be able to use String output as need be: ObjectWriter w = MAPPER.writer().without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); assertEquals(quote("1999-04-01"), w.writeValueAsString(date99)); assertEquals(quote(date0.toString()), w.writeValueAsString(date0)); assertEquals(aposToQuotes("{'date':'"+date0.toString()+"'}"), w.writeValueAsString(new SqlDateAsDefaultBean(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 testPatternWithSqlDate() throws Exception { ObjectMapper mapper = new ObjectMapper(); // `java.sql.Date` applies system default zone (and not UTC) mapper.setTimeZone(TimeZone.getDefault()); Person i = new Person(); i.dateOfBirth = java.sql.Date.valueOf("1980-04-14"); assertEquals(aposToQuotes("{'dateOfBirth':'1980.04.14'}"), mapper.writeValueAsString(i)); } // [databind#2064] public void testSqlDateConfigOverride() throws Exception { ObjectMapper mapper = newObjectMapper(); mapper.configOverride(java.sql.Date.class) .setFormat(JsonFormat.Value.forPattern("yyyy+MM+dd")); assertEquals("\"1980+04+14\"", mapper.writeValueAsString(java.sql.Date.valueOf("1980-04-14"))); } }
// You are a professional Java test case writer, please create a test case named `testSqlDateConfigOverride` for the issue `JacksonDatabind-2064`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2064 // // ## Issue-Title: // Cannot set custom format for SqlDateSerializer globally // // ## Issue-Description: // Version: 2.9.5 // // // After [#219](https://github.com/FasterXML/jackson-databind/issues/219) was fixed, the default format for `java.sql.Date` serialization switched from string to numeric, following the default value of `WRITE_DATES_AS_TIMESTAMPS`. // // // In order to prevent breaks, I want `java.sql.Date` to serialize as a string, without changing behavior for `java.util.Date` (which has always serialized as a number by default). // // // According to [#219 (comment)](https://github.com/FasterXML/jackson-databind/issues/219#issuecomment-370690333), I should be able to revert the behavior for `java.sql.Date` only with // // // // ``` // final ObjectMapper mapper = new ObjectMapper(); // mapper.configOverride(java.sql.Date.class).setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd")); // // ``` // // This doesn't seem to do anything, though. Looking at the code, it looks like it's because the custom format isn't actually added to `SqlDateSerializer` except in the `createContextual` method (<https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java#L59>). // // // For now, I've reverted this behavior with // // // // ``` // mapper.registerModule(new SimpleModule() { // { // addSerializer( // java.sql.Date.class, // new SqlDateSerializer().withFormat(false, new SimpleDateFormat("yyyy-MM-dd")) // ); // } // }); // // ``` // // but it seems pretty hacky so I'd prefer the other method if possible. // // // // public void testSqlDateConfigOverride() throws Exception {
105
// [databind#2064]
102
98
src/test/java/com/fasterxml/jackson/databind/ser/jdk/SqlDateSerializationTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-2064 ## Issue-Title: Cannot set custom format for SqlDateSerializer globally ## Issue-Description: Version: 2.9.5 After [#219](https://github.com/FasterXML/jackson-databind/issues/219) was fixed, the default format for `java.sql.Date` serialization switched from string to numeric, following the default value of `WRITE_DATES_AS_TIMESTAMPS`. In order to prevent breaks, I want `java.sql.Date` to serialize as a string, without changing behavior for `java.util.Date` (which has always serialized as a number by default). According to [#219 (comment)](https://github.com/FasterXML/jackson-databind/issues/219#issuecomment-370690333), I should be able to revert the behavior for `java.sql.Date` only with ``` final ObjectMapper mapper = new ObjectMapper(); mapper.configOverride(java.sql.Date.class).setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd")); ``` This doesn't seem to do anything, though. Looking at the code, it looks like it's because the custom format isn't actually added to `SqlDateSerializer` except in the `createContextual` method (<https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java#L59>). For now, I've reverted this behavior with ``` mapper.registerModule(new SimpleModule() { { addSerializer( java.sql.Date.class, new SqlDateSerializer().withFormat(false, new SimpleDateFormat("yyyy-MM-dd")) ); } }); ``` but it seems pretty hacky so I'd prefer the other method if possible. ``` You are a professional Java test case writer, please create a test case named `testSqlDateConfigOverride` for the issue `JacksonDatabind-2064`, utilizing the provided issue report information and the following function signature. ```java public void testSqlDateConfigOverride() throws Exception { ```
98
[ "com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase" ]
af126d26381db5f1cdb097b358c26253d6f7bfd812896a1a7ed33339aa90571f
public void testSqlDateConfigOverride() throws Exception
// You are a professional Java test case writer, please create a test case named `testSqlDateConfigOverride` for the issue `JacksonDatabind-2064`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2064 // // ## Issue-Title: // Cannot set custom format for SqlDateSerializer globally // // ## Issue-Description: // Version: 2.9.5 // // // After [#219](https://github.com/FasterXML/jackson-databind/issues/219) was fixed, the default format for `java.sql.Date` serialization switched from string to numeric, following the default value of `WRITE_DATES_AS_TIMESTAMPS`. // // // In order to prevent breaks, I want `java.sql.Date` to serialize as a string, without changing behavior for `java.util.Date` (which has always serialized as a number by default). // // // According to [#219 (comment)](https://github.com/FasterXML/jackson-databind/issues/219#issuecomment-370690333), I should be able to revert the behavior for `java.sql.Date` only with // // // // ``` // final ObjectMapper mapper = new ObjectMapper(); // mapper.configOverride(java.sql.Date.class).setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd")); // // ``` // // This doesn't seem to do anything, though. Looking at the code, it looks like it's because the custom format isn't actually added to `SqlDateSerializer` except in the `createContextual` method (<https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java#L59>). // // // For now, I've reverted this behavior with // // // // ``` // mapper.registerModule(new SimpleModule() { // { // addSerializer( // java.sql.Date.class, // new SqlDateSerializer().withFormat(false, new SimpleDateFormat("yyyy-MM-dd")) // ); // } // }); // // ``` // // but it seems pretty hacky so I'd prefer the other method if possible. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.ser.jdk; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; // Tests for `java.sql.Date`, `java.sql.Time` and `java.sql.Timestamp` public class SqlDateSerializationTest extends BaseMapTest { 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); } } // for [databind#1407] static class Person { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy.MM.dd") public java.sql.Date dateOfBirth; } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); @SuppressWarnings("deprecation") public void testSqlDate() throws IOException { // use date 1999-04-01 (note: months are 0-based, use constant) final java.sql.Date date99 = new java.sql.Date(99, Calendar.APRIL, 1); final java.sql.Date date0 = new java.sql.Date(0); // 11-Oct-2016, tatu: As per [databind#219] we really should use global // defaults in 2.9, even if this changes behavior. assertEquals(String.valueOf(date99.getTime()), MAPPER.writeValueAsString(date99)); assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsDefaultBean(0L))); // but may explicitly force timestamp too assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsNumberBean(0L))); // And also should be able to use String output as need be: ObjectWriter w = MAPPER.writer().without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); assertEquals(quote("1999-04-01"), w.writeValueAsString(date99)); assertEquals(quote(date0.toString()), w.writeValueAsString(date0)); assertEquals(aposToQuotes("{'date':'"+date0.toString()+"'}"), w.writeValueAsString(new SqlDateAsDefaultBean(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 testPatternWithSqlDate() throws Exception { ObjectMapper mapper = new ObjectMapper(); // `java.sql.Date` applies system default zone (and not UTC) mapper.setTimeZone(TimeZone.getDefault()); Person i = new Person(); i.dateOfBirth = java.sql.Date.valueOf("1980-04-14"); assertEquals(aposToQuotes("{'dateOfBirth':'1980.04.14'}"), mapper.writeValueAsString(i)); } // [databind#2064] public void testSqlDateConfigOverride() throws Exception { ObjectMapper mapper = newObjectMapper(); mapper.configOverride(java.sql.Date.class) .setFormat(JsonFormat.Value.forPattern("yyyy+MM+dd")); assertEquals("\"1980+04+14\"", mapper.writeValueAsString(java.sql.Date.valueOf("1980-04-14"))); } }
@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()); }
org.jsoup.parser.HtmlParserTest::testHandlesDeepSpans
src/test/java/org/jsoup/parser/HtmlParserTest.java
1,084
src/test/java/org/jsoup/parser/HtmlParserTest.java
testHandlesDeepSpans
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.Comment; 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.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, [email protected] */ 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> <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 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 < 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 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 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()); } }
// You are a professional Java test case writer, please create a test case named `testHandlesDeepSpans` for the issue `Jsoup-966`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-966 // // ## Issue-Title: // version 1.11.1 java.lang.StackOverflowError // // ## Issue-Description: // version 1.10.3 no problem // // version 1.11.1 java.lang.StackOverflowError // // Example URL: // // <http://szshb.nxszs.gov.cn/> // // <http://www.lnfsfda.gov.cn/> // // <http://www.beihai.gov.cn/> // // <http://www.fsepb.gov.cn/> // // <http://www.bhem.gov.cn> // // // // @Test public void testHandlesDeepSpans() {
1,084
68
1,073
src/test/java/org/jsoup/parser/HtmlParserTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-966 ## Issue-Title: version 1.11.1 java.lang.StackOverflowError ## Issue-Description: version 1.10.3 no problem version 1.11.1 java.lang.StackOverflowError Example URL: <http://szshb.nxszs.gov.cn/> <http://www.lnfsfda.gov.cn/> <http://www.beihai.gov.cn/> <http://www.fsepb.gov.cn/> <http://www.bhem.gov.cn> ``` You are a professional Java test case writer, please create a test case named `testHandlesDeepSpans` for the issue `Jsoup-966`, utilizing the provided issue report information and the following function signature. ```java @Test public void testHandlesDeepSpans() { ```
1,073
[ "org.jsoup.parser.HtmlTreeBuilder" ]
afb69967487e5d537d472d6f9fda0ad1685fd6fd54c0c7d7b8703934112b7cf1
@Test public void testHandlesDeepSpans()
// You are a professional Java test case writer, please create a test case named `testHandlesDeepSpans` for the issue `Jsoup-966`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-966 // // ## Issue-Title: // version 1.11.1 java.lang.StackOverflowError // // ## Issue-Description: // version 1.10.3 no problem // // version 1.11.1 java.lang.StackOverflowError // // Example URL: // // <http://szshb.nxszs.gov.cn/> // // <http://www.lnfsfda.gov.cn/> // // <http://www.beihai.gov.cn/> // // <http://www.fsepb.gov.cn/> // // <http://www.bhem.gov.cn> // // // //
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.Comment; 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.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, [email protected] */ 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> <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 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 < 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 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 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 testRoundTripOctalOrBinary8() { testRoundTripOctalOrBinary(8); }
org.apache.commons.compress.archivers.tar.TarUtilsTest::testRoundTripOctalOrBinary8
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
148
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
testRoundTripOctalOrBinary8
/* * 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 static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.commons.compress.archivers.zip.ZipEncoding; import org.apache.commons.compress.archivers.zip.ZipEncodingHelper; import org.apache.commons.compress.utils.CharsetNames; import org.junit.Test; public class TarUtilsTest { @Test public void testName(){ byte [] buff = new byte[20]; final 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); } @Test public void testParseOctal() throws Exception{ long value; byte [] buffer; final long MAX_OCTAL = 077777777777L; // Allowed 11 digits final long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations final String maxOctal = "777777777777"; // Maximum valid octal buffer = maxOctal.getBytes(CharsetNames.UTF_8); value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL_OVERFLOW, value); buffer[buffer.length - 1] = ' '; 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); buffer=new byte[]{' ',0}; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(0, value); } @Test 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 (final 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 (final IllegalArgumentException expected) { } buffer = "abcdef ".getBytes(CharsetNames.UTF_8); // Invalid input try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException expected) { } buffer = " 0 07 ".getBytes(CharsetNames.UTF_8); // Invalid - embedded space try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded space"); } catch (final IllegalArgumentException expected) { } buffer = " 0\00007 ".getBytes(CharsetNames.UTF_8); // Invalid - embedded NUL try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded NUL"); } catch (final IllegalArgumentException expected) { } } private void checkRoundTripOctal(final long value, final int bufsize) { final byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(value,parseValue); } private void checkRoundTripOctal(final long value) { checkRoundTripOctal(value, TarConstants.SIZELEN); } @Test public void testRoundTripOctal() { checkRoundTripOctal(0); checkRoundTripOctal(1); // checkRoundTripOctal(-1); // TODO What should this do? checkRoundTripOctal(TarConstants.MAXSIZE); // checkRoundTripOctal(0100000000000L); // TODO What should this do? checkRoundTripOctal(0, TarConstants.UIDLEN); checkRoundTripOctal(1, TarConstants.UIDLEN); checkRoundTripOctal(TarConstants.MAXID, 8); } private void checkRoundTripOctalOrBinary(final long value, final int bufsize) { final byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalOrBinaryBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctalOrBinary(buffer,0, buffer.length); assertEquals(value,parseValue); } @Test public void testRoundTripOctalOrBinary8() { testRoundTripOctalOrBinary(8); } @Test public void testRoundTripOctalOrBinary12() { testRoundTripOctalOrBinary(12); checkRoundTripOctalOrBinary(Long.MAX_VALUE, 12); checkRoundTripOctalOrBinary(Long.MIN_VALUE + 1, 12); } private void testRoundTripOctalOrBinary(final int length) { checkRoundTripOctalOrBinary(0, length); checkRoundTripOctalOrBinary(1, length); checkRoundTripOctalOrBinary(TarConstants.MAXSIZE, length); // will need binary format checkRoundTripOctalOrBinary(-1, length); // will need binary format checkRoundTripOctalOrBinary(0xff00000000000001l, length); } // Check correct trailing bytes are generated @Test public void testTrailers() { final 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 } @Test public void testNegative() throws Exception { final byte [] buffer = new byte[22]; TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length); assertEquals("1777777777777777777777", new String(buffer, CharsetNames.UTF_8)); } @Test public void testOverflow() throws Exception { final 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, CharsetNames.UTF_8)); try { TarUtils.formatUnsignedOctalString(017777777L, buffer, 0, buffer.length); fail("Should have cause IllegalArgumentException"); } catch (final IllegalArgumentException expected) { } } @Test public void testRoundTripNames(){ checkName(""); checkName("The quick brown fox\n"); checkName("\177"); // checkName("\0"); // does not work, because NUL is ignored } @Test public void testRoundEncoding() throws Exception { // COMPRESS-114 final ZipEncoding enc = ZipEncodingHelper.getZipEncoding(CharsetNames.ISO_8859_1); final String s = "0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W220\u00b1ZB\u00b1LALALA\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1CAN\u00b1\u00b1DC\u00b1\u00b1\u00b104\u00b1060302\u00b1MOE.model"; final byte buff[] = new byte[100]; final int len = TarUtils.formatNameBytes(s, buff, 0, buff.length, enc); assertEquals(s, TarUtils.parseName(buff, 0, len, enc)); } private void checkName(final String string) { final byte buff[] = new byte[100]; final int len = TarUtils.formatNameBytes(string, buff, 0, buff.length); assertEquals(string, TarUtils.parseName(buff, 0, len)); } @Test public void testReadNegativeBinary8Byte() { final byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } @Test public void testReadNegativeBinary12Byte() { final byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 12)); } @Test public void testWriteNegativeBinary8Byte() { final byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } // https://issues.apache.org/jira/browse/COMPRESS-191 @Test public void testVerifyHeaderCheckSum() { final byte[] valid = { // from bla.tar 116, 101, 115, 116, 49, 46, 120, 109, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 48, 54, 52, 52, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 48, 48, 48, 49, 49, 52, 50, 0, 49, 48, 55, 49, 54, 53, 52, 53, 54, 50, 54, 0, 48, 49, 50, 50, 54, 48, 0, 32, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 117, 115, 116, 97, 114, 32, 32, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertTrue(TarUtils.verifyCheckSum(valid)); final byte[] compress117 = { // from COMPRESS-117 (byte) 0x37, (byte) 0x7a, (byte) 0x43, (byte) 0x2e, (byte) 0x74, (byte) 0x78, (byte) 0x74, (byte) 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0x31, (byte) 0x30, (byte) 0x30, (byte) 0x37, (byte) 0x37, (byte) 0x37, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x30, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x30, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x31, (byte) 0x33, (byte) 0x30, (byte) 0x33, (byte) 0x33, (byte) 0x20, (byte) 0x31, (byte) 0x31, (byte) 0x31, (byte) 0x31, (byte) 0x35, (byte) 0x31, (byte) 0x36, (byte) 0x36, (byte) 0x30, (byte) 0x31, (byte) 0x36, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x35, (byte) 0x34, (byte) 0x31, (byte) 0x37, (byte) 0x20, (byte) 0x00, (byte) 0x30, (byte) 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; assertTrue(TarUtils.verifyCheckSum(compress117)); final byte[] invalid = { // from the testAIFF.aif file in Tika 70, 79, 82, 77, 0, 0, 15, 46, 65, 73, 70, 70, 67, 79, 77, 77, 0, 0, 0, 18, 0, 2, 0, 0, 3, -64, 0, 16, 64, 14, -84, 68, 0, 0, 0, 0, 0, 0, 83, 83, 78, 68, 0, 0, 15, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -2, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; assertFalse(TarUtils.verifyCheckSum(invalid)); } @Test public void testParseOctalCompress330() throws Exception{ final long expected = 0100000; final byte [] buffer = new byte[] { 32, 32, 32, 32, 32, 49, 48, 48, 48, 48, 48, 32 }; assertEquals(expected, TarUtils.parseOctalOrBinary(buffer, 0, buffer.length)); } }
// You are a professional Java test case writer, please create a test case named `testRoundTripOctalOrBinary8` for the issue `Compress-COMPRESS-411`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-411 // // ## Issue-Title: // TarUtils.formatLongOctalOrBinaryBytes never uses result of formatLongBinary // // ## Issue-Description: // // if the length < 9, formatLongBinary is executed, then overwritten by the results of formatBigIntegerBinary. // // // If the results are not ignored, a unit test would fail. // // // Also, do the binary hacks need to support negative numbers? // // // // // @Test public void testRoundTripOctalOrBinary8() {
148
45
145
src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-411 ## Issue-Title: TarUtils.formatLongOctalOrBinaryBytes never uses result of formatLongBinary ## Issue-Description: if the length < 9, formatLongBinary is executed, then overwritten by the results of formatBigIntegerBinary. If the results are not ignored, a unit test would fail. Also, do the binary hacks need to support negative numbers? ``` You are a professional Java test case writer, please create a test case named `testRoundTripOctalOrBinary8` for the issue `Compress-COMPRESS-411`, utilizing the provided issue report information and the following function signature. ```java @Test public void testRoundTripOctalOrBinary8() { ```
145
[ "org.apache.commons.compress.archivers.tar.TarUtils" ]
b008ad6afec5773c0ece7e59503f0aad98986c1b5ed80ecdc8c3d481ba4328ba
@Test public void testRoundTripOctalOrBinary8()
// You are a professional Java test case writer, please create a test case named `testRoundTripOctalOrBinary8` for the issue `Compress-COMPRESS-411`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-411 // // ## Issue-Title: // TarUtils.formatLongOctalOrBinaryBytes never uses result of formatLongBinary // // ## Issue-Description: // // if the length < 9, formatLongBinary is executed, then overwritten by the results of formatBigIntegerBinary. // // // If the results are not ignored, a unit test would fail. // // // Also, do the binary hacks need to support negative numbers? // // // // //
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 static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.commons.compress.archivers.zip.ZipEncoding; import org.apache.commons.compress.archivers.zip.ZipEncodingHelper; import org.apache.commons.compress.utils.CharsetNames; import org.junit.Test; public class TarUtilsTest { @Test public void testName(){ byte [] buff = new byte[20]; final 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); } @Test public void testParseOctal() throws Exception{ long value; byte [] buffer; final long MAX_OCTAL = 077777777777L; // Allowed 11 digits final long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations final String maxOctal = "777777777777"; // Maximum valid octal buffer = maxOctal.getBytes(CharsetNames.UTF_8); value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(MAX_OCTAL_OVERFLOW, value); buffer[buffer.length - 1] = ' '; 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); buffer=new byte[]{' ',0}; value = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(0, value); } @Test 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 (final 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 (final IllegalArgumentException expected) { } buffer = "abcdef ".getBytes(CharsetNames.UTF_8); // Invalid input try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException expected) { } buffer = " 0 07 ".getBytes(CharsetNames.UTF_8); // Invalid - embedded space try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded space"); } catch (final IllegalArgumentException expected) { } buffer = " 0\00007 ".getBytes(CharsetNames.UTF_8); // Invalid - embedded NUL try { TarUtils.parseOctal(buffer,0, buffer.length); fail("Expected IllegalArgumentException - embedded NUL"); } catch (final IllegalArgumentException expected) { } } private void checkRoundTripOctal(final long value, final int bufsize) { final byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctal(buffer,0, buffer.length); assertEquals(value,parseValue); } private void checkRoundTripOctal(final long value) { checkRoundTripOctal(value, TarConstants.SIZELEN); } @Test public void testRoundTripOctal() { checkRoundTripOctal(0); checkRoundTripOctal(1); // checkRoundTripOctal(-1); // TODO What should this do? checkRoundTripOctal(TarConstants.MAXSIZE); // checkRoundTripOctal(0100000000000L); // TODO What should this do? checkRoundTripOctal(0, TarConstants.UIDLEN); checkRoundTripOctal(1, TarConstants.UIDLEN); checkRoundTripOctal(TarConstants.MAXID, 8); } private void checkRoundTripOctalOrBinary(final long value, final int bufsize) { final byte [] buffer = new byte[bufsize]; long parseValue; TarUtils.formatLongOctalOrBinaryBytes(value, buffer, 0, buffer.length); parseValue = TarUtils.parseOctalOrBinary(buffer,0, buffer.length); assertEquals(value,parseValue); } @Test public void testRoundTripOctalOrBinary8() { testRoundTripOctalOrBinary(8); } @Test public void testRoundTripOctalOrBinary12() { testRoundTripOctalOrBinary(12); checkRoundTripOctalOrBinary(Long.MAX_VALUE, 12); checkRoundTripOctalOrBinary(Long.MIN_VALUE + 1, 12); } private void testRoundTripOctalOrBinary(final int length) { checkRoundTripOctalOrBinary(0, length); checkRoundTripOctalOrBinary(1, length); checkRoundTripOctalOrBinary(TarConstants.MAXSIZE, length); // will need binary format checkRoundTripOctalOrBinary(-1, length); // will need binary format checkRoundTripOctalOrBinary(0xff00000000000001l, length); } // Check correct trailing bytes are generated @Test public void testTrailers() { final 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 } @Test public void testNegative() throws Exception { final byte [] buffer = new byte[22]; TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length); assertEquals("1777777777777777777777", new String(buffer, CharsetNames.UTF_8)); } @Test public void testOverflow() throws Exception { final 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, CharsetNames.UTF_8)); try { TarUtils.formatUnsignedOctalString(017777777L, buffer, 0, buffer.length); fail("Should have cause IllegalArgumentException"); } catch (final IllegalArgumentException expected) { } } @Test public void testRoundTripNames(){ checkName(""); checkName("The quick brown fox\n"); checkName("\177"); // checkName("\0"); // does not work, because NUL is ignored } @Test public void testRoundEncoding() throws Exception { // COMPRESS-114 final ZipEncoding enc = ZipEncodingHelper.getZipEncoding(CharsetNames.ISO_8859_1); final String s = "0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W220\u00b1ZB\u00b1LALALA\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1CAN\u00b1\u00b1DC\u00b1\u00b1\u00b104\u00b1060302\u00b1MOE.model"; final byte buff[] = new byte[100]; final int len = TarUtils.formatNameBytes(s, buff, 0, buff.length, enc); assertEquals(s, TarUtils.parseName(buff, 0, len, enc)); } private void checkName(final String string) { final byte buff[] = new byte[100]; final int len = TarUtils.formatNameBytes(string, buff, 0, buff.length); assertEquals(string, TarUtils.parseName(buff, 0, len)); } @Test public void testReadNegativeBinary8Byte() { final byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } @Test public void testReadNegativeBinary12Byte() { final byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 12)); } @Test public void testWriteNegativeBinary8Byte() { final byte[] b = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef, }; assertEquals(-3601l, TarUtils.parseOctalOrBinary(b, 0, 8)); } // https://issues.apache.org/jira/browse/COMPRESS-191 @Test public void testVerifyHeaderCheckSum() { final byte[] valid = { // from bla.tar 116, 101, 115, 116, 49, 46, 120, 109, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 48, 48, 48, 54, 52, 52, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 55, 54, 53, 0, 48, 48, 48, 48, 48, 48, 48, 49, 49, 52, 50, 0, 49, 48, 55, 49, 54, 53, 52, 53, 54, 50, 54, 0, 48, 49, 50, 50, 54, 48, 0, 32, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 117, 115, 116, 97, 114, 32, 32, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 99, 117, 114, 100, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; assertTrue(TarUtils.verifyCheckSum(valid)); final byte[] compress117 = { // from COMPRESS-117 (byte) 0x37, (byte) 0x7a, (byte) 0x43, (byte) 0x2e, (byte) 0x74, (byte) 0x78, (byte) 0x74, (byte) 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0x31, (byte) 0x30, (byte) 0x30, (byte) 0x37, (byte) 0x37, (byte) 0x37, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x30, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x30, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x31, (byte) 0x33, (byte) 0x30, (byte) 0x33, (byte) 0x33, (byte) 0x20, (byte) 0x31, (byte) 0x31, (byte) 0x31, (byte) 0x31, (byte) 0x35, (byte) 0x31, (byte) 0x36, (byte) 0x36, (byte) 0x30, (byte) 0x31, (byte) 0x36, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x35, (byte) 0x34, (byte) 0x31, (byte) 0x37, (byte) 0x20, (byte) 0x00, (byte) 0x30, (byte) 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; assertTrue(TarUtils.verifyCheckSum(compress117)); final byte[] invalid = { // from the testAIFF.aif file in Tika 70, 79, 82, 77, 0, 0, 15, 46, 65, 73, 70, 70, 67, 79, 77, 77, 0, 0, 0, 18, 0, 2, 0, 0, 3, -64, 0, 16, 64, 14, -84, 68, 0, 0, 0, 0, 0, 0, 83, 83, 78, 68, 0, 0, 15, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 1, -1, -2, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -1, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 2, -1, -2, 0, 2, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, -1, -1, 0, 2, -1, -2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0, 0, 0, 0, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; assertFalse(TarUtils.verifyCheckSum(invalid)); } @Test public void testParseOctalCompress330() throws Exception{ final long expected = 0100000; final byte [] buffer = new byte[] { 32, 32, 32, 32, 32, 49, 48, 48, 48, 48, 48, 32 }; assertEquals(expected, TarUtils.parseOctalOrBinary(buffer, 0, buffer.length)); } }
public void testRootEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); // endpoint is root double result = solver.solve(f, Math.PI, 4); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, Math.PI, 4, 3.5); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI, 3.07); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); }
org.apache.commons.math.analysis.solvers.BrentSolverTest::testRootEndpoints
src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java
321
src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java
testRootEndpoints
/* * 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 junit.framework.TestCase; import org.apache.commons.math.MathException; import org.apache.commons.math.analysis.MonitoredFunction; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.SinFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; /** * Testcase for UnivariateRealSolver. * Because Brent-Dekker is guaranteed to converge in less than the default * maximum iteration count due to bisection fallback, it is quite hard to * debug. I include measured iteration counts plus one in order to detect * regressions. On average Brent-Dekker should use 4..5 iterations for the * default absolute accuracy of 10E-8 for sinus and the quintic function around * zero, and 5..10 iterations for the other zeros. * * @version $Revision:670469 $ $Date:2008-06-23 10:01:38 +0200 (lun., 23 juin 2008) $ */ public final class BrentSolverTest extends TestCase { public BrentSolverTest(String name) { super(name); } @Deprecated public void testDeprecated() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(f); // Somewhat benign interval. The function is monotone. result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(f); result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testSinZero() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(); // Somewhat benign interval. The function is monotone. result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(); result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testQuinticZero() throws MathException { // The quintic function has zeros at 0, +-0.5 and +-1. // Around the root of 0 the function is well behaved, with a second derivative // of zero a 0. // The other roots are less well to find, in particular the root at 1, because // the function grows fast for x>1. // The function has extrema (first derivative is zero) at 0.27195613 and 0.82221643, // intervals containing these values are harder for the solvers. UnivariateRealFunction f = new QuinticFunction(); double result; // Brent-Dekker solver. UnivariateRealSolver solver = new BrentSolver(); // Symmetric bracket around 0. Test whether solvers can handle hitting // the root in the first iteration. result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); assertTrue(solver.getIterationCount() <= 2); // 1 iterations on i586 JDK 1.4.1. // Asymmetric bracket around 0, just for fun. Contains extremum. result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); // Large bracket around 0. Contains two extrema. result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Benign bracket around 0.5, function is monotonous. result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Less benign bracket around 0.5, contains one extremum. result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Large, less benign bracket around 0.5, contains both extrema. result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Relatively benign bracket around 1, function is monotonous. Fast growth for x>1 // is still a problem. result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Less benign bracket around 1 with extremum. result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Large bracket around 1. Monotonous. result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); // Large bracket around 1. Interval contains extremum. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); // Very large bracket around 1 for testing fast growth behaviour. result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 12 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 13); // Secant solver. solver = new SecantSolver(); result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 1 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 2); result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // The followig is especially slow because the solver first has to reduce // the bracket to exclude the extremum. After that, convergence is rapide. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // Static solve method result = UnivariateRealSolverUtils.solve(f, -0.2, 0.2); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = UnivariateRealSolverUtils.solve(f, -0.1, 0.3); assertEquals(result, 0, 1E-8); result = UnivariateRealSolverUtils.solve(f, -0.3, 0.45); assertEquals(result, 0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.3, 0.7); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.2, 0.6); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.05, 0.95); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.25); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.8, 1.2); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.75); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.55, 1.45); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 5); assertEquals(result, 1.0, 1E-6); } public void testRootEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); // endpoint is root double result = solver.solve(f, Math.PI, 4); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, Math.PI, 4, 3.5); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI, 3.07); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); } public void testBadEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); try { // bad interval solver.solve(f, 1, -1); fail("Expecting IllegalArgumentException - bad interval"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5, 1.2); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } } public void testInitialGuess() throws MathException { MonitoredFunction f = new MonitoredFunction(new QuinticFunction()); UnivariateRealSolver solver = new BrentSolver(); double result; // no guess result = solver.solve(f, 0.6, 7.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); int referenceCallsCount = f.getCallsCount(); assertTrue(referenceCallsCount >= 13); // invalid guess (it *is* a root, but outside of the range) try { result = solver.solve(f, 0.6, 7.0, 0.0); fail("an IllegalArgumentException was expected"); } catch (IllegalArgumentException iae) { // expected behaviour } catch (Exception e) { fail("wrong exception caught: " + e.getMessage()); } // bad guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.61); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() > referenceCallsCount); // good guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.999999); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() < referenceCallsCount); // perfect guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 1.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertEquals(0, solver.getIterationCount()); assertEquals(1, f.getCallsCount()); } }
// You are a professional Java test case writer, please create a test case named `testRootEndpoints` for the issue `Math-MATH-344`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-344 // // ## Issue-Title: // Brent solver returns the wrong value if either bracket endpoint is root // // ## Issue-Description: // // The solve(final UnivariateRealFunction f, final double min, final double max, final double initial) function returns yMin or yMax if min or max are deemed to be roots, respectively, instead of min or max. // // // // // public void testRootEndpoints() throws Exception {
321
72
304
src/test/java/org/apache/commons/math/analysis/solvers/BrentSolverTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-344 ## Issue-Title: Brent solver returns the wrong value if either bracket endpoint is root ## Issue-Description: The solve(final UnivariateRealFunction f, final double min, final double max, final double initial) function returns yMin or yMax if min or max are deemed to be roots, respectively, instead of min or max. ``` You are a professional Java test case writer, please create a test case named `testRootEndpoints` for the issue `Math-MATH-344`, utilizing the provided issue report information and the following function signature. ```java public void testRootEndpoints() throws Exception { ```
304
[ "org.apache.commons.math.analysis.solvers.BrentSolver" ]
b00c45a46b2eca6acac4e801a1d8b70c17f92e2282b99afa8f09e99baeadd52e
public void testRootEndpoints() throws Exception
// You are a professional Java test case writer, please create a test case named `testRootEndpoints` for the issue `Math-MATH-344`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-344 // // ## Issue-Title: // Brent solver returns the wrong value if either bracket endpoint is root // // ## Issue-Description: // // The solve(final UnivariateRealFunction f, final double min, final double max, final double initial) function returns yMin or yMax if min or max are deemed to be roots, respectively, instead of min or max. // // // // //
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 junit.framework.TestCase; import org.apache.commons.math.MathException; import org.apache.commons.math.analysis.MonitoredFunction; import org.apache.commons.math.analysis.QuinticFunction; import org.apache.commons.math.analysis.SinFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; /** * Testcase for UnivariateRealSolver. * Because Brent-Dekker is guaranteed to converge in less than the default * maximum iteration count due to bisection fallback, it is quite hard to * debug. I include measured iteration counts plus one in order to detect * regressions. On average Brent-Dekker should use 4..5 iterations for the * default absolute accuracy of 10E-8 for sinus and the quintic function around * zero, and 5..10 iterations for the other zeros. * * @version $Revision:670469 $ $Date:2008-06-23 10:01:38 +0200 (lun., 23 juin 2008) $ */ public final class BrentSolverTest extends TestCase { public BrentSolverTest(String name) { super(name); } @Deprecated public void testDeprecated() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(f); // Somewhat benign interval. The function is monotone. result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(f); result = solver.solve(3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testSinZero() throws MathException { // The sinus function is behaved well around the root at #pi. The second // order derivative is zero, which means linar approximating methods will // still converge quadratically. UnivariateRealFunction f = new SinFunction(); double result; UnivariateRealSolver solver = new BrentSolver(); // Somewhat benign interval. The function is monotone. result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); // Larger and somewhat less benign interval. The function is grows first. result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); solver = new SecantSolver(); result = solver.solve(f, 3, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 4 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 5); result = solver.solve(f, 1, 4); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, Math.PI, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); assertEquals(result, solver.getResult(), 0); } public void testQuinticZero() throws MathException { // The quintic function has zeros at 0, +-0.5 and +-1. // Around the root of 0 the function is well behaved, with a second derivative // of zero a 0. // The other roots are less well to find, in particular the root at 1, because // the function grows fast for x>1. // The function has extrema (first derivative is zero) at 0.27195613 and 0.82221643, // intervals containing these values are harder for the solvers. UnivariateRealFunction f = new QuinticFunction(); double result; // Brent-Dekker solver. UnivariateRealSolver solver = new BrentSolver(); // Symmetric bracket around 0. Test whether solvers can handle hitting // the root in the first iteration. result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); assertTrue(solver.getIterationCount() <= 2); // 1 iterations on i586 JDK 1.4.1. // Asymmetric bracket around 0, just for fun. Contains extremum. result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); // Large bracket around 0. Contains two extrema. result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Benign bracket around 0.5, function is monotonous. result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Less benign bracket around 0.5, contains one extremum. result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); // Large, less benign bracket around 0.5, contains both extrema. result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Relatively benign bracket around 1, function is monotonous. Fast growth for x>1 // is still a problem. result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Less benign bracket around 1 with extremum. result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); // Large bracket around 1. Monotonous. result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); // Large bracket around 1. Interval contains extremum. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); // Very large bracket around 1 for testing fast growth behaviour. result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 12 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 13); // Secant solver. solver = new SecantSolver(); result = solver.solve(f, -0.2, 0.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 1 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 2); result = solver.solve(f, -0.1, 0.3); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 5 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 6); result = solver.solve(f, -0.3, 0.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.3, 0.7); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.2, 0.6); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 6 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 7); result = solver.solve(f, 0.05, 0.95); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 0.5, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.25); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 10 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 11); result = solver.solve(f, 0.8, 1.2); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 8 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 9); result = solver.solve(f, 0.85, 1.75); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // The followig is especially slow because the solver first has to reduce // the bracket to exclude the extremum. After that, convergence is rapide. result = solver.solve(f, 0.55, 1.45); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 7 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 8); result = solver.solve(f, 0.85, 5); //System.out.println( // "Root: " + result + " Iterations: " + solver.getIterationCount()); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); // 14 iterations on i586 JDK 1.4.1. assertTrue(solver.getIterationCount() <= 15); // Static solve method result = UnivariateRealSolverUtils.solve(f, -0.2, 0.2); assertEquals(result, 0, solver.getAbsoluteAccuracy()); result = UnivariateRealSolverUtils.solve(f, -0.1, 0.3); assertEquals(result, 0, 1E-8); result = UnivariateRealSolverUtils.solve(f, -0.3, 0.45); assertEquals(result, 0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.3, 0.7); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.2, 0.6); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.05, 0.95); assertEquals(result, 0.5, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.25); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.8, 1.2); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 1.75); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.55, 1.45); assertEquals(result, 1.0, 1E-6); result = UnivariateRealSolverUtils.solve(f, 0.85, 5); assertEquals(result, 1.0, 1E-6); } public void testRootEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); // endpoint is root double result = solver.solve(f, Math.PI, 4); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, Math.PI, 4, 3.5); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); result = solver.solve(f, 3, Math.PI, 3.07); assertEquals(Math.PI, result, solver.getAbsoluteAccuracy()); } public void testBadEndpoints() throws Exception { UnivariateRealFunction f = new SinFunction(); UnivariateRealSolver solver = new BrentSolver(); try { // bad interval solver.solve(f, 1, -1); fail("Expecting IllegalArgumentException - bad interval"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } try { // no bracket solver.solve(f, 1, 1.5, 1.2); fail("Expecting IllegalArgumentException - non-bracketing"); } catch (IllegalArgumentException ex) { // expected } } public void testInitialGuess() throws MathException { MonitoredFunction f = new MonitoredFunction(new QuinticFunction()); UnivariateRealSolver solver = new BrentSolver(); double result; // no guess result = solver.solve(f, 0.6, 7.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); int referenceCallsCount = f.getCallsCount(); assertTrue(referenceCallsCount >= 13); // invalid guess (it *is* a root, but outside of the range) try { result = solver.solve(f, 0.6, 7.0, 0.0); fail("an IllegalArgumentException was expected"); } catch (IllegalArgumentException iae) { // expected behaviour } catch (Exception e) { fail("wrong exception caught: " + e.getMessage()); } // bad guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.61); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() > referenceCallsCount); // good guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 0.999999); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertTrue(f.getCallsCount() < referenceCallsCount); // perfect guess f.setCallsCount(0); result = solver.solve(f, 0.6, 7.0, 1.0); assertEquals(result, 1.0, solver.getAbsoluteAccuracy()); assertEquals(0, solver.getIterationCount()); assertEquals(1, f.getCallsCount()); } }
@Test public void testOverrideMeanWithMathClass() throws Exception { double[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setMeanImpl(new Mean()); for(double i : scores) { stats.addValue(i); } Assert.assertEquals((new Mean()).evaluate(scores),stats.getMean(), 0); }
org.apache.commons.math.stat.descriptive.SummaryStatisticsTest::testOverrideMeanWithMathClass
src/test/java/org/apache/commons/math/stat/descriptive/SummaryStatisticsTest.java
335
src/test/java/org/apache/commons/math/stat/descriptive/SummaryStatisticsTest.java
testOverrideMeanWithMathClass
/* * 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.descriptive; import org.apache.commons.math.TestUtils; import org.apache.commons.math.stat.descriptive.moment.GeometricMean; import org.apache.commons.math.stat.descriptive.moment.Mean; import org.apache.commons.math.stat.descriptive.moment.Variance; import org.apache.commons.math.stat.descriptive.summary.Sum; import org.apache.commons.math.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Test cases for the {@link SummaryStatistics} class. * * @version $Id$ */ public class SummaryStatisticsTest { private double one = 1; private float twoF = 2; private long twoL = 2; private int three = 3; private double mean = 2; private double sumSq = 18; private double sum = 8; private double var = 0.666666666666666666667; private double popVar = 0.5; private double std = FastMath.sqrt(var); private double n = 4; private double min = 1; private double max = 3; private double tolerance = 10E-15; protected SummaryStatistics createSummaryStatistics() { return new SummaryStatistics(); } /** test stats */ @Test public void testStats() { SummaryStatistics u = createSummaryStatistics(); Assert.assertEquals("total count",0,u.getN(),tolerance); u.addValue(one); u.addValue(twoF); u.addValue(twoL); u.addValue(three); Assert.assertEquals("N",n,u.getN(),tolerance); Assert.assertEquals("sum",sum,u.getSum(),tolerance); Assert.assertEquals("sumsq",sumSq,u.getSumsq(),tolerance); Assert.assertEquals("var",var,u.getVariance(),tolerance); Assert.assertEquals("population var",popVar,u.getPopulationVariance(),tolerance); Assert.assertEquals("std",std,u.getStandardDeviation(),tolerance); Assert.assertEquals("mean",mean,u.getMean(),tolerance); Assert.assertEquals("min",min,u.getMin(),tolerance); Assert.assertEquals("max",max,u.getMax(),tolerance); u.clear(); Assert.assertEquals("total count",0,u.getN(),tolerance); } @Test public void testN0andN1Conditions() throws Exception { SummaryStatistics u = createSummaryStatistics(); Assert.assertTrue("Mean of n = 0 set should be NaN", Double.isNaN( u.getMean() ) ); Assert.assertTrue("Standard Deviation of n = 0 set should be NaN", Double.isNaN( u.getStandardDeviation() ) ); Assert.assertTrue("Variance of n = 0 set should be NaN", Double.isNaN(u.getVariance() ) ); /* n=1 */ u.addValue(one); Assert.assertTrue("mean should be one (n = 1)", u.getMean() == one); Assert.assertTrue("geometric should be one (n = 1) instead it is " + u.getGeometricMean(), u.getGeometricMean() == one); Assert.assertTrue("Std should be zero (n = 1)", u.getStandardDeviation() == 0.0); Assert.assertTrue("variance should be zero (n = 1)", u.getVariance() == 0.0); /* n=2 */ u.addValue(twoF); Assert.assertTrue("Std should not be zero (n = 2)", u.getStandardDeviation() != 0.0); Assert.assertTrue("variance should not be zero (n = 2)", u.getVariance() != 0.0); } @Test public void testProductAndGeometricMean() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue( 1.0 ); u.addValue( 2.0 ); u.addValue( 3.0 ); u.addValue( 4.0 ); Assert.assertEquals( "Geometric mean not expected", 2.213364, u.getGeometricMean(), 0.00001 ); } @Test public void testNaNContracts() { SummaryStatistics u = createSummaryStatistics(); Assert.assertTrue("mean not NaN",Double.isNaN(u.getMean())); Assert.assertTrue("min not NaN",Double.isNaN(u.getMin())); Assert.assertTrue("std dev not NaN",Double.isNaN(u.getStandardDeviation())); Assert.assertTrue("var not NaN",Double.isNaN(u.getVariance())); Assert.assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); u.addValue(1.0); Assert.assertEquals( "mean not expected", 1.0, u.getMean(), Double.MIN_VALUE); Assert.assertEquals( "variance not expected", 0.0, u.getVariance(), Double.MIN_VALUE); Assert.assertEquals( "geometric mean not expected", 1.0, u.getGeometricMean(), Double.MIN_VALUE); u.addValue(-1.0); Assert.assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); u.addValue(0.0); Assert.assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); //FiXME: test all other NaN contract specs } @Test public void testGetSummary() { SummaryStatistics u = createSummaryStatistics(); StatisticalSummary summary = u.getSummary(); verifySummary(u, summary); u.addValue(1d); summary = u.getSummary(); verifySummary(u, summary); u.addValue(2d); summary = u.getSummary(); verifySummary(u, summary); u.addValue(2d); summary = u.getSummary(); verifySummary(u, summary); } @Test public void testSerialization() { SummaryStatistics u = createSummaryStatistics(); // Empty test TestUtils.checkSerializedEquality(u); SummaryStatistics s = (SummaryStatistics) TestUtils.serializeAndRecover(u); StatisticalSummary summary = s.getSummary(); verifySummary(u, summary); // Add some data u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); u.addValue(5d); // Test again TestUtils.checkSerializedEquality(u); s = (SummaryStatistics) TestUtils.serializeAndRecover(u); summary = s.getSummary(); verifySummary(u, summary); } @Test public void testEqualsAndHashCode() { SummaryStatistics u = createSummaryStatistics(); SummaryStatistics t = null; int emptyHash = u.hashCode(); Assert.assertTrue("reflexive", u.equals(u)); Assert.assertFalse("non-null compared to null", u.equals(t)); Assert.assertFalse("wrong type", u.equals(Double.valueOf(0))); t = createSummaryStatistics(); Assert.assertTrue("empty instances should be equal", t.equals(u)); Assert.assertTrue("empty instances should be equal", u.equals(t)); Assert.assertEquals("empty hash code", emptyHash, t.hashCode()); // Add some data to u u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); Assert.assertFalse("different n's should make instances not equal", t.equals(u)); Assert.assertFalse("different n's should make instances not equal", u.equals(t)); Assert.assertTrue("different n's should make hashcodes different", u.hashCode() != t.hashCode()); //Add data in same order to t t.addValue(2d); t.addValue(1d); t.addValue(3d); t.addValue(4d); Assert.assertTrue("summaries based on same data should be equal", t.equals(u)); Assert.assertTrue("summaries based on same data should be equal", u.equals(t)); Assert.assertEquals("summaries based on same data should have same hashcodes", u.hashCode(), t.hashCode()); // Clear and make sure summaries are indistinguishable from empty summary u.clear(); t.clear(); Assert.assertTrue("empty instances should be equal", t.equals(u)); Assert.assertTrue("empty instances should be equal", u.equals(t)); Assert.assertEquals("empty hash code", emptyHash, t.hashCode()); Assert.assertEquals("empty hash code", emptyHash, u.hashCode()); } @Test public void testCopy() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); SummaryStatistics v = new SummaryStatistics(u); Assert.assertEquals(u, v); Assert.assertEquals(v, u); Assert.assertTrue(v.geoMean == v.getGeoMeanImpl()); Assert.assertTrue(v.mean == v.getMeanImpl()); Assert.assertTrue(v.min == v.getMinImpl()); Assert.assertTrue(v.max == v.getMaxImpl()); Assert.assertTrue(v.sum == v.getSumImpl()); Assert.assertTrue(v.sumsq == v.getSumsqImpl()); Assert.assertTrue(v.sumLog == v.getSumLogImpl()); Assert.assertTrue(v.variance == v.getVarianceImpl()); // Make sure both behave the same with additional values added u.addValue(7d); u.addValue(9d); u.addValue(11d); u.addValue(23d); v.addValue(7d); v.addValue(9d); v.addValue(11d); v.addValue(23d); Assert.assertEquals(u, v); Assert.assertEquals(v, u); // Check implementation pointers are preserved u.clear(); u.setSumImpl(new Sum()); SummaryStatistics.copy(u,v); Assert.assertEquals(u.sum, v.sum); Assert.assertEquals(u.getSumImpl(), v.getSumImpl()); } private void verifySummary(SummaryStatistics u, StatisticalSummary s) { Assert.assertEquals("N",s.getN(),u.getN()); TestUtils.assertEquals("sum",s.getSum(),u.getSum(),tolerance); TestUtils.assertEquals("var",s.getVariance(),u.getVariance(),tolerance); TestUtils.assertEquals("std",s.getStandardDeviation(),u.getStandardDeviation(),tolerance); TestUtils.assertEquals("mean",s.getMean(),u.getMean(),tolerance); TestUtils.assertEquals("min",s.getMin(),u.getMin(),tolerance); TestUtils.assertEquals("max",s.getMax(),u.getMax(),tolerance); } @Test public void testSetterInjection() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.setMeanImpl(new Sum()); u.setSumLogImpl(new Sum()); u.addValue(1); u.addValue(3); Assert.assertEquals(4, u.getMean(), 1E-14); Assert.assertEquals(4, u.getSumOfLogs(), 1E-14); Assert.assertEquals(FastMath.exp(2), u.getGeometricMean(), 1E-14); u.clear(); u.addValue(1); u.addValue(2); Assert.assertEquals(3, u.getMean(), 1E-14); u.clear(); u.setMeanImpl(new Mean()); // OK after clear } @Test public void testSetterIllegalState() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue(1); u.addValue(3); try { u.setMeanImpl(new Sum()); Assert.fail("Expecting IllegalStateException"); } catch (IllegalStateException ex) { // expected } } /** * JIRA: MATH-691 */ @Test public void testOverrideVarianceWithMathClass() throws Exception { double[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setVarianceImpl(new Variance(false)); //use "population variance" for(double i : scores) { stats.addValue(i); } Assert.assertEquals((new Variance(false)).evaluate(scores),stats.getVariance(), 0); } @Test public void testOverrideMeanWithMathClass() throws Exception { double[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setMeanImpl(new Mean()); for(double i : scores) { stats.addValue(i); } Assert.assertEquals((new Mean()).evaluate(scores),stats.getMean(), 0); } @Test public void testOverrideGeoMeanWithMathClass() throws Exception { double[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setGeoMeanImpl(new GeometricMean()); for(double i : scores) { stats.addValue(i); } Assert.assertEquals((new GeometricMean()).evaluate(scores),stats.getGeometricMean(), 0); } }
// You are a professional Java test case writer, please create a test case named `testOverrideMeanWithMathClass` for the issue `Math-MATH-691`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-691 // // ## Issue-Title: // Statistics.setVarianceImpl makes getStandardDeviation produce NaN // // ## Issue-Description: // // Invoking SummaryStatistics.setVarianceImpl(new Variance(true/false) makes getStandardDeviation produce NaN. The code to reproduce it: // // // // // ``` // int[] scores = {1, 2, 3, 4}; // SummaryStatistics stats = new SummaryStatistics(); // stats.setVarianceImpl(new Variance(false)); //use "population variance" // for(int i : scores) { // stats.addValue(i); // } // double sd = stats.getStandardDeviation(); // System.out.println(sd); // // ``` // // // A workaround suggested by Mikkel is: // // // // // ``` // double sd = FastMath.sqrt(stats.getSecondMoment() / stats.getN()); // // ``` // // // // // @Test public void testOverrideMeanWithMathClass() throws Exception {
335
43
326
src/test/java/org/apache/commons/math/stat/descriptive/SummaryStatisticsTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-691 ## Issue-Title: Statistics.setVarianceImpl makes getStandardDeviation produce NaN ## Issue-Description: Invoking SummaryStatistics.setVarianceImpl(new Variance(true/false) makes getStandardDeviation produce NaN. The code to reproduce it: ``` int[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setVarianceImpl(new Variance(false)); //use "population variance" for(int i : scores) { stats.addValue(i); } double sd = stats.getStandardDeviation(); System.out.println(sd); ``` A workaround suggested by Mikkel is: ``` double sd = FastMath.sqrt(stats.getSecondMoment() / stats.getN()); ``` ``` You are a professional Java test case writer, please create a test case named `testOverrideMeanWithMathClass` for the issue `Math-MATH-691`, utilizing the provided issue report information and the following function signature. ```java @Test public void testOverrideMeanWithMathClass() throws Exception { ```
326
[ "org.apache.commons.math.stat.descriptive.SummaryStatistics" ]
b015ba5d6b3f88dfb4048b064a55a604492de7472d47bebe43ca7153142ccb7a
@Test public void testOverrideMeanWithMathClass() throws Exception
// You are a professional Java test case writer, please create a test case named `testOverrideMeanWithMathClass` for the issue `Math-MATH-691`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-691 // // ## Issue-Title: // Statistics.setVarianceImpl makes getStandardDeviation produce NaN // // ## Issue-Description: // // Invoking SummaryStatistics.setVarianceImpl(new Variance(true/false) makes getStandardDeviation produce NaN. The code to reproduce it: // // // // // ``` // int[] scores = {1, 2, 3, 4}; // SummaryStatistics stats = new SummaryStatistics(); // stats.setVarianceImpl(new Variance(false)); //use "population variance" // for(int i : scores) { // stats.addValue(i); // } // double sd = stats.getStandardDeviation(); // System.out.println(sd); // // ``` // // // A workaround suggested by Mikkel is: // // // // // ``` // double sd = FastMath.sqrt(stats.getSecondMoment() / stats.getN()); // // ``` // // // // //
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.descriptive; import org.apache.commons.math.TestUtils; import org.apache.commons.math.stat.descriptive.moment.GeometricMean; import org.apache.commons.math.stat.descriptive.moment.Mean; import org.apache.commons.math.stat.descriptive.moment.Variance; import org.apache.commons.math.stat.descriptive.summary.Sum; import org.apache.commons.math.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Test cases for the {@link SummaryStatistics} class. * * @version $Id$ */ public class SummaryStatisticsTest { private double one = 1; private float twoF = 2; private long twoL = 2; private int three = 3; private double mean = 2; private double sumSq = 18; private double sum = 8; private double var = 0.666666666666666666667; private double popVar = 0.5; private double std = FastMath.sqrt(var); private double n = 4; private double min = 1; private double max = 3; private double tolerance = 10E-15; protected SummaryStatistics createSummaryStatistics() { return new SummaryStatistics(); } /** test stats */ @Test public void testStats() { SummaryStatistics u = createSummaryStatistics(); Assert.assertEquals("total count",0,u.getN(),tolerance); u.addValue(one); u.addValue(twoF); u.addValue(twoL); u.addValue(three); Assert.assertEquals("N",n,u.getN(),tolerance); Assert.assertEquals("sum",sum,u.getSum(),tolerance); Assert.assertEquals("sumsq",sumSq,u.getSumsq(),tolerance); Assert.assertEquals("var",var,u.getVariance(),tolerance); Assert.assertEquals("population var",popVar,u.getPopulationVariance(),tolerance); Assert.assertEquals("std",std,u.getStandardDeviation(),tolerance); Assert.assertEquals("mean",mean,u.getMean(),tolerance); Assert.assertEquals("min",min,u.getMin(),tolerance); Assert.assertEquals("max",max,u.getMax(),tolerance); u.clear(); Assert.assertEquals("total count",0,u.getN(),tolerance); } @Test public void testN0andN1Conditions() throws Exception { SummaryStatistics u = createSummaryStatistics(); Assert.assertTrue("Mean of n = 0 set should be NaN", Double.isNaN( u.getMean() ) ); Assert.assertTrue("Standard Deviation of n = 0 set should be NaN", Double.isNaN( u.getStandardDeviation() ) ); Assert.assertTrue("Variance of n = 0 set should be NaN", Double.isNaN(u.getVariance() ) ); /* n=1 */ u.addValue(one); Assert.assertTrue("mean should be one (n = 1)", u.getMean() == one); Assert.assertTrue("geometric should be one (n = 1) instead it is " + u.getGeometricMean(), u.getGeometricMean() == one); Assert.assertTrue("Std should be zero (n = 1)", u.getStandardDeviation() == 0.0); Assert.assertTrue("variance should be zero (n = 1)", u.getVariance() == 0.0); /* n=2 */ u.addValue(twoF); Assert.assertTrue("Std should not be zero (n = 2)", u.getStandardDeviation() != 0.0); Assert.assertTrue("variance should not be zero (n = 2)", u.getVariance() != 0.0); } @Test public void testProductAndGeometricMean() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue( 1.0 ); u.addValue( 2.0 ); u.addValue( 3.0 ); u.addValue( 4.0 ); Assert.assertEquals( "Geometric mean not expected", 2.213364, u.getGeometricMean(), 0.00001 ); } @Test public void testNaNContracts() { SummaryStatistics u = createSummaryStatistics(); Assert.assertTrue("mean not NaN",Double.isNaN(u.getMean())); Assert.assertTrue("min not NaN",Double.isNaN(u.getMin())); Assert.assertTrue("std dev not NaN",Double.isNaN(u.getStandardDeviation())); Assert.assertTrue("var not NaN",Double.isNaN(u.getVariance())); Assert.assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); u.addValue(1.0); Assert.assertEquals( "mean not expected", 1.0, u.getMean(), Double.MIN_VALUE); Assert.assertEquals( "variance not expected", 0.0, u.getVariance(), Double.MIN_VALUE); Assert.assertEquals( "geometric mean not expected", 1.0, u.getGeometricMean(), Double.MIN_VALUE); u.addValue(-1.0); Assert.assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); u.addValue(0.0); Assert.assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); //FiXME: test all other NaN contract specs } @Test public void testGetSummary() { SummaryStatistics u = createSummaryStatistics(); StatisticalSummary summary = u.getSummary(); verifySummary(u, summary); u.addValue(1d); summary = u.getSummary(); verifySummary(u, summary); u.addValue(2d); summary = u.getSummary(); verifySummary(u, summary); u.addValue(2d); summary = u.getSummary(); verifySummary(u, summary); } @Test public void testSerialization() { SummaryStatistics u = createSummaryStatistics(); // Empty test TestUtils.checkSerializedEquality(u); SummaryStatistics s = (SummaryStatistics) TestUtils.serializeAndRecover(u); StatisticalSummary summary = s.getSummary(); verifySummary(u, summary); // Add some data u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); u.addValue(5d); // Test again TestUtils.checkSerializedEquality(u); s = (SummaryStatistics) TestUtils.serializeAndRecover(u); summary = s.getSummary(); verifySummary(u, summary); } @Test public void testEqualsAndHashCode() { SummaryStatistics u = createSummaryStatistics(); SummaryStatistics t = null; int emptyHash = u.hashCode(); Assert.assertTrue("reflexive", u.equals(u)); Assert.assertFalse("non-null compared to null", u.equals(t)); Assert.assertFalse("wrong type", u.equals(Double.valueOf(0))); t = createSummaryStatistics(); Assert.assertTrue("empty instances should be equal", t.equals(u)); Assert.assertTrue("empty instances should be equal", u.equals(t)); Assert.assertEquals("empty hash code", emptyHash, t.hashCode()); // Add some data to u u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); Assert.assertFalse("different n's should make instances not equal", t.equals(u)); Assert.assertFalse("different n's should make instances not equal", u.equals(t)); Assert.assertTrue("different n's should make hashcodes different", u.hashCode() != t.hashCode()); //Add data in same order to t t.addValue(2d); t.addValue(1d); t.addValue(3d); t.addValue(4d); Assert.assertTrue("summaries based on same data should be equal", t.equals(u)); Assert.assertTrue("summaries based on same data should be equal", u.equals(t)); Assert.assertEquals("summaries based on same data should have same hashcodes", u.hashCode(), t.hashCode()); // Clear and make sure summaries are indistinguishable from empty summary u.clear(); t.clear(); Assert.assertTrue("empty instances should be equal", t.equals(u)); Assert.assertTrue("empty instances should be equal", u.equals(t)); Assert.assertEquals("empty hash code", emptyHash, t.hashCode()); Assert.assertEquals("empty hash code", emptyHash, u.hashCode()); } @Test public void testCopy() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); SummaryStatistics v = new SummaryStatistics(u); Assert.assertEquals(u, v); Assert.assertEquals(v, u); Assert.assertTrue(v.geoMean == v.getGeoMeanImpl()); Assert.assertTrue(v.mean == v.getMeanImpl()); Assert.assertTrue(v.min == v.getMinImpl()); Assert.assertTrue(v.max == v.getMaxImpl()); Assert.assertTrue(v.sum == v.getSumImpl()); Assert.assertTrue(v.sumsq == v.getSumsqImpl()); Assert.assertTrue(v.sumLog == v.getSumLogImpl()); Assert.assertTrue(v.variance == v.getVarianceImpl()); // Make sure both behave the same with additional values added u.addValue(7d); u.addValue(9d); u.addValue(11d); u.addValue(23d); v.addValue(7d); v.addValue(9d); v.addValue(11d); v.addValue(23d); Assert.assertEquals(u, v); Assert.assertEquals(v, u); // Check implementation pointers are preserved u.clear(); u.setSumImpl(new Sum()); SummaryStatistics.copy(u,v); Assert.assertEquals(u.sum, v.sum); Assert.assertEquals(u.getSumImpl(), v.getSumImpl()); } private void verifySummary(SummaryStatistics u, StatisticalSummary s) { Assert.assertEquals("N",s.getN(),u.getN()); TestUtils.assertEquals("sum",s.getSum(),u.getSum(),tolerance); TestUtils.assertEquals("var",s.getVariance(),u.getVariance(),tolerance); TestUtils.assertEquals("std",s.getStandardDeviation(),u.getStandardDeviation(),tolerance); TestUtils.assertEquals("mean",s.getMean(),u.getMean(),tolerance); TestUtils.assertEquals("min",s.getMin(),u.getMin(),tolerance); TestUtils.assertEquals("max",s.getMax(),u.getMax(),tolerance); } @Test public void testSetterInjection() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.setMeanImpl(new Sum()); u.setSumLogImpl(new Sum()); u.addValue(1); u.addValue(3); Assert.assertEquals(4, u.getMean(), 1E-14); Assert.assertEquals(4, u.getSumOfLogs(), 1E-14); Assert.assertEquals(FastMath.exp(2), u.getGeometricMean(), 1E-14); u.clear(); u.addValue(1); u.addValue(2); Assert.assertEquals(3, u.getMean(), 1E-14); u.clear(); u.setMeanImpl(new Mean()); // OK after clear } @Test public void testSetterIllegalState() throws Exception { SummaryStatistics u = createSummaryStatistics(); u.addValue(1); u.addValue(3); try { u.setMeanImpl(new Sum()); Assert.fail("Expecting IllegalStateException"); } catch (IllegalStateException ex) { // expected } } /** * JIRA: MATH-691 */ @Test public void testOverrideVarianceWithMathClass() throws Exception { double[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setVarianceImpl(new Variance(false)); //use "population variance" for(double i : scores) { stats.addValue(i); } Assert.assertEquals((new Variance(false)).evaluate(scores),stats.getVariance(), 0); } @Test public void testOverrideMeanWithMathClass() throws Exception { double[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setMeanImpl(new Mean()); for(double i : scores) { stats.addValue(i); } Assert.assertEquals((new Mean()).evaluate(scores),stats.getMean(), 0); } @Test public void testOverrideGeoMeanWithMathClass() throws Exception { double[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setGeoMeanImpl(new GeometricMean()); for(double i : scores) { stats.addValue(i); } Assert.assertEquals((new GeometricMean()).evaluate(scores),stats.getGeometricMean(), 0); } }
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"); }
com.google.javascript.jscomp.LooseTypeCheckTest::testMethodInference7
test/com/google/javascript/jscomp/LooseTypeCheckTest.java
1,791
test/com/google/javascript/jscomp/LooseTypeCheckTest.java
testMethodInference7
/* * 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.CheckLevel; import com.google.javascript.jscomp.Scope.Var; 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 java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * * This is a temporary fork of the TypeCheckTest for the experimental * "looseTypes" option. These tests should be be folded into TypeCheckTest * or removed along with the looseTypes option. * */ public class LooseTypeCheckTest extends CompilerTypeTestCase { @Override public CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.looseTypes = true; return options; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).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 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} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16a() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16b() 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.<number>\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|undefined}\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|undefined)\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 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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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=): 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-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 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);"); } 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 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", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createOptionalType(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"); } // 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}", "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|undefined)"); } 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|undefined)>\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 (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 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 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 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("/** @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;"); } 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|undefined)\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 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;", "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"); 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|undefined) */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type (null|undefined) */" + "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|null} */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|null} */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 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 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|undefined)\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|undefined)\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)"); } 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 testControlFlowRestrictsType1a() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }\n" + "/** @type {String?} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null|undefined) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1b() throws Exception { testTypes("/** @return {!String|null} */ function f() { return null; }\n" + "/** @type {!String|null} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1c() throws Exception { testTypes("/** @return {!String|undefined} */\n" + "function f() { return undefined; }\n" + "/** @type {!String|undefined} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type undefined */ var c = undefined;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } 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 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|undefined)"); } 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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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); 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 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 {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() 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 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|undefined)\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(createUnionType(OBJECT_TYPE, NULL_TYPE), VOID_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 4; };" + "/** @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 { 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() {};", "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 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 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() { };", // "cannot reference an interface ouside 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 testWarnDataPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @type {number} */T.prototype.x;", // "interface members can only be plain functions"); //} 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|undefined)"); } // 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|undefined)\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|undefined)"); } 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|undefined)"); } 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 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 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.createOptionalType( 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() { this });", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format()); } 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("number")); } 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()); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } 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 { 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, 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(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(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); } 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 `testMethodInference7` for the issue `Closure-634`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-634 // // ## Issue-Title: // {function(number, string)} should not be assignable to {function(number)} // // ## Issue-Description: // Consider the following snippet. I don't think the "second call" should compile. As a side note: it would be great if none of the compiled in some pseudo-strict compile mode. // // /\*\* @param {function(string,number):boolean} param \*/ // function func(param) {} // // /\*\* @type {function(string,number,boolean):boolean} \*/ // function paramFunc1() {} // // /\*\* @type {function(string):boolean} \*/ // function paramFunc2() {} // // // first call // func(paramFunc1); // // // second call // func(paramFunc2); // // public void testMethodInference7() throws Exception {
1,791
164
1,780
test/com/google/javascript/jscomp/LooseTypeCheckTest.java
test
```markdown ## Issue-ID: Closure-634 ## Issue-Title: {function(number, string)} should not be assignable to {function(number)} ## Issue-Description: Consider the following snippet. I don't think the "second call" should compile. As a side note: it would be great if none of the compiled in some pseudo-strict compile mode. /\*\* @param {function(string,number):boolean} param \*/ function func(param) {} /\*\* @type {function(string,number,boolean):boolean} \*/ function paramFunc1() {} /\*\* @type {function(string):boolean} \*/ function paramFunc2() {} // first call func(paramFunc1); // second call func(paramFunc2); ``` You are a professional Java test case writer, please create a test case named `testMethodInference7` for the issue `Closure-634`, utilizing the provided issue report information and the following function signature. ```java public void testMethodInference7() throws Exception { ```
1,780
[ "com.google.javascript.rhino.jstype.ArrowType" ]
b0f43f4a7c5dac5df6e31c4a1c3382c1ded360b75e72ceccc2376ef14b94c371
public void testMethodInference7() throws Exception
// You are a professional Java test case writer, please create a test case named `testMethodInference7` for the issue `Closure-634`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-634 // // ## Issue-Title: // {function(number, string)} should not be assignable to {function(number)} // // ## Issue-Description: // Consider the following snippet. I don't think the "second call" should compile. As a side note: it would be great if none of the compiled in some pseudo-strict compile mode. // // /\*\* @param {function(string,number):boolean} param \*/ // function func(param) {} // // /\*\* @type {function(string,number,boolean):boolean} \*/ // function paramFunc1() {} // // /\*\* @type {function(string):boolean} \*/ // function paramFunc2() {} // // // first call // func(paramFunc1); // // // second call // func(paramFunc2); // //
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.CheckLevel; import com.google.javascript.jscomp.Scope.Var; 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 java.util.Arrays; import java.util.List; /** * Tests {@link TypeCheck}. * * This is a temporary fork of the TypeCheckTest for the experimental * "looseTypes" option. These tests should be be folded into TypeCheckTest * or removed along with the looseTypes option. * */ public class LooseTypeCheckTest extends CompilerTypeTestCase { @Override public CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.looseTypes = true; return options; } public void testInitialTypingScope() { Scope s = new TypedScopeCreator(compiler, CodingConventions.getDefault()).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 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} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16a() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16b() 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.<number>\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|undefined}\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|undefined)\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 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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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=): 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-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 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);"); } 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 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", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createOptionalType(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"); } // 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}", "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|undefined)"); } 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|undefined)>\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 (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 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 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 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("/** @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;"); } 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|undefined)\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 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;", "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"); 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|undefined) */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type (null|undefined) */" + "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|null} */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|null} */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 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 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|undefined)\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|undefined)\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)"); } 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 testControlFlowRestrictsType1a() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }\n" + "/** @type {String?} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null|undefined) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1b() throws Exception { testTypes("/** @return {!String|null} */ function f() { return null; }\n" + "/** @type {!String|null} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1c() throws Exception { testTypes("/** @return {!String|undefined} */\n" + "function f() { return undefined; }\n" + "/** @type {!String|undefined} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type undefined */ var c = undefined;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } 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 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|undefined)"); } 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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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); 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 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 {number} x */ function f(x) {}" + "f(x.foo);" + "f([].foo);" + "}", "Property foo never defined on Array"); } public void testCast16() 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 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|undefined)\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(createUnionType(OBJECT_TYPE, NULL_TYPE), VOID_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 4; };" + "/** @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 { 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() {};", "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 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 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() { };", // "cannot reference an interface ouside 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 testWarnDataPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @type {number} */T.prototype.x;", // "interface members can only be plain functions"); //} 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|undefined)"); } // 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|undefined)\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|undefined)"); } 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|undefined)"); } 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 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 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.createOptionalType( 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() { this });", FunctionTypeBuilder.TEMPLATE_TYPE_DUPLICATED.format()); } 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("number")); } 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()); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } 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 { 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, 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(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(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); } 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 testIntegerOverflow() { checkIntegerOverflow(0.75000000001455192); checkIntegerOverflow(1.0e10); checkIntegerOverflow(-1.0e10); checkIntegerOverflow(-43979.60679604749); }
org.apache.commons.math3.fraction.FractionTest::testIntegerOverflow
src/test/java/org/apache/commons/math3/fraction/FractionTest.java
139
src/test/java/org/apache/commons/math3/fraction/FractionTest.java
testIntegerOverflow
/* * 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.fraction; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathArithmeticException; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * @version $Id$ */ public class FractionTest { private void assertFraction(int expectedNumerator, int expectedDenominator, Fraction actual) { Assert.assertEquals(expectedNumerator, actual.getNumerator()); Assert.assertEquals(expectedDenominator, actual.getDenominator()); } @Test public void testConstructor() { assertFraction(0, 1, new Fraction(0, 1)); assertFraction(0, 1, new Fraction(0, 2)); assertFraction(0, 1, new Fraction(0, -1)); assertFraction(1, 2, new Fraction(1, 2)); assertFraction(1, 2, new Fraction(2, 4)); assertFraction(-1, 2, new Fraction(-1, 2)); assertFraction(-1, 2, new Fraction(1, -2)); assertFraction(-1, 2, new Fraction(-2, 4)); assertFraction(-1, 2, new Fraction(2, -4)); // overflow try { new Fraction(Integer.MIN_VALUE, -1); Assert.fail(); } catch (MathArithmeticException ex) { // success } try { new Fraction(1, Integer.MIN_VALUE); Assert.fail(); } catch (MathArithmeticException ex) { // success } assertFraction(0, 1, new Fraction(0.00000000000001)); assertFraction(2, 5, new Fraction(0.40000000000001)); assertFraction(15, 1, new Fraction(15.0000000000001)); } @Test(expected=ConvergenceException.class) public void testGoldenRatio() { // the golden ratio is notoriously a difficult number for continuous fraction new Fraction((1 + FastMath.sqrt(5)) / 2, 1.0e-12, 25); } // MATH-179 @Test public void testDoubleConstructor() throws ConvergenceException { assertFraction(1, 2, new Fraction((double)1 / (double)2)); assertFraction(1, 3, new Fraction((double)1 / (double)3)); assertFraction(2, 3, new Fraction((double)2 / (double)3)); assertFraction(1, 4, new Fraction((double)1 / (double)4)); assertFraction(3, 4, new Fraction((double)3 / (double)4)); assertFraction(1, 5, new Fraction((double)1 / (double)5)); assertFraction(2, 5, new Fraction((double)2 / (double)5)); assertFraction(3, 5, new Fraction((double)3 / (double)5)); assertFraction(4, 5, new Fraction((double)4 / (double)5)); assertFraction(1, 6, new Fraction((double)1 / (double)6)); assertFraction(5, 6, new Fraction((double)5 / (double)6)); assertFraction(1, 7, new Fraction((double)1 / (double)7)); assertFraction(2, 7, new Fraction((double)2 / (double)7)); assertFraction(3, 7, new Fraction((double)3 / (double)7)); assertFraction(4, 7, new Fraction((double)4 / (double)7)); assertFraction(5, 7, new Fraction((double)5 / (double)7)); assertFraction(6, 7, new Fraction((double)6 / (double)7)); assertFraction(1, 8, new Fraction((double)1 / (double)8)); assertFraction(3, 8, new Fraction((double)3 / (double)8)); assertFraction(5, 8, new Fraction((double)5 / (double)8)); assertFraction(7, 8, new Fraction((double)7 / (double)8)); assertFraction(1, 9, new Fraction((double)1 / (double)9)); assertFraction(2, 9, new Fraction((double)2 / (double)9)); assertFraction(4, 9, new Fraction((double)4 / (double)9)); assertFraction(5, 9, new Fraction((double)5 / (double)9)); assertFraction(7, 9, new Fraction((double)7 / (double)9)); assertFraction(8, 9, new Fraction((double)8 / (double)9)); assertFraction(1, 10, new Fraction((double)1 / (double)10)); assertFraction(3, 10, new Fraction((double)3 / (double)10)); assertFraction(7, 10, new Fraction((double)7 / (double)10)); assertFraction(9, 10, new Fraction((double)9 / (double)10)); assertFraction(1, 11, new Fraction((double)1 / (double)11)); assertFraction(2, 11, new Fraction((double)2 / (double)11)); assertFraction(3, 11, new Fraction((double)3 / (double)11)); assertFraction(4, 11, new Fraction((double)4 / (double)11)); assertFraction(5, 11, new Fraction((double)5 / (double)11)); assertFraction(6, 11, new Fraction((double)6 / (double)11)); assertFraction(7, 11, new Fraction((double)7 / (double)11)); assertFraction(8, 11, new Fraction((double)8 / (double)11)); assertFraction(9, 11, new Fraction((double)9 / (double)11)); assertFraction(10, 11, new Fraction((double)10 / (double)11)); } // MATH-181 @Test public void testDigitLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 9)); assertFraction(2, 5, new Fraction(0.4, 99)); assertFraction(2, 5, new Fraction(0.4, 999)); assertFraction(3, 5, new Fraction(0.6152, 9)); assertFraction(8, 13, new Fraction(0.6152, 99)); assertFraction(510, 829, new Fraction(0.6152, 999)); assertFraction(769, 1250, new Fraction(0.6152, 9999)); } @Test public void testIntegerOverflow() { checkIntegerOverflow(0.75000000001455192); checkIntegerOverflow(1.0e10); checkIntegerOverflow(-1.0e10); checkIntegerOverflow(-43979.60679604749); } private void checkIntegerOverflow(double a) { try { new Fraction(a, 1.0e-12, 1000); Assert.fail("an exception should have been thrown"); } catch (ConvergenceException ce) { // expected behavior } } @Test public void testEpsilonLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 1.0e-5, 100)); assertFraction(3, 5, new Fraction(0.6152, 0.02, 100)); assertFraction(8, 13, new Fraction(0.6152, 1.0e-3, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-4, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-5, 100)); assertFraction(510, 829, new Fraction(0.6152, 1.0e-6, 100)); assertFraction(769, 1250, new Fraction(0.6152, 1.0e-7, 100)); } @Test public void testCompareTo() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Fraction third = new Fraction(1, 2); Assert.assertEquals(0, first.compareTo(first)); Assert.assertEquals(0, first.compareTo(third)); Assert.assertEquals(1, first.compareTo(second)); Assert.assertEquals(-1, second.compareTo(first)); // these two values are different approximations of PI // the first one is approximately PI - 3.07e-18 // the second one is approximately PI + 1.936e-17 Fraction pi1 = new Fraction(1068966896, 340262731); Fraction pi2 = new Fraction( 411557987, 131002976); Assert.assertEquals(-1, pi1.compareTo(pi2)); Assert.assertEquals( 1, pi2.compareTo(pi1)); Assert.assertEquals(0.0, pi1.doubleValue() - pi2.doubleValue(), 1.0e-20); } @Test public void testDoubleValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Assert.assertEquals(0.5, first.doubleValue(), 0.0); Assert.assertEquals(1.0 / 3.0, second.doubleValue(), 0.0); } @Test public void testFloatValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Assert.assertEquals(0.5f, first.floatValue(), 0.0f); Assert.assertEquals((float)(1.0 / 3.0), second.floatValue(), 0.0f); } @Test public void testIntValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); Assert.assertEquals(0, first.intValue()); Assert.assertEquals(1, second.intValue()); } @Test public void testLongValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); Assert.assertEquals(0L, first.longValue()); Assert.assertEquals(1L, second.longValue()); } @Test public void testConstructorDouble() { assertFraction(1, 2, new Fraction(0.5)); assertFraction(1, 3, new Fraction(1.0 / 3.0)); assertFraction(17, 100, new Fraction(17.0 / 100.0)); assertFraction(317, 100, new Fraction(317.0 / 100.0)); assertFraction(-1, 2, new Fraction(-0.5)); assertFraction(-1, 3, new Fraction(-1.0 / 3.0)); assertFraction(-17, 100, new Fraction(17.0 / -100.0)); assertFraction(-317, 100, new Fraction(-317.0 / 100.0)); } @Test public void testAbs() { Fraction a = new Fraction(10, 21); Fraction b = new Fraction(-10, 21); Fraction c = new Fraction(10, -21); assertFraction(10, 21, a.abs()); assertFraction(10, 21, b.abs()); assertFraction(10, 21, c.abs()); } @Test public void testPercentage() { Assert.assertEquals(50.0, new Fraction(1, 2).percentageValue(), 1.0e-15); } @Test public void testMath835() { final int numer = Integer.MAX_VALUE / 99; final int denom = 1; final double percentage = 100 * ((double) numer) / denom; final Fraction frac = new Fraction(numer, denom); // With the implementation that preceded the fix suggested in MATH-835, // this test was failing, due to overflow. Assert.assertEquals(percentage, frac.percentageValue(), Math.ulp(percentage)); } @Test public void testReciprocal() { Fraction f = null; f = new Fraction(50, 75); f = f.reciprocal(); Assert.assertEquals(3, f.getNumerator()); Assert.assertEquals(2, f.getDenominator()); f = new Fraction(4, 3); f = f.reciprocal(); Assert.assertEquals(3, f.getNumerator()); Assert.assertEquals(4, f.getDenominator()); f = new Fraction(-15, 47); f = f.reciprocal(); Assert.assertEquals(-47, f.getNumerator()); Assert.assertEquals(15, f.getDenominator()); f = new Fraction(0, 3); try { f = f.reciprocal(); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} // large values f = new Fraction(Integer.MAX_VALUE, 1); f = f.reciprocal(); Assert.assertEquals(1, f.getNumerator()); Assert.assertEquals(Integer.MAX_VALUE, f.getDenominator()); } @Test public void testNegate() { Fraction f = null; f = new Fraction(50, 75); f = f.negate(); Assert.assertEquals(-2, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); f = new Fraction(-50, 75); f = f.negate(); Assert.assertEquals(2, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); // large values f = new Fraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = f.negate(); Assert.assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); Assert.assertEquals(Integer.MAX_VALUE, f.getDenominator()); f = new Fraction(Integer.MIN_VALUE, 1); try { f = f.negate(); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} } @Test public void testAdd() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.add(a)); assertFraction(7, 6, a.add(b)); assertFraction(7, 6, b.add(a)); assertFraction(4, 3, b.add(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE - 1, 1); Fraction f2 = Fraction.ONE; Fraction f = f1.add(f2); Assert.assertEquals(Integer.MAX_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f = f1.add(1); Assert.assertEquals(Integer.MAX_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f1 = new Fraction(-1, 13*13*2*2); f2 = new Fraction(-2, 13*17*2); f = f1.add(f2); Assert.assertEquals(13*13*17*2*2, f.getDenominator()); Assert.assertEquals(-17 - 2*13*2, f.getNumerator()); try { f.add(null); Assert.fail("expecting MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = new Fraction(1,32768*3); f2 = new Fraction(1,59049); f = f1.add(f2); Assert.assertEquals(52451, f.getNumerator()); Assert.assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3); f = f1.add(f2); Assert.assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); Assert.assertEquals(Integer.MAX_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f = f.add(Fraction.ONE); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(-1,5); try { f = f1.add(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.add(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} } @Test public void testDivide() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.divide(a)); assertFraction(3, 4, a.divide(b)); assertFraction(4, 3, b.divide(a)); assertFraction(1, 1, b.divide(b)); Fraction f1 = new Fraction(3, 5); Fraction f2 = Fraction.ZERO; try { f1.divide(f2); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(0, 5); f2 = new Fraction(2, 7); Fraction f = f1.divide(f2); Assert.assertSame(Fraction.ZERO, f); f1 = new Fraction(2, 7); f2 = Fraction.ONE; f = f1.divide(f2); Assert.assertEquals(2, f.getNumerator()); Assert.assertEquals(7, f.getDenominator()); f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1); Assert.assertEquals(1, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f2); Assert.assertEquals(Integer.MIN_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f.divide(null); Assert.fail("MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} try { f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} try { f1 = new Fraction(1, -Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(6, 35); f = f1.divide(15); Assert.assertEquals(2, f.getNumerator()); Assert.assertEquals(175, f.getDenominator()); } @Test public void testMultiply() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 4, a.multiply(a)); assertFraction(1, 3, a.multiply(b)); assertFraction(1, 3, b.multiply(a)); assertFraction(4, 9, b.multiply(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE, 1); Fraction f2 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); Fraction f = f1.multiply(f2); Assert.assertEquals(Integer.MIN_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f.multiply(null); Assert.fail("expecting MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} f1 = new Fraction(6, 35); f = f1.multiply(15); Assert.assertEquals(18, f.getNumerator()); Assert.assertEquals(7, f.getDenominator()); } @Test public void testSubtract() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(0, 1, a.subtract(a)); assertFraction(-1, 6, a.subtract(b)); assertFraction(1, 6, b.subtract(a)); assertFraction(0, 1, b.subtract(b)); Fraction f = new Fraction(1,1); try { f.subtract(null); Assert.fail("expecting MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} // if this fraction is subtracted naively, it will overflow. // check that it doesn't. Fraction f1 = new Fraction(1,32768*3); Fraction f2 = new Fraction(1,59049); f = f1.subtract(f2); Assert.assertEquals(-13085, f.getNumerator()); Assert.assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3).negate(); f = f1.subtract(f2); Assert.assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); Assert.assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f = f1.subtract(1); Assert.assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f1 = new Fraction(1, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE - 1); f = f1.subtract(f2); Assert.fail("expecting MathArithmeticException"); //should overflow } catch (MathArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(1,5); try { f = f1.subtract(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} try { f= new Fraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} try { f= new Fraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.subtract(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} } @Test public void testEqualsAndHashCode() { Fraction zero = new Fraction(0,1); Fraction nullFraction = null; Assert.assertTrue( zero.equals(zero)); Assert.assertFalse(zero.equals(nullFraction)); Assert.assertFalse(zero.equals(Double.valueOf(0))); Fraction zero2 = new Fraction(0,2); Assert.assertTrue(zero.equals(zero2)); Assert.assertEquals(zero.hashCode(), zero2.hashCode()); Fraction one = new Fraction(1,1); Assert.assertFalse((one.equals(zero) ||zero.equals(one))); } @Test public void testGetReducedFraction() { Fraction threeFourths = new Fraction(3, 4); Assert.assertTrue(threeFourths.equals(Fraction.getReducedFraction(6, 8))); Assert.assertTrue(Fraction.ZERO.equals(Fraction.getReducedFraction(0, -1))); try { Fraction.getReducedFraction(1, 0); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) { // expected } Assert.assertEquals(Fraction.getReducedFraction (2, Integer.MIN_VALUE).getNumerator(),-1); Assert.assertEquals(Fraction.getReducedFraction (1, -1).getNumerator(), -1); } @Test public void testToString() { Assert.assertEquals("0", new Fraction(0, 3).toString()); Assert.assertEquals("3", new Fraction(6, 2).toString()); Assert.assertEquals("2 / 3", new Fraction(18, 27).toString()); } @Test public void testSerial() throws FractionConversionException { Fraction[] fractions = { new Fraction(3, 4), Fraction.ONE, Fraction.ZERO, new Fraction(17), new Fraction(FastMath.PI, 1000), new Fraction(-5, 2) }; for (Fraction fraction : fractions) { Assert.assertEquals(fraction, TestUtils.serializeAndRecover(fraction)); } } }
// You are a professional Java test case writer, please create a test case named `testIntegerOverflow` for the issue `Math-MATH-836`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-836 // // ## Issue-Title: // Fraction(double, int) constructor strange behaviour // // ## Issue-Description: // // The Fraction constructor Fraction(double, int) takes a double value and a int maximal denominator, and approximates a fraction. When the double value is a large, negative number with many digits in the fractional part, and the maximal denominator is a big, positive integer (in the 100'000s), two distinct bugs can manifest: // // // 1: the constructor returns a positive Fraction. Calling Fraction(-33655.1677817278, 371880) returns the fraction 410517235/243036, which both has the wrong sign, and is far away from the absolute value of the given value // // // 2: the constructor does not manage to reduce the Fraction properly. Calling Fraction(-43979.60679604749, 366081) returns the fraction -1651878166/256677, which should have\* been reduced to -24654898/3831. // // // I have, as of yet, not found a solution. The constructor looks like this: // // // public Fraction(double value, int maxDenominator) // // throws FractionConversionException // // // { // this(value, 0, maxDenominator, 100); // } // // Increasing the 100 value (max iterations) does not fix the problem for all cases. Changing the 0-value (the epsilon, maximum allowed error) to something small does not work either, as this breaks the tests in FractionTest. // // // The problem is not neccissarily that the algorithm is unable to approximate a fraction correctly. A solution where a FractionConversionException had been thrown in each of these examples would probably be the best solution if an improvement on the approximation algorithm turns out to be hard to find. // // // This bug has been found when trying to explore the idea of axiom-based testing (<http://bldl.ii.uib.no/testing.html>). Attached is a java test class FractionTestByAxiom (junit, goes into org.apache.commons.math3.fraction) which shows these bugs through a simplified approach to this kind of testing, and a text file describing some of the value/maxDenominator combinations which causes one of these failures. // // // * It is never specified in the documentation that the Fraction class guarantees that completely reduced rational numbers are constructed, but a comment inside the equals method claims that "since fractions are always in lowest terms, numerators and can be compared directly for equality", so it seems like this is the intention. // // // // // @Test public void testIntegerOverflow() {
139
26
133
src/test/java/org/apache/commons/math3/fraction/FractionTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-836 ## Issue-Title: Fraction(double, int) constructor strange behaviour ## Issue-Description: The Fraction constructor Fraction(double, int) takes a double value and a int maximal denominator, and approximates a fraction. When the double value is a large, negative number with many digits in the fractional part, and the maximal denominator is a big, positive integer (in the 100'000s), two distinct bugs can manifest: 1: the constructor returns a positive Fraction. Calling Fraction(-33655.1677817278, 371880) returns the fraction 410517235/243036, which both has the wrong sign, and is far away from the absolute value of the given value 2: the constructor does not manage to reduce the Fraction properly. Calling Fraction(-43979.60679604749, 366081) returns the fraction -1651878166/256677, which should have\* been reduced to -24654898/3831. I have, as of yet, not found a solution. The constructor looks like this: public Fraction(double value, int maxDenominator) throws FractionConversionException { this(value, 0, maxDenominator, 100); } Increasing the 100 value (max iterations) does not fix the problem for all cases. Changing the 0-value (the epsilon, maximum allowed error) to something small does not work either, as this breaks the tests in FractionTest. The problem is not neccissarily that the algorithm is unable to approximate a fraction correctly. A solution where a FractionConversionException had been thrown in each of these examples would probably be the best solution if an improvement on the approximation algorithm turns out to be hard to find. This bug has been found when trying to explore the idea of axiom-based testing (<http://bldl.ii.uib.no/testing.html>). Attached is a java test class FractionTestByAxiom (junit, goes into org.apache.commons.math3.fraction) which shows these bugs through a simplified approach to this kind of testing, and a text file describing some of the value/maxDenominator combinations which causes one of these failures. * It is never specified in the documentation that the Fraction class guarantees that completely reduced rational numbers are constructed, but a comment inside the equals method claims that "since fractions are always in lowest terms, numerators and can be compared directly for equality", so it seems like this is the intention. ``` You are a professional Java test case writer, please create a test case named `testIntegerOverflow` for the issue `Math-MATH-836`, utilizing the provided issue report information and the following function signature. ```java @Test public void testIntegerOverflow() { ```
133
[ "org.apache.commons.math3.fraction.Fraction" ]
b18b08072f7a7b1697a28f59f75409b75765eaf5e177e814f18576eacd56a652
@Test public void testIntegerOverflow()
// You are a professional Java test case writer, please create a test case named `testIntegerOverflow` for the issue `Math-MATH-836`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-836 // // ## Issue-Title: // Fraction(double, int) constructor strange behaviour // // ## Issue-Description: // // The Fraction constructor Fraction(double, int) takes a double value and a int maximal denominator, and approximates a fraction. When the double value is a large, negative number with many digits in the fractional part, and the maximal denominator is a big, positive integer (in the 100'000s), two distinct bugs can manifest: // // // 1: the constructor returns a positive Fraction. Calling Fraction(-33655.1677817278, 371880) returns the fraction 410517235/243036, which both has the wrong sign, and is far away from the absolute value of the given value // // // 2: the constructor does not manage to reduce the Fraction properly. Calling Fraction(-43979.60679604749, 366081) returns the fraction -1651878166/256677, which should have\* been reduced to -24654898/3831. // // // I have, as of yet, not found a solution. The constructor looks like this: // // // public Fraction(double value, int maxDenominator) // // throws FractionConversionException // // // { // this(value, 0, maxDenominator, 100); // } // // Increasing the 100 value (max iterations) does not fix the problem for all cases. Changing the 0-value (the epsilon, maximum allowed error) to something small does not work either, as this breaks the tests in FractionTest. // // // The problem is not neccissarily that the algorithm is unable to approximate a fraction correctly. A solution where a FractionConversionException had been thrown in each of these examples would probably be the best solution if an improvement on the approximation algorithm turns out to be hard to find. // // // This bug has been found when trying to explore the idea of axiom-based testing (<http://bldl.ii.uib.no/testing.html>). Attached is a java test class FractionTestByAxiom (junit, goes into org.apache.commons.math3.fraction) which shows these bugs through a simplified approach to this kind of testing, and a text file describing some of the value/maxDenominator combinations which causes one of these failures. // // // * It is never specified in the documentation that the Fraction class guarantees that completely reduced rational numbers are constructed, but a comment inside the equals method claims that "since fractions are always in lowest terms, numerators and can be compared directly for equality", so it seems like this is the intention. // // // // //
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.fraction; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathArithmeticException; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * @version $Id$ */ public class FractionTest { private void assertFraction(int expectedNumerator, int expectedDenominator, Fraction actual) { Assert.assertEquals(expectedNumerator, actual.getNumerator()); Assert.assertEquals(expectedDenominator, actual.getDenominator()); } @Test public void testConstructor() { assertFraction(0, 1, new Fraction(0, 1)); assertFraction(0, 1, new Fraction(0, 2)); assertFraction(0, 1, new Fraction(0, -1)); assertFraction(1, 2, new Fraction(1, 2)); assertFraction(1, 2, new Fraction(2, 4)); assertFraction(-1, 2, new Fraction(-1, 2)); assertFraction(-1, 2, new Fraction(1, -2)); assertFraction(-1, 2, new Fraction(-2, 4)); assertFraction(-1, 2, new Fraction(2, -4)); // overflow try { new Fraction(Integer.MIN_VALUE, -1); Assert.fail(); } catch (MathArithmeticException ex) { // success } try { new Fraction(1, Integer.MIN_VALUE); Assert.fail(); } catch (MathArithmeticException ex) { // success } assertFraction(0, 1, new Fraction(0.00000000000001)); assertFraction(2, 5, new Fraction(0.40000000000001)); assertFraction(15, 1, new Fraction(15.0000000000001)); } @Test(expected=ConvergenceException.class) public void testGoldenRatio() { // the golden ratio is notoriously a difficult number for continuous fraction new Fraction((1 + FastMath.sqrt(5)) / 2, 1.0e-12, 25); } // MATH-179 @Test public void testDoubleConstructor() throws ConvergenceException { assertFraction(1, 2, new Fraction((double)1 / (double)2)); assertFraction(1, 3, new Fraction((double)1 / (double)3)); assertFraction(2, 3, new Fraction((double)2 / (double)3)); assertFraction(1, 4, new Fraction((double)1 / (double)4)); assertFraction(3, 4, new Fraction((double)3 / (double)4)); assertFraction(1, 5, new Fraction((double)1 / (double)5)); assertFraction(2, 5, new Fraction((double)2 / (double)5)); assertFraction(3, 5, new Fraction((double)3 / (double)5)); assertFraction(4, 5, new Fraction((double)4 / (double)5)); assertFraction(1, 6, new Fraction((double)1 / (double)6)); assertFraction(5, 6, new Fraction((double)5 / (double)6)); assertFraction(1, 7, new Fraction((double)1 / (double)7)); assertFraction(2, 7, new Fraction((double)2 / (double)7)); assertFraction(3, 7, new Fraction((double)3 / (double)7)); assertFraction(4, 7, new Fraction((double)4 / (double)7)); assertFraction(5, 7, new Fraction((double)5 / (double)7)); assertFraction(6, 7, new Fraction((double)6 / (double)7)); assertFraction(1, 8, new Fraction((double)1 / (double)8)); assertFraction(3, 8, new Fraction((double)3 / (double)8)); assertFraction(5, 8, new Fraction((double)5 / (double)8)); assertFraction(7, 8, new Fraction((double)7 / (double)8)); assertFraction(1, 9, new Fraction((double)1 / (double)9)); assertFraction(2, 9, new Fraction((double)2 / (double)9)); assertFraction(4, 9, new Fraction((double)4 / (double)9)); assertFraction(5, 9, new Fraction((double)5 / (double)9)); assertFraction(7, 9, new Fraction((double)7 / (double)9)); assertFraction(8, 9, new Fraction((double)8 / (double)9)); assertFraction(1, 10, new Fraction((double)1 / (double)10)); assertFraction(3, 10, new Fraction((double)3 / (double)10)); assertFraction(7, 10, new Fraction((double)7 / (double)10)); assertFraction(9, 10, new Fraction((double)9 / (double)10)); assertFraction(1, 11, new Fraction((double)1 / (double)11)); assertFraction(2, 11, new Fraction((double)2 / (double)11)); assertFraction(3, 11, new Fraction((double)3 / (double)11)); assertFraction(4, 11, new Fraction((double)4 / (double)11)); assertFraction(5, 11, new Fraction((double)5 / (double)11)); assertFraction(6, 11, new Fraction((double)6 / (double)11)); assertFraction(7, 11, new Fraction((double)7 / (double)11)); assertFraction(8, 11, new Fraction((double)8 / (double)11)); assertFraction(9, 11, new Fraction((double)9 / (double)11)); assertFraction(10, 11, new Fraction((double)10 / (double)11)); } // MATH-181 @Test public void testDigitLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 9)); assertFraction(2, 5, new Fraction(0.4, 99)); assertFraction(2, 5, new Fraction(0.4, 999)); assertFraction(3, 5, new Fraction(0.6152, 9)); assertFraction(8, 13, new Fraction(0.6152, 99)); assertFraction(510, 829, new Fraction(0.6152, 999)); assertFraction(769, 1250, new Fraction(0.6152, 9999)); } @Test public void testIntegerOverflow() { checkIntegerOverflow(0.75000000001455192); checkIntegerOverflow(1.0e10); checkIntegerOverflow(-1.0e10); checkIntegerOverflow(-43979.60679604749); } private void checkIntegerOverflow(double a) { try { new Fraction(a, 1.0e-12, 1000); Assert.fail("an exception should have been thrown"); } catch (ConvergenceException ce) { // expected behavior } } @Test public void testEpsilonLimitConstructor() throws ConvergenceException { assertFraction(2, 5, new Fraction(0.4, 1.0e-5, 100)); assertFraction(3, 5, new Fraction(0.6152, 0.02, 100)); assertFraction(8, 13, new Fraction(0.6152, 1.0e-3, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-4, 100)); assertFraction(251, 408, new Fraction(0.6152, 1.0e-5, 100)); assertFraction(510, 829, new Fraction(0.6152, 1.0e-6, 100)); assertFraction(769, 1250, new Fraction(0.6152, 1.0e-7, 100)); } @Test public void testCompareTo() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Fraction third = new Fraction(1, 2); Assert.assertEquals(0, first.compareTo(first)); Assert.assertEquals(0, first.compareTo(third)); Assert.assertEquals(1, first.compareTo(second)); Assert.assertEquals(-1, second.compareTo(first)); // these two values are different approximations of PI // the first one is approximately PI - 3.07e-18 // the second one is approximately PI + 1.936e-17 Fraction pi1 = new Fraction(1068966896, 340262731); Fraction pi2 = new Fraction( 411557987, 131002976); Assert.assertEquals(-1, pi1.compareTo(pi2)); Assert.assertEquals( 1, pi2.compareTo(pi1)); Assert.assertEquals(0.0, pi1.doubleValue() - pi2.doubleValue(), 1.0e-20); } @Test public void testDoubleValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Assert.assertEquals(0.5, first.doubleValue(), 0.0); Assert.assertEquals(1.0 / 3.0, second.doubleValue(), 0.0); } @Test public void testFloatValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(1, 3); Assert.assertEquals(0.5f, first.floatValue(), 0.0f); Assert.assertEquals((float)(1.0 / 3.0), second.floatValue(), 0.0f); } @Test public void testIntValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); Assert.assertEquals(0, first.intValue()); Assert.assertEquals(1, second.intValue()); } @Test public void testLongValue() { Fraction first = new Fraction(1, 2); Fraction second = new Fraction(3, 2); Assert.assertEquals(0L, first.longValue()); Assert.assertEquals(1L, second.longValue()); } @Test public void testConstructorDouble() { assertFraction(1, 2, new Fraction(0.5)); assertFraction(1, 3, new Fraction(1.0 / 3.0)); assertFraction(17, 100, new Fraction(17.0 / 100.0)); assertFraction(317, 100, new Fraction(317.0 / 100.0)); assertFraction(-1, 2, new Fraction(-0.5)); assertFraction(-1, 3, new Fraction(-1.0 / 3.0)); assertFraction(-17, 100, new Fraction(17.0 / -100.0)); assertFraction(-317, 100, new Fraction(-317.0 / 100.0)); } @Test public void testAbs() { Fraction a = new Fraction(10, 21); Fraction b = new Fraction(-10, 21); Fraction c = new Fraction(10, -21); assertFraction(10, 21, a.abs()); assertFraction(10, 21, b.abs()); assertFraction(10, 21, c.abs()); } @Test public void testPercentage() { Assert.assertEquals(50.0, new Fraction(1, 2).percentageValue(), 1.0e-15); } @Test public void testMath835() { final int numer = Integer.MAX_VALUE / 99; final int denom = 1; final double percentage = 100 * ((double) numer) / denom; final Fraction frac = new Fraction(numer, denom); // With the implementation that preceded the fix suggested in MATH-835, // this test was failing, due to overflow. Assert.assertEquals(percentage, frac.percentageValue(), Math.ulp(percentage)); } @Test public void testReciprocal() { Fraction f = null; f = new Fraction(50, 75); f = f.reciprocal(); Assert.assertEquals(3, f.getNumerator()); Assert.assertEquals(2, f.getDenominator()); f = new Fraction(4, 3); f = f.reciprocal(); Assert.assertEquals(3, f.getNumerator()); Assert.assertEquals(4, f.getDenominator()); f = new Fraction(-15, 47); f = f.reciprocal(); Assert.assertEquals(-47, f.getNumerator()); Assert.assertEquals(15, f.getDenominator()); f = new Fraction(0, 3); try { f = f.reciprocal(); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} // large values f = new Fraction(Integer.MAX_VALUE, 1); f = f.reciprocal(); Assert.assertEquals(1, f.getNumerator()); Assert.assertEquals(Integer.MAX_VALUE, f.getDenominator()); } @Test public void testNegate() { Fraction f = null; f = new Fraction(50, 75); f = f.negate(); Assert.assertEquals(-2, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); f = new Fraction(-50, 75); f = f.negate(); Assert.assertEquals(2, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); // large values f = new Fraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = f.negate(); Assert.assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); Assert.assertEquals(Integer.MAX_VALUE, f.getDenominator()); f = new Fraction(Integer.MIN_VALUE, 1); try { f = f.negate(); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} } @Test public void testAdd() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.add(a)); assertFraction(7, 6, a.add(b)); assertFraction(7, 6, b.add(a)); assertFraction(4, 3, b.add(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE - 1, 1); Fraction f2 = Fraction.ONE; Fraction f = f1.add(f2); Assert.assertEquals(Integer.MAX_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f = f1.add(1); Assert.assertEquals(Integer.MAX_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f1 = new Fraction(-1, 13*13*2*2); f2 = new Fraction(-2, 13*17*2); f = f1.add(f2); Assert.assertEquals(13*13*17*2*2, f.getDenominator()); Assert.assertEquals(-17 - 2*13*2, f.getNumerator()); try { f.add(null); Assert.fail("expecting MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = new Fraction(1,32768*3); f2 = new Fraction(1,59049); f = f1.add(f2); Assert.assertEquals(52451, f.getNumerator()); Assert.assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3); f = f1.add(f2); Assert.assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); Assert.assertEquals(Integer.MAX_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f = f.add(Fraction.ONE); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(-1,5); try { f = f1.add(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} try { f= new Fraction(-Integer.MAX_VALUE, 1); f = f.add(f); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.add(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} } @Test public void testDivide() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 1, a.divide(a)); assertFraction(3, 4, a.divide(b)); assertFraction(4, 3, b.divide(a)); assertFraction(1, 1, b.divide(b)); Fraction f1 = new Fraction(3, 5); Fraction f2 = Fraction.ZERO; try { f1.divide(f2); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(0, 5); f2 = new Fraction(2, 7); Fraction f = f1.divide(f2); Assert.assertSame(Fraction.ZERO, f); f1 = new Fraction(2, 7); f2 = Fraction.ONE; f = f1.divide(f2); Assert.assertEquals(2, f.getNumerator()); Assert.assertEquals(7, f.getDenominator()); f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1); Assert.assertEquals(1, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f2); Assert.assertEquals(Integer.MIN_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f.divide(null); Assert.fail("MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} try { f1 = new Fraction(1, Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} try { f1 = new Fraction(1, -Integer.MAX_VALUE); f = f1.divide(f1.reciprocal()); // should overflow Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(6, 35); f = f1.divide(15); Assert.assertEquals(2, f.getNumerator()); Assert.assertEquals(175, f.getDenominator()); } @Test public void testMultiply() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(1, 4, a.multiply(a)); assertFraction(1, 3, a.multiply(b)); assertFraction(1, 3, b.multiply(a)); assertFraction(4, 9, b.multiply(b)); Fraction f1 = new Fraction(Integer.MAX_VALUE, 1); Fraction f2 = new Fraction(Integer.MIN_VALUE, Integer.MAX_VALUE); Fraction f = f1.multiply(f2); Assert.assertEquals(Integer.MIN_VALUE, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f.multiply(null); Assert.fail("expecting MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} f1 = new Fraction(6, 35); f = f1.multiply(15); Assert.assertEquals(18, f.getNumerator()); Assert.assertEquals(7, f.getDenominator()); } @Test public void testSubtract() { Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); assertFraction(0, 1, a.subtract(a)); assertFraction(-1, 6, a.subtract(b)); assertFraction(1, 6, b.subtract(a)); assertFraction(0, 1, b.subtract(b)); Fraction f = new Fraction(1,1); try { f.subtract(null); Assert.fail("expecting MathIllegalArgumentException"); } catch (MathIllegalArgumentException ex) {} // if this fraction is subtracted naively, it will overflow. // check that it doesn't. Fraction f1 = new Fraction(1,32768*3); Fraction f2 = new Fraction(1,59049); f = f1.subtract(f2); Assert.assertEquals(-13085, f.getNumerator()); Assert.assertEquals(1934917632, f.getDenominator()); f1 = new Fraction(Integer.MIN_VALUE, 3); f2 = new Fraction(1,3).negate(); f = f1.subtract(f2); Assert.assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); Assert.assertEquals(3, f.getDenominator()); f1 = new Fraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); Assert.assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); f = f1.subtract(1); Assert.assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); Assert.assertEquals(1, f.getDenominator()); try { f1 = new Fraction(1, Integer.MAX_VALUE); f2 = new Fraction(1, Integer.MAX_VALUE - 1); f = f1.subtract(f2); Assert.fail("expecting MathArithmeticException"); //should overflow } catch (MathArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = new Fraction(Integer.MIN_VALUE, 5); f2 = new Fraction(1,5); try { f = f1.subtract(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} try { f= new Fraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} try { f= new Fraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) {} f1 = new Fraction(3,327680); f2 = new Fraction(2,59049); try { f = f1.subtract(f2); // should overflow Assert.fail("expecting MathArithmeticException but got: " + f.toString()); } catch (MathArithmeticException ex) {} } @Test public void testEqualsAndHashCode() { Fraction zero = new Fraction(0,1); Fraction nullFraction = null; Assert.assertTrue( zero.equals(zero)); Assert.assertFalse(zero.equals(nullFraction)); Assert.assertFalse(zero.equals(Double.valueOf(0))); Fraction zero2 = new Fraction(0,2); Assert.assertTrue(zero.equals(zero2)); Assert.assertEquals(zero.hashCode(), zero2.hashCode()); Fraction one = new Fraction(1,1); Assert.assertFalse((one.equals(zero) ||zero.equals(one))); } @Test public void testGetReducedFraction() { Fraction threeFourths = new Fraction(3, 4); Assert.assertTrue(threeFourths.equals(Fraction.getReducedFraction(6, 8))); Assert.assertTrue(Fraction.ZERO.equals(Fraction.getReducedFraction(0, -1))); try { Fraction.getReducedFraction(1, 0); Assert.fail("expecting MathArithmeticException"); } catch (MathArithmeticException ex) { // expected } Assert.assertEquals(Fraction.getReducedFraction (2, Integer.MIN_VALUE).getNumerator(),-1); Assert.assertEquals(Fraction.getReducedFraction (1, -1).getNumerator(), -1); } @Test public void testToString() { Assert.assertEquals("0", new Fraction(0, 3).toString()); Assert.assertEquals("3", new Fraction(6, 2).toString()); Assert.assertEquals("2 / 3", new Fraction(18, 27).toString()); } @Test public void testSerial() throws FractionConversionException { Fraction[] fractions = { new Fraction(3, 4), Fraction.ONE, Fraction.ZERO, new Fraction(17), new Fraction(FastMath.PI, 1000), new Fraction(-5, 2) }; for (Fraction fraction : fractions) { Assert.assertEquals(fraction, TestUtils.serializeAndRecover(fraction)); } } }
public void testEscapeJavaScript() { assertEquals(null, StringEscapeUtils.escapeJavaScript(null)); try { StringEscapeUtils.escapeJavaScript(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJavaScript(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeJavaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeJavaScript("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';")); }
org.apache.commons.lang.StringEscapeUtilsTest::testEscapeJavaScript
src/test/org/apache/commons/lang/StringEscapeUtilsTest.java
188
src/test/org/apache/commons/lang/StringEscapeUtilsTest.java
testEscapeJavaScript
/* * 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.lang; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests for {@link StringEscapeUtils}. * * @author <a href="mailto:[email protected]">Alexander Day Chaffee</a> * @version $Id$ */ public class StringEscapeUtilsTest extends TestCase { private final static String FOO = "foo"; public StringEscapeUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(StringEscapeUtilsTest.class); suite.setName("StringEscapeUtilsTest Tests"); return suite; } //----------------------------------------------------------------------- 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.escapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJava(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"); } 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.escapeJava(writer, original); assertEquals(expected, writer.toString()); } public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.unescapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava(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.unescapeJava(writer, original); assertEquals(unescaped, writer.toString()); } public void testEscapeJavaScript() { assertEquals(null, StringEscapeUtils.escapeJavaScript(null)); try { StringEscapeUtils.escapeJavaScript(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJavaScript(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeJavaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeJavaScript("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,&#26085;&#26412;&#35486; (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii doesn't number-escape", "~\u007F", "\u007E\u007F"}, {"8-bit ascii does number-escape", "&#128;&#159;", "\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.escapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } public void testUnescapeHtml() { 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.unescapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.unescapeHtml(sw, original); } 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.unescapeHtml("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml("Hello&##;World")); } public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#x80;&#x9F;")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#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.unescapeHtml(escapedC1 + escapedC2)); } } public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml("&zzzz;")); } public void testEscapeHtmlVersions() throws Exception { assertEquals("&Beta;", StringEscapeUtils.escapeHtml("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml("&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 use numbers, not names for HTML entities", "&#161;", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should use numbers, not names for HTML entities", "\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.escapeXml(sw, "<abc>"); } catch (IOException e) { } assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.unescapeXml(sw, "&lt;abc&gt;"); } catch (IOException e) { } assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() ); } // SQL // see http://www.jguru.com/faq/view.jsp?EID=8881 //-------------------- public void testEscapeSql() throws Exception { assertEquals("don''t stop", StringEscapeUtils.escapeSql("don't stop")); assertEquals("", StringEscapeUtils.escapeSql("")); assertEquals(null, StringEscapeUtils.escapeSql(null)); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 public void testStandaloneAmphersand() { assertEquals("<P&O>", StringEscapeUtils.unescapeHtml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeHtml("test & &lt;")); assertEquals("<P&O>", StringEscapeUtils.unescapeXml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & &lt;")); } public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml("& &amp;")); } }
// You are a professional Java test case writer, please create a test case named `testEscapeJavaScript` for the issue `Lang-LANG-363`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-363 // // ## Issue-Title: // StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly // // ## Issue-Description: // // If Javascripts including'/', IE will parse the scripts uncorrectly, actually '/' should be escaped to '\/'. // // For example, document.getElementById("test").value = '<script>alert(\'aaa\');</script>';this expression will make IE render page uncorrect, it should be document.getElementById("test").value = '<script>alert(\'aaa\');<\/script>'; // // // Btw, Spring's JavascriptEscape behavor is correct. // // Try to run below codes, you will find the difference: // // String s = "<script>alert('aaa');</script>"; // // String str = org.springframework.web.util.JavaScriptUtils.javaScriptEscape(s); // // System.out.println("Spring JS Escape : "+str); // // str = org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(s); // // System.out.println("Apache Common Lang JS Escape : "+ str); // // // // // public void testEscapeJavaScript() {
188
52
168
src/test/org/apache/commons/lang/StringEscapeUtilsTest.java
src/test
```markdown ## Issue-ID: Lang-LANG-363 ## Issue-Title: StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly ## Issue-Description: If Javascripts including'/', IE will parse the scripts uncorrectly, actually '/' should be escaped to '\/'. For example, document.getElementById("test").value = '<script>alert(\'aaa\');</script>';this expression will make IE render page uncorrect, it should be document.getElementById("test").value = '<script>alert(\'aaa\');<\/script>'; Btw, Spring's JavascriptEscape behavor is correct. Try to run below codes, you will find the difference: String s = "<script>alert('aaa');</script>"; String str = org.springframework.web.util.JavaScriptUtils.javaScriptEscape(s); System.out.println("Spring JS Escape : "+str); str = org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(s); System.out.println("Apache Common Lang JS Escape : "+ str); ``` You are a professional Java test case writer, please create a test case named `testEscapeJavaScript` for the issue `Lang-LANG-363`, utilizing the provided issue report information and the following function signature. ```java public void testEscapeJavaScript() { ```
168
[ "org.apache.commons.lang.StringEscapeUtils" ]
b5e4b6be56e6e0da70de161820ea62f3bc9a25192210ebce63b80a66b39fad2c
public void testEscapeJavaScript()
// You are a professional Java test case writer, please create a test case named `testEscapeJavaScript` for the issue `Lang-LANG-363`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-363 // // ## Issue-Title: // StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly // // ## Issue-Description: // // If Javascripts including'/', IE will parse the scripts uncorrectly, actually '/' should be escaped to '\/'. // // For example, document.getElementById("test").value = '<script>alert(\'aaa\');</script>';this expression will make IE render page uncorrect, it should be document.getElementById("test").value = '<script>alert(\'aaa\');<\/script>'; // // // Btw, Spring's JavascriptEscape behavor is correct. // // Try to run below codes, you will find the difference: // // String s = "<script>alert('aaa');</script>"; // // String str = org.springframework.web.util.JavaScriptUtils.javaScriptEscape(s); // // System.out.println("Spring JS Escape : "+str); // // str = org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(s); // // System.out.println("Apache Common Lang JS Escape : "+ str); // // // // //
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.lang; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests for {@link StringEscapeUtils}. * * @author <a href="mailto:[email protected]">Alexander Day Chaffee</a> * @version $Id$ */ public class StringEscapeUtilsTest extends TestCase { private final static String FOO = "foo"; public StringEscapeUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(StringEscapeUtilsTest.class); suite.setName("StringEscapeUtilsTest Tests"); return suite; } //----------------------------------------------------------------------- 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.escapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJava(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"); } 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.escapeJava(writer, original); assertEquals(expected, writer.toString()); } public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.unescapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava(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.unescapeJava(writer, original); assertEquals(unescaped, writer.toString()); } public void testEscapeJavaScript() { assertEquals(null, StringEscapeUtils.escapeJavaScript(null)); try { StringEscapeUtils.escapeJavaScript(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJavaScript(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeJavaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeJavaScript("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,&#26085;&#26412;&#35486; (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii doesn't number-escape", "~\u007F", "\u007E\u007F"}, {"8-bit ascii does number-escape", "&#128;&#159;", "\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.escapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } public void testUnescapeHtml() { 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.unescapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.unescapeHtml(sw, original); } 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.unescapeHtml("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml("Hello&##;World")); } public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#x80;&#x9F;")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("&#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.unescapeHtml(escapedC1 + escapedC2)); } } public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml("&zzzz;")); } public void testEscapeHtmlVersions() throws Exception { assertEquals("&Beta;", StringEscapeUtils.escapeHtml("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml("&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 use numbers, not names for HTML entities", "&#161;", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should use numbers, not names for HTML entities", "\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.escapeXml(sw, "<abc>"); } catch (IOException e) { } assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.unescapeXml(sw, "&lt;abc&gt;"); } catch (IOException e) { } assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() ); } // SQL // see http://www.jguru.com/faq/view.jsp?EID=8881 //-------------------- public void testEscapeSql() throws Exception { assertEquals("don''t stop", StringEscapeUtils.escapeSql("don't stop")); assertEquals("", StringEscapeUtils.escapeSql("")); assertEquals(null, StringEscapeUtils.escapeSql(null)); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 public void testStandaloneAmphersand() { assertEquals("<P&O>", StringEscapeUtils.unescapeHtml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeHtml("test & &lt;")); assertEquals("<P&O>", StringEscapeUtils.unescapeXml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & &lt;")); } public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml("& &amp;")); } }
public void testMath221() { assertEquals(new Complex(0,-1), new Complex(0,1).multiply(new Complex(-1,0))); }
org.apache.commons.math.complex.ComplexTest::testMath221
src/test/org/apache/commons/math/complex/ComplexTest.java
696
src/test/org/apache/commons/math/complex/ComplexTest.java
testMath221
/* * 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.complex; import org.apache.commons.math.TestUtils; import junit.framework.TestCase; /** * @version $Revision$ $Date$ */ public class ComplexTest extends TestCase { private double inf = Double.POSITIVE_INFINITY; private double neginf = Double.NEGATIVE_INFINITY; private double nan = Double.NaN; private double pi = Math.PI; private Complex oneInf = new Complex(1, inf); private Complex oneNegInf = new Complex(1, neginf); private Complex infOne = new Complex(inf, 1); private Complex infZero = new Complex(inf, 0); private Complex infNaN = new Complex(inf, nan); private Complex infNegInf = new Complex(inf, neginf); private Complex infInf = new Complex(inf, inf); private Complex negInfInf = new Complex(neginf, inf); private Complex negInfZero = new Complex(neginf, 0); private Complex negInfOne = new Complex(neginf, 1); private Complex negInfNaN = new Complex(neginf, nan); private Complex negInfNegInf = new Complex(neginf, neginf); private Complex oneNaN = new Complex(1, nan); private Complex zeroInf = new Complex(0, inf); private Complex zeroNaN = new Complex(0, nan); private Complex nanInf = new Complex(nan, inf); private Complex nanNegInf = new Complex(nan, neginf); private Complex nanZero = new Complex(nan, 0); public void testConstructor() { Complex z = new Complex(3.0, 4.0); assertEquals(3.0, z.getReal(), 1.0e-5); assertEquals(4.0, z.getImaginary(), 1.0e-5); } public void testConstructorNaN() { Complex z = new Complex(3.0, Double.NaN); assertTrue(z.isNaN()); z = new Complex(nan, 4.0); assertTrue(z.isNaN()); z = new Complex(3.0, 4.0); assertFalse(z.isNaN()); } public void testAbs() { Complex z = new Complex(3.0, 4.0); assertEquals(5.0, z.abs(), 1.0e-5); } public void testAbsNaN() { assertTrue(Double.isNaN(Complex.NaN.abs())); Complex z = new Complex(inf, nan); assertTrue(Double.isNaN(z.abs())); } public void testAbsInfinite() { Complex z = new Complex(inf, 0); assertEquals(inf, z.abs(), 0); z = new Complex(0, neginf); assertEquals(inf, z.abs(), 0); z = new Complex(inf, neginf); assertEquals(inf, z.abs(), 0); } public void testAdd() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.add(y); assertEquals(8.0, z.getReal(), 1.0e-5); assertEquals(10.0, z.getImaginary(), 1.0e-5); } public void testAddNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.add(Complex.NaN); assertTrue(z.isNaN()); z = new Complex(1, nan); Complex w = x.add(z); assertEquals(w.getReal(), 4.0, 0); assertTrue(Double.isNaN(w.getImaginary())); } public void testAddInfinite() { Complex x = new Complex(1, 1); Complex z = new Complex(inf, 0); Complex w = x.add(z); assertEquals(w.getImaginary(), 1, 0); assertEquals(inf, w.getReal(), 0); x = new Complex(neginf, 0); assertTrue(Double.isNaN(x.add(z).getReal())); } public void testConjugate() { Complex x = new Complex(3.0, 4.0); Complex z = x.conjugate(); assertEquals(3.0, z.getReal(), 1.0e-5); assertEquals(-4.0, z.getImaginary(), 1.0e-5); } public void testConjugateNaN() { Complex z = Complex.NaN.conjugate(); assertTrue(z.isNaN()); } public void testConjugateInfiinite() { Complex z = new Complex(0, inf); assertEquals(neginf, z.conjugate().getImaginary(), 0); z = new Complex(0, neginf); assertEquals(inf, z.conjugate().getImaginary(), 0); } public void testDivide() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.divide(y); assertEquals(39.0 / 61.0, z.getReal(), 1.0e-5); assertEquals(2.0 / 61.0, z.getImaginary(), 1.0e-5); } public void testDivideInfinite() { Complex x = new Complex(3, 4); Complex w = new Complex(neginf, inf); assertTrue(x.divide(w).equals(Complex.ZERO)); Complex z = w.divide(x); assertTrue(Double.isNaN(z.getReal())); assertEquals(inf, z.getImaginary(), 0); w = new Complex(inf, inf); z = w.divide(x); assertTrue(Double.isNaN(z.getImaginary())); assertEquals(inf, z.getReal(), 0); w = new Complex(1, inf); z = w.divide(w); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); } public void testDivideNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.NaN); assertTrue(z.isNaN()); } public void testDivideNaNInf() { Complex z = oneInf.divide(Complex.ONE); assertTrue(Double.isNaN(z.getReal())); assertEquals(inf, z.getImaginary(), 0); z = negInfNegInf.divide(oneNaN); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); z = negInfInf.divide(Complex.ONE); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); } public void testMultiply() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.multiply(y); assertEquals(-9.0, z.getReal(), 1.0e-5); assertEquals(38.0, z.getImaginary(), 1.0e-5); } public void testMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Complex.NaN); assertTrue(z.isNaN()); } public void testMultiplyNaNInf() { Complex z = new Complex(1,1); Complex w = z.multiply(infOne); assertEquals(w.getReal(), inf, 0); assertEquals(w.getImaginary(), inf, 0); // [MATH-164] assertTrue(new Complex( 1,0).multiply(infInf).equals(Complex.INF)); assertTrue(new Complex(-1,0).multiply(infInf).equals(Complex.INF)); assertTrue(new Complex( 1,0).multiply(negInfZero).equals(Complex.INF)); w = oneInf.multiply(oneNegInf); assertEquals(w.getReal(), inf, 0); assertEquals(w.getImaginary(), inf, 0); w = negInfNegInf.multiply(oneNaN); assertTrue(Double.isNaN(w.getReal())); assertTrue(Double.isNaN(w.getImaginary())); } public void testNegate() { Complex x = new Complex(3.0, 4.0); Complex z = x.negate(); assertEquals(-3.0, z.getReal(), 1.0e-5); assertEquals(-4.0, z.getImaginary(), 1.0e-5); } public void testNegateNaN() { Complex z = Complex.NaN.negate(); assertTrue(z.isNaN()); } public void testSubtract() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.subtract(y); assertEquals(-2.0, z.getReal(), 1.0e-5); assertEquals(-2.0, z.getImaginary(), 1.0e-5); } public void testSubtractNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.subtract(Complex.NaN); assertTrue(z.isNaN()); } public void testEqualsNull() { Complex x = new Complex(3.0, 4.0); assertFalse(x.equals(null)); } public void testEqualsClass() { Complex x = new Complex(3.0, 4.0); assertFalse(x.equals(this)); } public void testEqualsSame() { Complex x = new Complex(3.0, 4.0); assertTrue(x.equals(x)); } public void testEqualsTrue() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(3.0, 4.0); assertTrue(x.equals(y)); } public void testEqualsRealDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0 + Double.MIN_VALUE, 0.0); assertFalse(x.equals(y)); } public void testEqualsImaginaryDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); assertFalse(x.equals(y)); } public void testEqualsNaN() { Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Complex complexNaN = Complex.NaN; assertTrue(realNaN.equals(imaginaryNaN)); assertTrue(imaginaryNaN.equals(complexNaN)); assertTrue(realNaN.equals(complexNaN)); } public void testHashCode() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); assertFalse(x.hashCode()==y.hashCode()); y = new Complex(0.0 + Double.MIN_VALUE, 0.0); assertFalse(x.hashCode()==y.hashCode()); Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); assertEquals(realNaN.hashCode(), imaginaryNaN.hashCode()); assertEquals(imaginaryNaN.hashCode(), Complex.NaN.hashCode()); } public void testAcos() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.936812, -2.30551); TestUtils.assertEquals(expected, z.acos(), 1.0e-5); TestUtils.assertEquals(new Complex(Math.acos(0), 0), Complex.ZERO.acos(), 1.0e-12); } public void testAcosInf() { TestUtils.assertSame(Complex.NaN, oneInf.acos()); TestUtils.assertSame(Complex.NaN, oneNegInf.acos()); TestUtils.assertSame(Complex.NaN, infOne.acos()); TestUtils.assertSame(Complex.NaN, negInfOne.acos()); TestUtils.assertSame(Complex.NaN, infInf.acos()); TestUtils.assertSame(Complex.NaN, infNegInf.acos()); TestUtils.assertSame(Complex.NaN, negInfInf.acos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.acos()); } public void testAcosNaN() { assertTrue(Complex.NaN.acos().isNaN()); } public void testAsin() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.633984, 2.30551); TestUtils.assertEquals(expected, z.asin(), 1.0e-5); } public void testAsinNaN() { assertTrue(Complex.NaN.asin().isNaN()); } public void testAsinInf() { TestUtils.assertSame(Complex.NaN, oneInf.asin()); TestUtils.assertSame(Complex.NaN, oneNegInf.asin()); TestUtils.assertSame(Complex.NaN, infOne.asin()); TestUtils.assertSame(Complex.NaN, negInfOne.asin()); TestUtils.assertSame(Complex.NaN, infInf.asin()); TestUtils.assertSame(Complex.NaN, infNegInf.asin()); TestUtils.assertSame(Complex.NaN, negInfInf.asin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.asin()); } public void testAtan() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.44831, 0.158997); TestUtils.assertEquals(expected, z.atan(), 1.0e-5); } public void testAtanInf() { TestUtils.assertSame(Complex.NaN, oneInf.atan()); TestUtils.assertSame(Complex.NaN, oneNegInf.atan()); TestUtils.assertSame(Complex.NaN, infOne.atan()); TestUtils.assertSame(Complex.NaN, negInfOne.atan()); TestUtils.assertSame(Complex.NaN, infInf.atan()); TestUtils.assertSame(Complex.NaN, infNegInf.atan()); TestUtils.assertSame(Complex.NaN, negInfInf.atan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.atan()); } public void testAtanNaN() { assertTrue(Complex.NaN.atan().isNaN()); assertTrue(Complex.I.atan().isNaN()); } public void testCos() { Complex z = new Complex(3, 4); Complex expected = new Complex(-27.03495, -3.851153); TestUtils.assertEquals(expected, z.cos(), 1.0e-5); } public void testCosNaN() { assertTrue(Complex.NaN.cos().isNaN()); } public void testCosInf() { TestUtils.assertSame(infNegInf, oneInf.cos()); TestUtils.assertSame(infInf, oneNegInf.cos()); TestUtils.assertSame(Complex.NaN, infOne.cos()); TestUtils.assertSame(Complex.NaN, negInfOne.cos()); TestUtils.assertSame(Complex.NaN, infInf.cos()); TestUtils.assertSame(Complex.NaN, infNegInf.cos()); TestUtils.assertSame(Complex.NaN, negInfInf.cos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cos()); } public void testCosh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.58066, -7.58155); TestUtils.assertEquals(expected, z.cosh(), 1.0e-5); } public void testCoshNaN() { assertTrue(Complex.NaN.cosh().isNaN()); } public void testCoshInf() { TestUtils.assertSame(Complex.NaN, oneInf.cosh()); TestUtils.assertSame(Complex.NaN, oneNegInf.cosh()); TestUtils.assertSame(infInf, infOne.cosh()); TestUtils.assertSame(infNegInf, negInfOne.cosh()); TestUtils.assertSame(Complex.NaN, infInf.cosh()); TestUtils.assertSame(Complex.NaN, infNegInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cosh()); } public void testExp() { Complex z = new Complex(3, 4); Complex expected = new Complex(-13.12878, -15.20078); TestUtils.assertEquals(expected, z.exp(), 1.0e-5); TestUtils.assertEquals(Complex.ONE, Complex.ZERO.exp(), 10e-12); Complex iPi = Complex.I.multiply(new Complex(pi,0)); TestUtils.assertEquals(Complex.ONE.negate(), iPi.exp(), 10e-12); } public void testExpNaN() { assertTrue(Complex.NaN.exp().isNaN()); } public void testExpInf() { TestUtils.assertSame(Complex.NaN, oneInf.exp()); TestUtils.assertSame(Complex.NaN, oneNegInf.exp()); TestUtils.assertSame(infInf, infOne.exp()); TestUtils.assertSame(Complex.ZERO, negInfOne.exp()); TestUtils.assertSame(Complex.NaN, infInf.exp()); TestUtils.assertSame(Complex.NaN, infNegInf.exp()); TestUtils.assertSame(Complex.NaN, negInfInf.exp()); TestUtils.assertSame(Complex.NaN, negInfNegInf.exp()); } public void testLog() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.60944, 0.927295); TestUtils.assertEquals(expected, z.log(), 1.0e-5); } public void testLogNaN() { assertTrue(Complex.NaN.log().isNaN()); } public void testLogInf() { TestUtils.assertEquals(new Complex(inf, pi / 2), oneInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 2), oneNegInf.log(), 10e-12); TestUtils.assertEquals(infZero, infOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi), negInfOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi / 4), infInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 4), infNegInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, 3d * pi / 4), negInfInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, - 3d * pi / 4), negInfNegInf.log(), 10e-12); } public void testLogZero() { TestUtils.assertSame(negInfZero, Complex.ZERO.log()); } public void testPow() { Complex x = new Complex(3, 4); Complex y = new Complex(5, 6); Complex expected = new Complex(-1.860893, 11.83677); TestUtils.assertEquals(expected, x.pow(y), 1.0e-5); } public void testPowNaNBase() { Complex x = new Complex(3, 4); assertTrue(Complex.NaN.pow(x).isNaN()); } public void testPowNaNExponent() { Complex x = new Complex(3, 4); assertTrue(x.pow(Complex.NaN).isNaN()); } public void testPowInf() { TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infOne)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infInf)); } public void testPowZero() { TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ZERO)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.I)); TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, Complex.I.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(Complex.ZERO), 10e-12); } public void testpowNull() { try { Complex.ONE.pow(null); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected } } public void testSin() { Complex z = new Complex(3, 4); Complex expected = new Complex(3.853738, -27.01681); TestUtils.assertEquals(expected, z.sin(), 1.0e-5); } public void testSinInf() { TestUtils.assertSame(infInf, oneInf.sin()); TestUtils.assertSame(infNegInf, oneNegInf.sin()); TestUtils.assertSame(Complex.NaN, infOne.sin()); TestUtils.assertSame(Complex.NaN, negInfOne.sin()); TestUtils.assertSame(Complex.NaN, infInf.sin()); TestUtils.assertSame(Complex.NaN, infNegInf.sin()); TestUtils.assertSame(Complex.NaN, negInfInf.sin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sin()); } public void testSinNaN() { assertTrue(Complex.NaN.sin().isNaN()); } public void testSinh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.54812, -7.61923); TestUtils.assertEquals(expected, z.sinh(), 1.0e-5); } public void testSinhNaN() { assertTrue(Complex.NaN.sinh().isNaN()); } public void testSinhInf() { TestUtils.assertSame(Complex.NaN, oneInf.sinh()); TestUtils.assertSame(Complex.NaN, oneNegInf.sinh()); TestUtils.assertSame(infInf, infOne.sinh()); TestUtils.assertSame(negInfInf, negInfOne.sinh()); TestUtils.assertSame(Complex.NaN, infInf.sinh()); TestUtils.assertSame(Complex.NaN, infNegInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sinh()); } public void testSqrtRealPositive() { Complex z = new Complex(3, 4); Complex expected = new Complex(2, 1); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtRealZero() { Complex z = new Complex(0.0, 4); Complex expected = new Complex(1.41421, 1.41421); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtRealNegative() { Complex z = new Complex(-3.0, 4); Complex expected = new Complex(1, 2); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtImaginaryZero() { Complex z = new Complex(-3.0, 0.0); Complex expected = new Complex(0.0, 1.73205); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtImaginaryNegative() { Complex z = new Complex(-3.0, -4.0); Complex expected = new Complex(1.0, -2.0); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtPolar() { double r = 1; for (int i = 0; i < 5; i++) { r += i; double theta = 0; for (int j =0; j < 11; j++) { theta += pi /12; Complex z = ComplexUtils.polar2Complex(r, theta); Complex sqrtz = ComplexUtils.polar2Complex(Math.sqrt(r), theta / 2); TestUtils.assertEquals(sqrtz, z.sqrt(), 10e-12); } } } public void testSqrtNaN() { assertTrue(Complex.NaN.sqrt().isNaN()); } public void testSqrtInf() { TestUtils.assertSame(infNaN, oneInf.sqrt()); TestUtils.assertSame(infNaN, oneNegInf.sqrt()); TestUtils.assertSame(infZero, infOne.sqrt()); TestUtils.assertSame(zeroInf, negInfOne.sqrt()); TestUtils.assertSame(infNaN, infInf.sqrt()); TestUtils.assertSame(infNaN, infNegInf.sqrt()); TestUtils.assertSame(nanInf, negInfInf.sqrt()); TestUtils.assertSame(nanNegInf, negInfNegInf.sqrt()); } public void testSqrt1z() { Complex z = new Complex(3, 4); Complex expected = new Complex(4.08033, -2.94094); TestUtils.assertEquals(expected, z.sqrt1z(), 1.0e-5); } public void testSqrt1zNaN() { assertTrue(Complex.NaN.sqrt1z().isNaN()); } public void testTan() { Complex z = new Complex(3, 4); Complex expected = new Complex(-0.000187346, 0.999356); TestUtils.assertEquals(expected, z.tan(), 1.0e-5); } public void testTanNaN() { assertTrue(Complex.NaN.tan().isNaN()); } public void testTanInf() { TestUtils.assertSame(zeroNaN, oneInf.tan()); TestUtils.assertSame(zeroNaN, oneNegInf.tan()); TestUtils.assertSame(Complex.NaN, infOne.tan()); TestUtils.assertSame(Complex.NaN, negInfOne.tan()); TestUtils.assertSame(Complex.NaN, infInf.tan()); TestUtils.assertSame(Complex.NaN, infNegInf.tan()); TestUtils.assertSame(Complex.NaN, negInfInf.tan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tan()); } public void testTanCritical() { TestUtils.assertSame(infNaN, new Complex(pi/2, 0).tan()); TestUtils.assertSame(negInfNaN, new Complex(-pi/2, 0).tan()); } public void testTanh() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.00071, 0.00490826); TestUtils.assertEquals(expected, z.tanh(), 1.0e-5); } public void testTanhNaN() { assertTrue(Complex.NaN.tanh().isNaN()); } public void testTanhInf() { TestUtils.assertSame(Complex.NaN, oneInf.tanh()); TestUtils.assertSame(Complex.NaN, oneNegInf.tanh()); TestUtils.assertSame(nanZero, infOne.tanh()); TestUtils.assertSame(nanZero, negInfOne.tanh()); TestUtils.assertSame(Complex.NaN, infInf.tanh()); TestUtils.assertSame(Complex.NaN, infNegInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tanh()); } public void testTanhCritical() { TestUtils.assertSame(nanInf, new Complex(0, pi/2).tanh()); } /** test issue MATH-221 */ public void testMath221() { assertEquals(new Complex(0,-1), new Complex(0,1).multiply(new Complex(-1,0))); } }
// You are a professional Java test case writer, please create a test case named `testMath221` for the issue `Math-MATH-221`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-221 // // ## Issue-Title: // Result of multiplying and equals for complex numbers is wrong // // ## Issue-Description: // // Hi. // // // The bug relates on complex numbers. // // The methods "multiply" and "equals" of the class Complex are involved. // // // mathematic background: (0,i) \* (-1,0i) = (0,-i). // // // little java program + output that shows the bug: // // ----------------------------------------------------------------------- // // // // // ``` // import org.apache.commons.math.complex.*; // public class TestProg { // public static void main(String[] args) { // // ComplexFormat f = new ComplexFormat(); // Complex c1 = new Complex(0,1); // Complex c2 = new Complex(-1,0); // // Complex res = c1.multiply(c2); // Complex comp = new Complex(0,-1); // // System.out.println("res: "+f.format(res)); // System.out.println("comp: "+f.format(comp)); // // System.out.println("res=comp: "+res.equals(comp)); // } // } // // ``` // // // ----------------------------------------------------------------------- // // // res: -0 - 1i // // comp: 0 - 1i // // res=comp: false // // // ----------------------------------------------------------------------- // // // I think the "equals" should return "true". // // The problem could either be the "multiply" method that gives (-0,-1i) instead of (0,-1i), // // or if you think thats right, the equals method has to be modified. // // // Good Luck // // Dieter // // // // // public void testMath221() {
696
/** test issue MATH-221 */
96
694
src/test/org/apache/commons/math/complex/ComplexTest.java
src/test
```markdown ## Issue-ID: Math-MATH-221 ## Issue-Title: Result of multiplying and equals for complex numbers is wrong ## Issue-Description: Hi. The bug relates on complex numbers. The methods "multiply" and "equals" of the class Complex are involved. mathematic background: (0,i) \* (-1,0i) = (0,-i). little java program + output that shows the bug: ----------------------------------------------------------------------- ``` import org.apache.commons.math.complex.*; public class TestProg { public static void main(String[] args) { ComplexFormat f = new ComplexFormat(); Complex c1 = new Complex(0,1); Complex c2 = new Complex(-1,0); Complex res = c1.multiply(c2); Complex comp = new Complex(0,-1); System.out.println("res: "+f.format(res)); System.out.println("comp: "+f.format(comp)); System.out.println("res=comp: "+res.equals(comp)); } } ``` ----------------------------------------------------------------------- res: -0 - 1i comp: 0 - 1i res=comp: false ----------------------------------------------------------------------- I think the "equals" should return "true". The problem could either be the "multiply" method that gives (-0,-1i) instead of (0,-1i), or if you think thats right, the equals method has to be modified. Good Luck Dieter ``` You are a professional Java test case writer, please create a test case named `testMath221` for the issue `Math-MATH-221`, utilizing the provided issue report information and the following function signature. ```java public void testMath221() { ```
694
[ "org.apache.commons.math.complex.Complex" ]
b6fd83df563ac2ee9a670a216844e821bb02ee7d278f6561e38dc532c546e75d
public void testMath221()
// You are a professional Java test case writer, please create a test case named `testMath221` for the issue `Math-MATH-221`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-221 // // ## Issue-Title: // Result of multiplying and equals for complex numbers is wrong // // ## Issue-Description: // // Hi. // // // The bug relates on complex numbers. // // The methods "multiply" and "equals" of the class Complex are involved. // // // mathematic background: (0,i) \* (-1,0i) = (0,-i). // // // little java program + output that shows the bug: // // ----------------------------------------------------------------------- // // // // // ``` // import org.apache.commons.math.complex.*; // public class TestProg { // public static void main(String[] args) { // // ComplexFormat f = new ComplexFormat(); // Complex c1 = new Complex(0,1); // Complex c2 = new Complex(-1,0); // // Complex res = c1.multiply(c2); // Complex comp = new Complex(0,-1); // // System.out.println("res: "+f.format(res)); // System.out.println("comp: "+f.format(comp)); // // System.out.println("res=comp: "+res.equals(comp)); // } // } // // ``` // // // ----------------------------------------------------------------------- // // // res: -0 - 1i // // comp: 0 - 1i // // res=comp: false // // // ----------------------------------------------------------------------- // // // I think the "equals" should return "true". // // The problem could either be the "multiply" method that gives (-0,-1i) instead of (0,-1i), // // or if you think thats right, the equals method has to be modified. // // // Good Luck // // Dieter // // // // //
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.complex; import org.apache.commons.math.TestUtils; import junit.framework.TestCase; /** * @version $Revision$ $Date$ */ public class ComplexTest extends TestCase { private double inf = Double.POSITIVE_INFINITY; private double neginf = Double.NEGATIVE_INFINITY; private double nan = Double.NaN; private double pi = Math.PI; private Complex oneInf = new Complex(1, inf); private Complex oneNegInf = new Complex(1, neginf); private Complex infOne = new Complex(inf, 1); private Complex infZero = new Complex(inf, 0); private Complex infNaN = new Complex(inf, nan); private Complex infNegInf = new Complex(inf, neginf); private Complex infInf = new Complex(inf, inf); private Complex negInfInf = new Complex(neginf, inf); private Complex negInfZero = new Complex(neginf, 0); private Complex negInfOne = new Complex(neginf, 1); private Complex negInfNaN = new Complex(neginf, nan); private Complex negInfNegInf = new Complex(neginf, neginf); private Complex oneNaN = new Complex(1, nan); private Complex zeroInf = new Complex(0, inf); private Complex zeroNaN = new Complex(0, nan); private Complex nanInf = new Complex(nan, inf); private Complex nanNegInf = new Complex(nan, neginf); private Complex nanZero = new Complex(nan, 0); public void testConstructor() { Complex z = new Complex(3.0, 4.0); assertEquals(3.0, z.getReal(), 1.0e-5); assertEquals(4.0, z.getImaginary(), 1.0e-5); } public void testConstructorNaN() { Complex z = new Complex(3.0, Double.NaN); assertTrue(z.isNaN()); z = new Complex(nan, 4.0); assertTrue(z.isNaN()); z = new Complex(3.0, 4.0); assertFalse(z.isNaN()); } public void testAbs() { Complex z = new Complex(3.0, 4.0); assertEquals(5.0, z.abs(), 1.0e-5); } public void testAbsNaN() { assertTrue(Double.isNaN(Complex.NaN.abs())); Complex z = new Complex(inf, nan); assertTrue(Double.isNaN(z.abs())); } public void testAbsInfinite() { Complex z = new Complex(inf, 0); assertEquals(inf, z.abs(), 0); z = new Complex(0, neginf); assertEquals(inf, z.abs(), 0); z = new Complex(inf, neginf); assertEquals(inf, z.abs(), 0); } public void testAdd() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.add(y); assertEquals(8.0, z.getReal(), 1.0e-5); assertEquals(10.0, z.getImaginary(), 1.0e-5); } public void testAddNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.add(Complex.NaN); assertTrue(z.isNaN()); z = new Complex(1, nan); Complex w = x.add(z); assertEquals(w.getReal(), 4.0, 0); assertTrue(Double.isNaN(w.getImaginary())); } public void testAddInfinite() { Complex x = new Complex(1, 1); Complex z = new Complex(inf, 0); Complex w = x.add(z); assertEquals(w.getImaginary(), 1, 0); assertEquals(inf, w.getReal(), 0); x = new Complex(neginf, 0); assertTrue(Double.isNaN(x.add(z).getReal())); } public void testConjugate() { Complex x = new Complex(3.0, 4.0); Complex z = x.conjugate(); assertEquals(3.0, z.getReal(), 1.0e-5); assertEquals(-4.0, z.getImaginary(), 1.0e-5); } public void testConjugateNaN() { Complex z = Complex.NaN.conjugate(); assertTrue(z.isNaN()); } public void testConjugateInfiinite() { Complex z = new Complex(0, inf); assertEquals(neginf, z.conjugate().getImaginary(), 0); z = new Complex(0, neginf); assertEquals(inf, z.conjugate().getImaginary(), 0); } public void testDivide() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.divide(y); assertEquals(39.0 / 61.0, z.getReal(), 1.0e-5); assertEquals(2.0 / 61.0, z.getImaginary(), 1.0e-5); } public void testDivideInfinite() { Complex x = new Complex(3, 4); Complex w = new Complex(neginf, inf); assertTrue(x.divide(w).equals(Complex.ZERO)); Complex z = w.divide(x); assertTrue(Double.isNaN(z.getReal())); assertEquals(inf, z.getImaginary(), 0); w = new Complex(inf, inf); z = w.divide(x); assertTrue(Double.isNaN(z.getImaginary())); assertEquals(inf, z.getReal(), 0); w = new Complex(1, inf); z = w.divide(w); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); } public void testDivideNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.divide(Complex.NaN); assertTrue(z.isNaN()); } public void testDivideNaNInf() { Complex z = oneInf.divide(Complex.ONE); assertTrue(Double.isNaN(z.getReal())); assertEquals(inf, z.getImaginary(), 0); z = negInfNegInf.divide(oneNaN); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); z = negInfInf.divide(Complex.ONE); assertTrue(Double.isNaN(z.getReal())); assertTrue(Double.isNaN(z.getImaginary())); } public void testMultiply() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.multiply(y); assertEquals(-9.0, z.getReal(), 1.0e-5); assertEquals(38.0, z.getImaginary(), 1.0e-5); } public void testMultiplyNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.multiply(Complex.NaN); assertTrue(z.isNaN()); } public void testMultiplyNaNInf() { Complex z = new Complex(1,1); Complex w = z.multiply(infOne); assertEquals(w.getReal(), inf, 0); assertEquals(w.getImaginary(), inf, 0); // [MATH-164] assertTrue(new Complex( 1,0).multiply(infInf).equals(Complex.INF)); assertTrue(new Complex(-1,0).multiply(infInf).equals(Complex.INF)); assertTrue(new Complex( 1,0).multiply(negInfZero).equals(Complex.INF)); w = oneInf.multiply(oneNegInf); assertEquals(w.getReal(), inf, 0); assertEquals(w.getImaginary(), inf, 0); w = negInfNegInf.multiply(oneNaN); assertTrue(Double.isNaN(w.getReal())); assertTrue(Double.isNaN(w.getImaginary())); } public void testNegate() { Complex x = new Complex(3.0, 4.0); Complex z = x.negate(); assertEquals(-3.0, z.getReal(), 1.0e-5); assertEquals(-4.0, z.getImaginary(), 1.0e-5); } public void testNegateNaN() { Complex z = Complex.NaN.negate(); assertTrue(z.isNaN()); } public void testSubtract() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(5.0, 6.0); Complex z = x.subtract(y); assertEquals(-2.0, z.getReal(), 1.0e-5); assertEquals(-2.0, z.getImaginary(), 1.0e-5); } public void testSubtractNaN() { Complex x = new Complex(3.0, 4.0); Complex z = x.subtract(Complex.NaN); assertTrue(z.isNaN()); } public void testEqualsNull() { Complex x = new Complex(3.0, 4.0); assertFalse(x.equals(null)); } public void testEqualsClass() { Complex x = new Complex(3.0, 4.0); assertFalse(x.equals(this)); } public void testEqualsSame() { Complex x = new Complex(3.0, 4.0); assertTrue(x.equals(x)); } public void testEqualsTrue() { Complex x = new Complex(3.0, 4.0); Complex y = new Complex(3.0, 4.0); assertTrue(x.equals(y)); } public void testEqualsRealDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0 + Double.MIN_VALUE, 0.0); assertFalse(x.equals(y)); } public void testEqualsImaginaryDifference() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); assertFalse(x.equals(y)); } public void testEqualsNaN() { Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); Complex complexNaN = Complex.NaN; assertTrue(realNaN.equals(imaginaryNaN)); assertTrue(imaginaryNaN.equals(complexNaN)); assertTrue(realNaN.equals(complexNaN)); } public void testHashCode() { Complex x = new Complex(0.0, 0.0); Complex y = new Complex(0.0, 0.0 + Double.MIN_VALUE); assertFalse(x.hashCode()==y.hashCode()); y = new Complex(0.0 + Double.MIN_VALUE, 0.0); assertFalse(x.hashCode()==y.hashCode()); Complex realNaN = new Complex(Double.NaN, 0.0); Complex imaginaryNaN = new Complex(0.0, Double.NaN); assertEquals(realNaN.hashCode(), imaginaryNaN.hashCode()); assertEquals(imaginaryNaN.hashCode(), Complex.NaN.hashCode()); } public void testAcos() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.936812, -2.30551); TestUtils.assertEquals(expected, z.acos(), 1.0e-5); TestUtils.assertEquals(new Complex(Math.acos(0), 0), Complex.ZERO.acos(), 1.0e-12); } public void testAcosInf() { TestUtils.assertSame(Complex.NaN, oneInf.acos()); TestUtils.assertSame(Complex.NaN, oneNegInf.acos()); TestUtils.assertSame(Complex.NaN, infOne.acos()); TestUtils.assertSame(Complex.NaN, negInfOne.acos()); TestUtils.assertSame(Complex.NaN, infInf.acos()); TestUtils.assertSame(Complex.NaN, infNegInf.acos()); TestUtils.assertSame(Complex.NaN, negInfInf.acos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.acos()); } public void testAcosNaN() { assertTrue(Complex.NaN.acos().isNaN()); } public void testAsin() { Complex z = new Complex(3, 4); Complex expected = new Complex(0.633984, 2.30551); TestUtils.assertEquals(expected, z.asin(), 1.0e-5); } public void testAsinNaN() { assertTrue(Complex.NaN.asin().isNaN()); } public void testAsinInf() { TestUtils.assertSame(Complex.NaN, oneInf.asin()); TestUtils.assertSame(Complex.NaN, oneNegInf.asin()); TestUtils.assertSame(Complex.NaN, infOne.asin()); TestUtils.assertSame(Complex.NaN, negInfOne.asin()); TestUtils.assertSame(Complex.NaN, infInf.asin()); TestUtils.assertSame(Complex.NaN, infNegInf.asin()); TestUtils.assertSame(Complex.NaN, negInfInf.asin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.asin()); } public void testAtan() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.44831, 0.158997); TestUtils.assertEquals(expected, z.atan(), 1.0e-5); } public void testAtanInf() { TestUtils.assertSame(Complex.NaN, oneInf.atan()); TestUtils.assertSame(Complex.NaN, oneNegInf.atan()); TestUtils.assertSame(Complex.NaN, infOne.atan()); TestUtils.assertSame(Complex.NaN, negInfOne.atan()); TestUtils.assertSame(Complex.NaN, infInf.atan()); TestUtils.assertSame(Complex.NaN, infNegInf.atan()); TestUtils.assertSame(Complex.NaN, negInfInf.atan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.atan()); } public void testAtanNaN() { assertTrue(Complex.NaN.atan().isNaN()); assertTrue(Complex.I.atan().isNaN()); } public void testCos() { Complex z = new Complex(3, 4); Complex expected = new Complex(-27.03495, -3.851153); TestUtils.assertEquals(expected, z.cos(), 1.0e-5); } public void testCosNaN() { assertTrue(Complex.NaN.cos().isNaN()); } public void testCosInf() { TestUtils.assertSame(infNegInf, oneInf.cos()); TestUtils.assertSame(infInf, oneNegInf.cos()); TestUtils.assertSame(Complex.NaN, infOne.cos()); TestUtils.assertSame(Complex.NaN, negInfOne.cos()); TestUtils.assertSame(Complex.NaN, infInf.cos()); TestUtils.assertSame(Complex.NaN, infNegInf.cos()); TestUtils.assertSame(Complex.NaN, negInfInf.cos()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cos()); } public void testCosh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.58066, -7.58155); TestUtils.assertEquals(expected, z.cosh(), 1.0e-5); } public void testCoshNaN() { assertTrue(Complex.NaN.cosh().isNaN()); } public void testCoshInf() { TestUtils.assertSame(Complex.NaN, oneInf.cosh()); TestUtils.assertSame(Complex.NaN, oneNegInf.cosh()); TestUtils.assertSame(infInf, infOne.cosh()); TestUtils.assertSame(infNegInf, negInfOne.cosh()); TestUtils.assertSame(Complex.NaN, infInf.cosh()); TestUtils.assertSame(Complex.NaN, infNegInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfInf.cosh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.cosh()); } public void testExp() { Complex z = new Complex(3, 4); Complex expected = new Complex(-13.12878, -15.20078); TestUtils.assertEquals(expected, z.exp(), 1.0e-5); TestUtils.assertEquals(Complex.ONE, Complex.ZERO.exp(), 10e-12); Complex iPi = Complex.I.multiply(new Complex(pi,0)); TestUtils.assertEquals(Complex.ONE.negate(), iPi.exp(), 10e-12); } public void testExpNaN() { assertTrue(Complex.NaN.exp().isNaN()); } public void testExpInf() { TestUtils.assertSame(Complex.NaN, oneInf.exp()); TestUtils.assertSame(Complex.NaN, oneNegInf.exp()); TestUtils.assertSame(infInf, infOne.exp()); TestUtils.assertSame(Complex.ZERO, negInfOne.exp()); TestUtils.assertSame(Complex.NaN, infInf.exp()); TestUtils.assertSame(Complex.NaN, infNegInf.exp()); TestUtils.assertSame(Complex.NaN, negInfInf.exp()); TestUtils.assertSame(Complex.NaN, negInfNegInf.exp()); } public void testLog() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.60944, 0.927295); TestUtils.assertEquals(expected, z.log(), 1.0e-5); } public void testLogNaN() { assertTrue(Complex.NaN.log().isNaN()); } public void testLogInf() { TestUtils.assertEquals(new Complex(inf, pi / 2), oneInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 2), oneNegInf.log(), 10e-12); TestUtils.assertEquals(infZero, infOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi), negInfOne.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, pi / 4), infInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, -pi / 4), infNegInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, 3d * pi / 4), negInfInf.log(), 10e-12); TestUtils.assertEquals(new Complex(inf, - 3d * pi / 4), negInfNegInf.log(), 10e-12); } public void testLogZero() { TestUtils.assertSame(negInfZero, Complex.ZERO.log()); } public void testPow() { Complex x = new Complex(3, 4); Complex y = new Complex(5, 6); Complex expected = new Complex(-1.860893, 11.83677); TestUtils.assertEquals(expected, x.pow(y), 1.0e-5); } public void testPowNaNBase() { Complex x = new Complex(3, 4); assertTrue(Complex.NaN.pow(x).isNaN()); } public void testPowNaNExponent() { Complex x = new Complex(3, 4); assertTrue(x.pow(Complex.NaN).isNaN()); } public void testPowInf() { TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(oneNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infOne)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfInf)); TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfOne.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infInf.pow(infInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(negInfNegInf)); TestUtils.assertSame(Complex.NaN,infNegInf.pow(infInf)); } public void testPowZero() { TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ONE)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.ZERO)); TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(Complex.I)); TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, Complex.I.pow(Complex.ZERO), 10e-12); TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(Complex.ZERO), 10e-12); } public void testpowNull() { try { Complex.ONE.pow(null); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { // expected } } public void testSin() { Complex z = new Complex(3, 4); Complex expected = new Complex(3.853738, -27.01681); TestUtils.assertEquals(expected, z.sin(), 1.0e-5); } public void testSinInf() { TestUtils.assertSame(infInf, oneInf.sin()); TestUtils.assertSame(infNegInf, oneNegInf.sin()); TestUtils.assertSame(Complex.NaN, infOne.sin()); TestUtils.assertSame(Complex.NaN, negInfOne.sin()); TestUtils.assertSame(Complex.NaN, infInf.sin()); TestUtils.assertSame(Complex.NaN, infNegInf.sin()); TestUtils.assertSame(Complex.NaN, negInfInf.sin()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sin()); } public void testSinNaN() { assertTrue(Complex.NaN.sin().isNaN()); } public void testSinh() { Complex z = new Complex(3, 4); Complex expected = new Complex(-6.54812, -7.61923); TestUtils.assertEquals(expected, z.sinh(), 1.0e-5); } public void testSinhNaN() { assertTrue(Complex.NaN.sinh().isNaN()); } public void testSinhInf() { TestUtils.assertSame(Complex.NaN, oneInf.sinh()); TestUtils.assertSame(Complex.NaN, oneNegInf.sinh()); TestUtils.assertSame(infInf, infOne.sinh()); TestUtils.assertSame(negInfInf, negInfOne.sinh()); TestUtils.assertSame(Complex.NaN, infInf.sinh()); TestUtils.assertSame(Complex.NaN, infNegInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfInf.sinh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.sinh()); } public void testSqrtRealPositive() { Complex z = new Complex(3, 4); Complex expected = new Complex(2, 1); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtRealZero() { Complex z = new Complex(0.0, 4); Complex expected = new Complex(1.41421, 1.41421); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtRealNegative() { Complex z = new Complex(-3.0, 4); Complex expected = new Complex(1, 2); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtImaginaryZero() { Complex z = new Complex(-3.0, 0.0); Complex expected = new Complex(0.0, 1.73205); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtImaginaryNegative() { Complex z = new Complex(-3.0, -4.0); Complex expected = new Complex(1.0, -2.0); TestUtils.assertEquals(expected, z.sqrt(), 1.0e-5); } public void testSqrtPolar() { double r = 1; for (int i = 0; i < 5; i++) { r += i; double theta = 0; for (int j =0; j < 11; j++) { theta += pi /12; Complex z = ComplexUtils.polar2Complex(r, theta); Complex sqrtz = ComplexUtils.polar2Complex(Math.sqrt(r), theta / 2); TestUtils.assertEquals(sqrtz, z.sqrt(), 10e-12); } } } public void testSqrtNaN() { assertTrue(Complex.NaN.sqrt().isNaN()); } public void testSqrtInf() { TestUtils.assertSame(infNaN, oneInf.sqrt()); TestUtils.assertSame(infNaN, oneNegInf.sqrt()); TestUtils.assertSame(infZero, infOne.sqrt()); TestUtils.assertSame(zeroInf, negInfOne.sqrt()); TestUtils.assertSame(infNaN, infInf.sqrt()); TestUtils.assertSame(infNaN, infNegInf.sqrt()); TestUtils.assertSame(nanInf, negInfInf.sqrt()); TestUtils.assertSame(nanNegInf, negInfNegInf.sqrt()); } public void testSqrt1z() { Complex z = new Complex(3, 4); Complex expected = new Complex(4.08033, -2.94094); TestUtils.assertEquals(expected, z.sqrt1z(), 1.0e-5); } public void testSqrt1zNaN() { assertTrue(Complex.NaN.sqrt1z().isNaN()); } public void testTan() { Complex z = new Complex(3, 4); Complex expected = new Complex(-0.000187346, 0.999356); TestUtils.assertEquals(expected, z.tan(), 1.0e-5); } public void testTanNaN() { assertTrue(Complex.NaN.tan().isNaN()); } public void testTanInf() { TestUtils.assertSame(zeroNaN, oneInf.tan()); TestUtils.assertSame(zeroNaN, oneNegInf.tan()); TestUtils.assertSame(Complex.NaN, infOne.tan()); TestUtils.assertSame(Complex.NaN, negInfOne.tan()); TestUtils.assertSame(Complex.NaN, infInf.tan()); TestUtils.assertSame(Complex.NaN, infNegInf.tan()); TestUtils.assertSame(Complex.NaN, negInfInf.tan()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tan()); } public void testTanCritical() { TestUtils.assertSame(infNaN, new Complex(pi/2, 0).tan()); TestUtils.assertSame(negInfNaN, new Complex(-pi/2, 0).tan()); } public void testTanh() { Complex z = new Complex(3, 4); Complex expected = new Complex(1.00071, 0.00490826); TestUtils.assertEquals(expected, z.tanh(), 1.0e-5); } public void testTanhNaN() { assertTrue(Complex.NaN.tanh().isNaN()); } public void testTanhInf() { TestUtils.assertSame(Complex.NaN, oneInf.tanh()); TestUtils.assertSame(Complex.NaN, oneNegInf.tanh()); TestUtils.assertSame(nanZero, infOne.tanh()); TestUtils.assertSame(nanZero, negInfOne.tanh()); TestUtils.assertSame(Complex.NaN, infInf.tanh()); TestUtils.assertSame(Complex.NaN, infNegInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfInf.tanh()); TestUtils.assertSame(Complex.NaN, negInfNegInf.tanh()); } public void testTanhCritical() { TestUtils.assertSame(nanInf, new Complex(0, pi/2).tanh()); } /** test issue MATH-221 */ public void testMath221() { assertEquals(new Complex(0,-1), new Complex(0,1).multiply(new Complex(-1,0))); } }
@Test public void listener() throws Exception { InvocationListener invocationListener = mock(InvocationListener.class); List mockedList = mock(List.class, withSettings().invocationListeners(invocationListener)); reset(mockedList); mockedList.clear(); verify(invocationListener).reportInvocation(any(MethodInvocationReport.class)); }
org.mockitousage.bugs.ListenersLostOnResetMockTest::listener
test/org/mockitousage/bugs/ListenersLostOnResetMockTest.java
23
test/org/mockitousage/bugs/ListenersLostOnResetMockTest.java
listener
package org.mockitousage.bugs; import org.junit.Test; import org.mockito.listeners.InvocationListener; import org.mockito.listeners.MethodInvocationReport; import java.util.List; import static org.mockito.Mockito.*; public class ListenersLostOnResetMockTest { @Test public void listener() throws Exception { InvocationListener invocationListener = mock(InvocationListener.class); List mockedList = mock(List.class, withSettings().invocationListeners(invocationListener)); reset(mockedList); mockedList.clear(); verify(invocationListener).reportInvocation(any(MethodInvocationReport.class)); } }
// You are a professional Java test case writer, please create a test case named `listener` for the issue `Mockito-282`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-282 // // ## Issue-Title: // Exception when stubbing more than once with when...thenThrow // // ## Issue-Description: // If I create a mock and stub a method so it throws an exception and do that twice the first exception will be thrown upon invoking the second stub instruction. // // // Example: // // // // ``` // @Test // public void testThrowException() { // Object o = Mockito.mock(Object.class); // // test behavior with Runtimeexception // Mockito.when(o.toString()).thenThrow(RuntimeException.class); // // ... // // test behavior with another exception // // this throws a RuntimeException // Mockito.when(o.toString()).thenThrow(IllegalArgumentException.class); // // ... // } // // ``` // // I can work around this if I do it the other way around with doThrow...when. But I lose type safety then. Can you fix this? // // // // @Test public void listener() throws Exception {
23
27
13
test/org/mockitousage/bugs/ListenersLostOnResetMockTest.java
test
```markdown ## Issue-ID: Mockito-282 ## Issue-Title: Exception when stubbing more than once with when...thenThrow ## Issue-Description: If I create a mock and stub a method so it throws an exception and do that twice the first exception will be thrown upon invoking the second stub instruction. Example: ``` @Test public void testThrowException() { Object o = Mockito.mock(Object.class); // test behavior with Runtimeexception Mockito.when(o.toString()).thenThrow(RuntimeException.class); // ... // test behavior with another exception // this throws a RuntimeException Mockito.when(o.toString()).thenThrow(IllegalArgumentException.class); // ... } ``` I can work around this if I do it the other way around with doThrow...when. But I lose type safety then. Can you fix this? ``` You are a professional Java test case writer, please create a test case named `listener` for the issue `Mockito-282`, utilizing the provided issue report information and the following function signature. ```java @Test public void listener() throws Exception { ```
13
[ "org.mockito.internal.util.MockUtil" ]
b74e7e68b70d1da61135a8f91daf1b25cbfa79d32ded35fa5a793db61280f82d
@Test public void listener() throws Exception
// You are a professional Java test case writer, please create a test case named `listener` for the issue `Mockito-282`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Mockito-282 // // ## Issue-Title: // Exception when stubbing more than once with when...thenThrow // // ## Issue-Description: // If I create a mock and stub a method so it throws an exception and do that twice the first exception will be thrown upon invoking the second stub instruction. // // // Example: // // // // ``` // @Test // public void testThrowException() { // Object o = Mockito.mock(Object.class); // // test behavior with Runtimeexception // Mockito.when(o.toString()).thenThrow(RuntimeException.class); // // ... // // test behavior with another exception // // this throws a RuntimeException // Mockito.when(o.toString()).thenThrow(IllegalArgumentException.class); // // ... // } // // ``` // // I can work around this if I do it the other way around with doThrow...when. But I lose type safety then. Can you fix this? // // // //
Mockito
package org.mockitousage.bugs; import org.junit.Test; import org.mockito.listeners.InvocationListener; import org.mockito.listeners.MethodInvocationReport; import java.util.List; import static org.mockito.Mockito.*; public class ListenersLostOnResetMockTest { @Test public void listener() throws Exception { InvocationListener invocationListener = mock(InvocationListener.class); List mockedList = mock(List.class, withSettings().invocationListeners(invocationListener)); reset(mockedList); mockedList.clear(); verify(invocationListener).reportInvocation(any(MethodInvocationReport.class)); } }
@Test public void createsFormData() { String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>" + "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' value='off'>" + "<input name='eight' type='checkbox' checked><input name='nine' type='checkbox' value='unset'>" + "<input name='ten' value='text' disabled>" + "<input name='eleven' value='text' type='button'>" + "</form>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(6, data.size()); assertEquals("one=two", data.get(0).toString()); assertEquals("three=four", data.get(1).toString()); assertEquals("three=five", data.get(2).toString()); assertEquals("six=seven", data.get(3).toString()); assertEquals("seven=on", data.get(4).toString()); // set assertEquals("eight=on", data.get(5).toString()); // default // nine should not appear, not checked checkbox // ten should not appear, disabled // eleven should not appear, button }
org.jsoup.nodes.FormElementTest::createsFormData
src/test/java/org/jsoup/nodes/FormElementTest.java
48
src/test/java/org/jsoup/nodes/FormElementTest.java
createsFormData
package org.jsoup.nodes; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** * Tests for FormElement * * @author Jonathan Hedley */ public class FormElementTest { @Test public void hasAssociatedControls() { //"button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" String html = "<form id=1><button id=1><fieldset id=2 /><input id=3><keygen id=4><object id=5><output id=6>" + "<select id=7><option></select><textarea id=8><p id=9>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); assertEquals(8, form.elements().size()); } @Test public void createsFormData() { String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>" + "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' value='off'>" + "<input name='eight' type='checkbox' checked><input name='nine' type='checkbox' value='unset'>" + "<input name='ten' value='text' disabled>" + "<input name='eleven' value='text' type='button'>" + "</form>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(6, data.size()); assertEquals("one=two", data.get(0).toString()); assertEquals("three=four", data.get(1).toString()); assertEquals("three=five", data.get(2).toString()); assertEquals("six=seven", data.get(3).toString()); assertEquals("seven=on", data.get(4).toString()); // set assertEquals("eight=on", data.get(5).toString()); // default // nine should not appear, not checked checkbox // ten should not appear, disabled // eleven should not appear, button } @Test public void formDataUsesFirstAttribute() { String html = "<form><input name=test value=foo name=test2 value=bar>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.selectFirst("form"); assertEquals("test=foo", form.formData().get(0).toString()); } @Test public void createsSubmitableConnection() { String html = "<form action='/search'><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); doc.select("[name=q]").attr("value", "jsoup"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals(Connection.Method.GET, con.request().method()); assertEquals("http://example.com/search", con.request().url().toExternalForm()); List<Connection.KeyVal> dataList = (List<Connection.KeyVal>) con.request().data(); assertEquals("q=jsoup", dataList.get(0).toString()); doc.select("form").attr("method", "post"); Connection con2 = form.submit(); assertEquals(Connection.Method.POST, con2.request().method()); } @Test public void actionWithNoValue() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals("http://example.com/", con.request().url().toExternalForm()); } @Test public void actionWithNoBaseUri() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html); FormElement form = ((FormElement) doc.select("form").first()); boolean threw = false; try { Connection con = form.submit(); } catch (IllegalArgumentException e) { threw = true; assertEquals("Could not determine a form action URL for submit. Ensure you set a base URI when parsing.", e.getMessage()); } assertTrue(threw); } @Test public void formsAddedAfterParseAreFormElements() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form action='http://example.com/search'><input name='q' value='search'>"); Element formEl = doc.select("form").first(); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); } @Test public void controlsAddedAfterParseAreLinkedWithForms() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form />"); Element formEl = doc.select("form").first(); formEl.append("<input name=foo value=bar>"); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); List<Connection.KeyVal> data = form.formData(); assertEquals("foo=bar", data.get(0).toString()); } @Test public void usesOnForCheckboxValueIfNoValueSet() { Document doc = Jsoup.parse("<form><input type=checkbox checked name=foo></form>"); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals("on", data.get(0).value()); assertEquals("foo", data.get(0).key()); } @Test public void adoptedFormsRetainInputs() { // test for https://github.com/jhy/jsoup/issues/249 String html = "<html>\n" + "<body> \n" + " <table>\n" + " <form action=\"/hello.php\" method=\"post\">\n" + " <tr><td>User:</td><td> <input type=\"text\" name=\"user\" /></td></tr>\n" + " <tr><td>Password:</td><td> <input type=\"password\" name=\"pass\" /></td></tr>\n" + " <tr><td><input type=\"submit\" name=\"login\" value=\"login\" /></td></tr>\n" + " </form>\n" + " </table>\n" + "</body>\n" + "</html>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(3, data.size()); assertEquals("user", data.get(0).key()); assertEquals("pass", data.get(1).key()); assertEquals("login", data.get(2).key()); } @Test public void removeFormElement() { String html = "<html>\n" + " <body> \n" + " <form action=\"/hello.php\" method=\"post\">\n" + " User:<input type=\"text\" name=\"user\" />\n" + " Password:<input type=\"password\" name=\"pass\" />\n" + " <input type=\"submit\" name=\"login\" value=\"login\" />\n" + " </form>\n" + " </body>\n" + "</html> "; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.selectFirst("form"); Element pass = form.selectFirst("input[name=pass]"); pass.remove(); List<Connection.KeyVal> data = form.formData(); assertEquals(2, data.size()); assertEquals("user", data.get(0).key()); assertEquals("login", data.get(1).key()); assertEquals(null, doc.selectFirst("input[name=pass]")); } }
// You are a professional Java test case writer, please create a test case named `createsFormData` for the issue `Jsoup-1231`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1231 // // ## Issue-Title: // <input type="image"> is not special cased in formData method // // ## Issue-Description: // The following code: // // // // ``` // import org.jsoup.Jsoup; // import org.jsoup.nodes.FormElement; // // class Scratch { // public static void main(String[] args) { // System.out.println(((FormElement) Jsoup.parse("<form id=f><input type=image name=x></form>").getElementById("f")).formData()); // } // } // ``` // // Returns the following output: // // // // ``` // [x=] // // ``` // // When either `[]` or `[x.x=0, x.y=0]` is expected (not sure which, but `[x=]` is definitely wrong). // // // // @Test public void createsFormData() {
48
93
26
src/test/java/org/jsoup/nodes/FormElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-1231 ## Issue-Title: <input type="image"> is not special cased in formData method ## Issue-Description: The following code: ``` import org.jsoup.Jsoup; import org.jsoup.nodes.FormElement; class Scratch { public static void main(String[] args) { System.out.println(((FormElement) Jsoup.parse("<form id=f><input type=image name=x></form>").getElementById("f")).formData()); } } ``` Returns the following output: ``` [x=] ``` When either `[]` or `[x.x=0, x.y=0]` is expected (not sure which, but `[x=]` is definitely wrong). ``` You are a professional Java test case writer, please create a test case named `createsFormData` for the issue `Jsoup-1231`, utilizing the provided issue report information and the following function signature. ```java @Test public void createsFormData() { ```
26
[ "org.jsoup.nodes.FormElement" ]
b7e5f4016bf4f09f8f361eaf3f693083dad381b9a96cf70d3ab701e6ab0132d6
@Test public void createsFormData()
// You are a professional Java test case writer, please create a test case named `createsFormData` for the issue `Jsoup-1231`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-1231 // // ## Issue-Title: // <input type="image"> is not special cased in formData method // // ## Issue-Description: // The following code: // // // // ``` // import org.jsoup.Jsoup; // import org.jsoup.nodes.FormElement; // // class Scratch { // public static void main(String[] args) { // System.out.println(((FormElement) Jsoup.parse("<form id=f><input type=image name=x></form>").getElementById("f")).formData()); // } // } // ``` // // Returns the following output: // // // // ``` // [x=] // // ``` // // When either `[]` or `[x.x=0, x.y=0]` is expected (not sure which, but `[x=]` is definitely wrong). // // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** * Tests for FormElement * * @author Jonathan Hedley */ public class FormElementTest { @Test public void hasAssociatedControls() { //"button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" String html = "<form id=1><button id=1><fieldset id=2 /><input id=3><keygen id=4><object id=5><output id=6>" + "<select id=7><option></select><textarea id=8><p id=9>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); assertEquals(8, form.elements().size()); } @Test public void createsFormData() { String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>" + "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' value='off'>" + "<input name='eight' type='checkbox' checked><input name='nine' type='checkbox' value='unset'>" + "<input name='ten' value='text' disabled>" + "<input name='eleven' value='text' type='button'>" + "</form>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(6, data.size()); assertEquals("one=two", data.get(0).toString()); assertEquals("three=four", data.get(1).toString()); assertEquals("three=five", data.get(2).toString()); assertEquals("six=seven", data.get(3).toString()); assertEquals("seven=on", data.get(4).toString()); // set assertEquals("eight=on", data.get(5).toString()); // default // nine should not appear, not checked checkbox // ten should not appear, disabled // eleven should not appear, button } @Test public void formDataUsesFirstAttribute() { String html = "<form><input name=test value=foo name=test2 value=bar>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.selectFirst("form"); assertEquals("test=foo", form.formData().get(0).toString()); } @Test public void createsSubmitableConnection() { String html = "<form action='/search'><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); doc.select("[name=q]").attr("value", "jsoup"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals(Connection.Method.GET, con.request().method()); assertEquals("http://example.com/search", con.request().url().toExternalForm()); List<Connection.KeyVal> dataList = (List<Connection.KeyVal>) con.request().data(); assertEquals("q=jsoup", dataList.get(0).toString()); doc.select("form").attr("method", "post"); Connection con2 = form.submit(); assertEquals(Connection.Method.POST, con2.request().method()); } @Test public void actionWithNoValue() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals("http://example.com/", con.request().url().toExternalForm()); } @Test public void actionWithNoBaseUri() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html); FormElement form = ((FormElement) doc.select("form").first()); boolean threw = false; try { Connection con = form.submit(); } catch (IllegalArgumentException e) { threw = true; assertEquals("Could not determine a form action URL for submit. Ensure you set a base URI when parsing.", e.getMessage()); } assertTrue(threw); } @Test public void formsAddedAfterParseAreFormElements() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form action='http://example.com/search'><input name='q' value='search'>"); Element formEl = doc.select("form").first(); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); } @Test public void controlsAddedAfterParseAreLinkedWithForms() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form />"); Element formEl = doc.select("form").first(); formEl.append("<input name=foo value=bar>"); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); List<Connection.KeyVal> data = form.formData(); assertEquals("foo=bar", data.get(0).toString()); } @Test public void usesOnForCheckboxValueIfNoValueSet() { Document doc = Jsoup.parse("<form><input type=checkbox checked name=foo></form>"); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals("on", data.get(0).value()); assertEquals("foo", data.get(0).key()); } @Test public void adoptedFormsRetainInputs() { // test for https://github.com/jhy/jsoup/issues/249 String html = "<html>\n" + "<body> \n" + " <table>\n" + " <form action=\"/hello.php\" method=\"post\">\n" + " <tr><td>User:</td><td> <input type=\"text\" name=\"user\" /></td></tr>\n" + " <tr><td>Password:</td><td> <input type=\"password\" name=\"pass\" /></td></tr>\n" + " <tr><td><input type=\"submit\" name=\"login\" value=\"login\" /></td></tr>\n" + " </form>\n" + " </table>\n" + "</body>\n" + "</html>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(3, data.size()); assertEquals("user", data.get(0).key()); assertEquals("pass", data.get(1).key()); assertEquals("login", data.get(2).key()); } @Test public void removeFormElement() { String html = "<html>\n" + " <body> \n" + " <form action=\"/hello.php\" method=\"post\">\n" + " User:<input type=\"text\" name=\"user\" />\n" + " Password:<input type=\"password\" name=\"pass\" />\n" + " <input type=\"submit\" name=\"login\" value=\"login\" />\n" + " </form>\n" + " </body>\n" + "</html> "; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.selectFirst("form"); Element pass = form.selectFirst("input[name=pass]"); pass.remove(); List<Connection.KeyVal> data = form.formData(); assertEquals(2, data.size()); assertEquals("user", data.get(0).key()); assertEquals("login", data.get(1).key()); assertEquals(null, doc.selectFirst("input[name=pass]")); } }
public void testSuspiciousBlockCommentWarning3() { parse("/* \n *@type {number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); }
com.google.javascript.jscomp.parsing.ParserTest::testSuspiciousBlockCommentWarning3
test/com/google/javascript/jscomp/parsing/ParserTest.java
695
test/com/google/javascript/jscomp/parsing/ParserTest.java
testSuspiciousBlockCommentWarning3
/* * 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.javascript.jscomp.parsing.Config.LanguageMode; import com.google.javascript.jscomp.testing.TestErrorReporter; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.head.ScriptRuntime; import com.google.javascript.rhino.jstype.SimpleSourceFile; import com.google.javascript.rhino.jstype.StaticSourceFile; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import java.io.IOException; import java.util.List; import java.util.logging.Logger; public class ParserTest extends BaseJSTypeTestCase { private static final String SUSPICIOUS_COMMENT_WARNING = IRFactory.SUSPICIOUS_COMMENT_WARNING; private static final String TRAILING_COMMA_MESSAGE = ScriptRuntime.getMessage0("msg.extra.trailing.comma"); private static final String BAD_PROPERTY_MESSAGE = ScriptRuntime.getMessage0("msg.bad.prop"); private static final String MISSING_GT_MESSAGE = "Bad type annotation. " + com.google.javascript.rhino.SimpleErrorReporter.getMessage0( "msg.jsdoc.missing.gt"); private static final String MISPLACED_TYPE_ANNOTATION = IRFactory.MISPLACED_TYPE_ANNOTATION; private Config.LanguageMode mode; private boolean isIdeMode = false; @Override protected void setUp() throws Exception { super.setUp(); mode = LanguageMode.ECMASCRIPT3; isIdeMode = false; } public void testLinenoCharnoAssign1() throws Exception { Node assign = parse("a = b").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(1, assign.getLineno()); assertEquals(0, assign.getCharno()); } public void testLinenoCharnoAssign2() throws Exception { Node assign = parse("\n a.g.h.k = 45").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(2, assign.getLineno()); assertEquals(1, assign.getCharno()); } public void testLinenoCharnoCall() throws Exception { Node call = parse("\n foo(123);").getFirstChild().getFirstChild(); assertEquals(Token.CALL, call.getType()); assertEquals(2, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetProp1() throws Exception { Node getprop = parse("\n foo.bar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(2, name.getLineno()); assertEquals(5, name.getCharno()); } public void testLinenoCharnoGetProp2() throws Exception { Node getprop = parse("\n foo.\nbar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(3, name.getLineno()); assertEquals(0, name.getCharno()); } public void testLinenoCharnoGetelem1() throws Exception { Node call = parse("\n foo[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(2, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem2() throws Exception { Node call = parse("\n \n foo()[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem3() throws Exception { Node call = parse("\n \n (8 + kl)[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoForComparison() throws Exception { Node lt = parse("for (; i < j;){}").getFirstChild().getFirstChild().getNext(); assertEquals(Token.LT, lt.getType()); assertEquals(1, lt.getLineno()); assertEquals(7, lt.getCharno()); } public void testLinenoCharnoHook() throws Exception { Node n = parse("\n a ? 9 : 0").getFirstChild().getFirstChild(); assertEquals(Token.HOOK, n.getType()); assertEquals(2, n.getLineno()); assertEquals(1, n.getCharno()); } public void testLinenoCharnoArrayLiteral() throws Exception { Node n = parse("\n [8, 9]").getFirstChild().getFirstChild(); assertEquals(Token.ARRAYLIT, n.getType()); assertEquals(2, n.getLineno()); assertEquals(2, n.getCharno()); n = n.getFirstChild(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(3, n.getCharno()); n = n.getNext(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(6, n.getCharno()); } public void testLinenoCharnoObjectLiteral() throws Exception { Node n = parse("\n\n var a = {a:0\n,b :1};") .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, n.getType()); assertEquals(3, n.getLineno()); assertEquals(9, n.getCharno()); Node key = n.getFirstChild(); assertEquals(Token.STRING_KEY, key.getType()); assertEquals(3, key.getLineno()); assertEquals(10, key.getCharno()); Node value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(3, value.getLineno()); assertEquals(12, value.getCharno()); key = key.getNext(); assertEquals(Token.STRING_KEY, key.getType()); assertEquals(4, key.getLineno()); assertEquals(1, key.getCharno()); value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(4, value.getLineno()); assertEquals(4, value.getCharno()); } public void testLinenoCharnoAdd() throws Exception { testLinenoCharnoBinop("+"); } public void testLinenoCharnoSub() throws Exception { testLinenoCharnoBinop("-"); } public void testLinenoCharnoMul() throws Exception { testLinenoCharnoBinop("*"); } public void testLinenoCharnoDiv() throws Exception { testLinenoCharnoBinop("/"); } public void testLinenoCharnoMod() throws Exception { testLinenoCharnoBinop("%"); } public void testLinenoCharnoShift() throws Exception { testLinenoCharnoBinop("<<"); } public void testLinenoCharnoBinaryAnd() throws Exception { testLinenoCharnoBinop("&"); } public void testLinenoCharnoAnd() throws Exception { testLinenoCharnoBinop("&&"); } public void testLinenoCharnoBinaryOr() throws Exception { testLinenoCharnoBinop("|"); } public void testLinenoCharnoOr() throws Exception { testLinenoCharnoBinop("||"); } public void testLinenoCharnoLt() throws Exception { testLinenoCharnoBinop("<"); } public void testLinenoCharnoLe() throws Exception { testLinenoCharnoBinop("<="); } public void testLinenoCharnoGt() throws Exception { testLinenoCharnoBinop(">"); } public void testLinenoCharnoGe() throws Exception { testLinenoCharnoBinop(">="); } private void testLinenoCharnoBinop(String binop) { Node op = parse("var a = 89 " + binop + " 76").getFirstChild(). getFirstChild().getFirstChild(); assertEquals(1, op.getLineno()); assertEquals(8, op.getCharno()); } public void testJSDocAttachment1() { Node varNode = parse("/** @type number */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment2() { Node varNode = parse("/** @type number */var a,b;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // First NAME Node nameNode1 = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode1.getType()); assertNull(nameNode1.getJSDocInfo()); // Second NAME Node nameNode2 = nameNode1.getNext(); assertEquals(Token.NAME, nameNode2.getType()); assertNull(nameNode2.getJSDocInfo()); } public void testJSDocAttachment3() { Node assignNode = parse( "/** @type number */goog.FOO = 5;").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assignNode.getType()); JSDocInfo info = assignNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment4() { Node varNode = parse( "var a, /** @define {number} */ b = 5;").getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNull(a.getJSDocInfo()); // b Node b = a.getNext(); JSDocInfo info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment5() { Node varNode = parse( "var /** @type number */a, /** @define {number} */b = 5;") .getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNotNull(a.getJSDocInfo()); JSDocInfo info = a.getJSDocInfo(); assertNotNull(info); assertFalse(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); // b Node b = a.getNext(); info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } /** * Tests that a JSDoc comment in an unexpected place of the code does not * propagate to following code due to {@link JSDocInfo} aggregation. */ public void testJSDocAttachment6() throws Exception { Node functionNode = parse( "var a = /** @param {number} index */5;" + "/** @return boolean */function f(index){}") .getFirstChild().getNext(); assertEquals(Token.FUNCTION, functionNode.getType()); JSDocInfo info = functionNode.getJSDocInfo(); assertNotNull(info); assertFalse(info.hasParameter("index")); assertTrue(info.hasReturnType()); assertTypeEquals(UNKNOWN_TYPE, info.getReturnType()); } public void testJSDocAttachment7() { Node varNode = parse("/** */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment8() { Node varNode = parse("/** x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment9() { Node varNode = parse("/** \n x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment10() { Node varNode = parse("/** x\n */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment11() { Node varNode = parse("/** @type {{x : number, 'y' : string, z}} */var a;") .getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(createRecordTypeBuilder(). addProperty("x", NUMBER_TYPE, null). addProperty("y", STRING_TYPE, null). addProperty("z", UNKNOWN_TYPE, null). build(), info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment12() { Node varNode = parse("var a = {/** @type {Object} */ b: c};") .getFirstChild(); Node objectLitNode = varNode.getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLitNode.getType()); assertNotNull(objectLitNode.getFirstChild().getJSDocInfo()); } public void testJSDocAttachment13() { Node varNode = parse("/** foo */ var a;").getFirstChild(); assertNotNull(varNode.getJSDocInfo()); } public void testJSDocAttachment14() { Node varNode = parse("/** */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testJSDocAttachment15() { Node varNode = parse("/** \n * \n */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testJSDocAttachment16() { Node exprCall = parse("/** @private */ x(); function f() {};").getFirstChild(); assertEquals(Token.EXPR_RESULT, exprCall.getType()); assertNull(exprCall.getNext().getJSDocInfo()); assertNotNull(exprCall.getFirstChild().getJSDocInfo()); } public void testJSDocAttachment17() { Node fn = parse( "function f() { " + " return /** @type {string} */ (g(1 /** @desc x */));" + "};").getFirstChild(); assertEquals(Token.FUNCTION, fn.getType()); Node cast = fn.getLastChild().getFirstChild().getFirstChild(); assertEquals(Token.CAST, cast.getType()); } public void testJSDocAttachment18() { Node fn = parse( "function f() { " + " var x = /** @type {string} */ (y);" + "};").getFirstChild(); assertEquals(Token.FUNCTION, fn.getType()); Node cast = fn.getLastChild().getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.CAST, cast.getType()); } public void testInlineJSDocAttachment1() { Node fn = parse("function f(/** string */ x) {}").getFirstChild(); assertTrue(fn.isFunction()); JSDocInfo info = fn.getFirstChild().getNext().getFirstChild().getJSDocInfo(); assertNotNull(info); assertTypeEquals(STRING_TYPE, info.getType()); } public void testInlineJSDocAttachment2() { Node fn = parse( "function f(/**\n" + " * {string}\n" + " */ x) {}").getFirstChild(); assertTrue(fn.isFunction()); JSDocInfo info = fn.getFirstChild().getNext().getFirstChild().getJSDocInfo(); assertNotNull(info); assertTypeEquals(STRING_TYPE, info.getType()); } public void testInlineJSDocAttachment3() { parse( "function f(/** @type {string} */ x) {}", "Bad type annotation. type not recognized due to syntax error"); } public void testInlineJSDocAttachment4() { parse( "function f(/**\n" + " * @type {string}\n" + " */ x) {}", "Bad type annotation. type not recognized due to syntax error"); } public void testIncorrectJSDocDoesNotAlterJSParsing1() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type Array.<number*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing2() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type {Array.<number}*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing3() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {Array.<number} nums */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing4() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @return boolean */" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing5() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param boolean this is some string*/" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing6() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {bool!*%E$} */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "Bad type annotation. expected closing }", "Bad type annotation. expecting a variable name in a @param tag")); } public void testIncorrectJSDocDoesNotAlterJSParsing7() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @see */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@see tag missing description")); } public void testIncorrectJSDocDoesNotAlterJSParsing8() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @author */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@author tag missing author")); } public void testIncorrectJSDocDoesNotAlterJSParsing9() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @someillegaltag */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "illegal use of unknown JSDoc tag \"someillegaltag\";" + " ignoring it")); } public void testUnescapedSlashInRegexpCharClass() throws Exception { // The tokenizer without the fix for this bug throws an error. parse("var foo = /[/]/;"); parse("var foo = /[hi there/]/;"); parse("var foo = /[/yo dude]/;"); parse("var foo = /\\/[@#$/watashi/wa/suteevu/desu]/;"); } private void assertNodeEquality(Node expected, Node found) { String message = expected.checkTreeEquals(found); if (message != null) { fail(message); } } @SuppressWarnings("unchecked") public void testParse() { Node a = Node.newString(Token.NAME, "a"); a.addChildToFront(Node.newString(Token.NAME, "b")); List<ParserResult> testCases = ImmutableList.of( new ParserResult( "3;", createScript(new Node(Token.EXPR_RESULT, Node.newNumber(3.0)))), new ParserResult( "var a = b;", createScript(new Node(Token.VAR, a))), new ParserResult( "\"hell\\\no\\ world\\\n\\\n!\"", createScript(new Node(Token.EXPR_RESULT, Node.newString(Token.STRING, "hello world!"))))); for (ParserResult testCase : testCases) { assertNodeEquality(testCase.node, parse(testCase.code)); } } private Node createScript(Node n) { Node script = new Node(Token.SCRIPT); script.addChildToBack(n); return script; } public void testTrailingCommaWarning1() { parse("var a = ['foo', 'bar'];"); } public void testTrailingCommaWarning2() { parse("var a = ['foo',,'bar'];"); } public void testTrailingCommaWarning3() { parse("var a = ['foo', 'bar',];", TRAILING_COMMA_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var a = ['foo', 'bar',];"); } public void testTrailingCommaWarning4() { parse("var a = [,];", TRAILING_COMMA_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var a = [,];"); } public void testTrailingCommaWarning5() { parse("var a = {'foo': 'bar'};"); } public void testTrailingCommaWarning6() { parse("var a = {'foo': 'bar',};", TRAILING_COMMA_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var a = {'foo': 'bar',};"); } public void testTrailingCommaWarning7() { parseError("var a = {,};", BAD_PROPERTY_MESSAGE); } public void testSuspiciousBlockCommentWarning1() { parse("/* @type {number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning2() { parse("/* \n * @type {number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning3() { parse("/* \n *@type {number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning4() { parse( " /*\n" + " * @type {number}\n" + " */\n" + " var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning5() { parse( " /*\n" + " * some random text here\n" + " * @type {number}\n" + " */\n" + " var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning6() { parse("/* @type{number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testCatchClauseForbidden() { parseError("try { } catch (e if true) {}", "Catch clauses are not supported"); } public void testConstForbidden() { parseError("const x = 3;", "Unsupported syntax: CONST"); } public void testDestructuringAssignForbidden() { parseError("var [x, y] = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden2() { parseError("var {x, y} = foo();", "missing : after property id"); } public void testDestructuringAssignForbidden3() { parseError("var {x: x, y: y} = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden4() { parseError("[x, y] = foo();", "destructuring assignment forbidden", "invalid assignment target"); } public void testLetForbidden() { parseError("function f() { let (x = 3) { alert(x); }; }", "missing ; before statement", "syntax error"); } public void testYieldForbidden() { parseError("function f() { yield 3; }", "missing ; before statement"); } public void testBracelessFunctionForbidden() { parseError("var sq = function(x) x * x;", "missing { before function body"); } public void testGeneratorsForbidden() { parseError("var i = (x for (x in obj));", "Unsupported syntax: GENEXPR"); } public void testGettersForbidden1() { parseError("var x = {get foo() { return 3; }};", IRFactory.GETTER_ERROR_MESSAGE); } public void testGettersForbidden2() { parseError("var x = {get foo bar() { return 3; }};", "invalid property id"); } public void testGettersForbidden3() { parseError("var x = {a getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden4() { parseError("var x = {\"a\" getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden5() { parseError("var x = {a: 2, get foo() { return 3; }};", IRFactory.GETTER_ERROR_MESSAGE); } public void testSettersForbidden() { parseError("var x = {set foo() { return 3; }};", IRFactory.SETTER_ERROR_MESSAGE); } public void testSettersForbidden2() { parseError("var x = {a setter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testFileOverviewJSDoc1() { Node n = parse("/** @fileoverview Hi mom! */ function Foo() {}"); assertEquals(Token.FUNCTION, n.getFirstChild().getType()); assertTrue(n.getJSDocInfo() != null); assertNull(n.getFirstChild().getJSDocInfo()); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); } public void testFileOverviewJSDocDoesNotHoseParsing() { assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n * * * */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x \n */ function Foo() {}") .getFirstChild().getType()); } public void testFileOverviewJSDoc2() { Node n = parse("/** @fileoverview Hi mom! */ " + "/** @constructor */ function Foo() {}"); assertTrue(n.getJSDocInfo() != null); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo() != null); assertFalse(n.getFirstChild().getJSDocInfo().hasFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo().isConstructor()); } public void testObjectLiteralDoc1() { Node n = parse("var x = {/** @type {number} */ 1: 2};"); Node objectLit = n.getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLit.getType()); Node number = objectLit.getFirstChild(); assertEquals(Token.STRING_KEY, number.getType()); assertNotNull(number.getJSDocInfo()); } public void testDuplicatedParam() { parse("function foo(x, x) {}", "Duplicate parameter name \"x\"."); } public void testGetter() { mode = LanguageMode.ECMASCRIPT3; parseError("var x = {get 1(){}};", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get 'a'(){}};", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get a(){}};", IRFactory.GETTER_ERROR_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var x = {get 1(){}};"); parse("var x = {get 'a'(){}};"); parse("var x = {get a(){}};"); parseError("var x = {get a(b){}};", "getters may not have parameters"); } public void testSetter() { mode = LanguageMode.ECMASCRIPT3; parseError("var x = {set 1(x){}};", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set 'a'(x){}};", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set a(x){}};", IRFactory.SETTER_ERROR_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var x = {set 1(x){}};"); parse("var x = {set 'a'(x){}};"); parse("var x = {set a(x){}};"); parseError("var x = {set a(){}};", "setters must have exactly one parameter"); } public void testLamestWarningEver() { // This used to be a warning. parse("var x = /** @type {undefined} */ (y);"); parse("var x = /** @type {void} */ (y);"); } public void testUnfinishedComment() { parseError("/** this is a comment ", "unterminated comment"); } public void testParseBlockDescription() { Node n = parse("/** This is a variable. */ var x;"); Node var = n.getFirstChild(); assertNotNull(var.getJSDocInfo()); assertEquals("This is a variable.", var.getJSDocInfo().getBlockDescription()); } public void testUnnamedFunctionStatement() { // Statements parseError("function() {};", "unnamed function statement"); parseError("if (true) { function() {}; }", "unnamed function statement"); parse("function f() {};"); // Expressions parse("(function f() {});"); parse("(function () {});"); } public void testReservedKeywords() { mode = LanguageMode.ECMASCRIPT3; parseError("var boolean;", "identifier is a reserved word"); parseError("function boolean() {};", "identifier is a reserved word"); parseError("boolean = 1;", "identifier is a reserved word"); parseError("class = 1;", "identifier is a reserved word"); parseError("public = 2;", "identifier is a reserved word"); mode = LanguageMode.ECMASCRIPT5; parse("var boolean;"); parse("function boolean() {};"); parse("boolean = 1;"); parseError("class = 1;", "identifier is a reserved word"); parse("public = 2;"); mode = LanguageMode.ECMASCRIPT5_STRICT; parse("var boolean;"); parse("function boolean() {};"); parse("boolean = 1;"); parseError("class = 1;", "identifier is a reserved word"); parseError("public = 2;", "identifier is a reserved word"); } public void testKeywordsAsProperties() { mode = LanguageMode.ECMASCRIPT3; parse("var x = {function: 1};", IRFactory.INVALID_ES3_PROP_NAME); parse("x.function;", IRFactory.INVALID_ES3_PROP_NAME); parseError("var x = {get x(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get function(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get 'function'(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get 1(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {set function(a){} };", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set 'function'(a){} };", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set 1(a){} };", IRFactory.SETTER_ERROR_MESSAGE); parse("var x = {class: 1};", IRFactory.INVALID_ES3_PROP_NAME); parse("var x = {'class': 1};"); parse("x.class;", IRFactory.INVALID_ES3_PROP_NAME); parse("x['class'];"); parse("var x = {let: 1};"); // 'let' is not reserved in ES3 parse("x.let;"); parse("var x = {yield: 1};"); // 'yield' is not reserved in ES3 parse("x.yield;"); mode = LanguageMode.ECMASCRIPT5; parse("var x = {function: 1};"); parse("x.function;"); parse("var x = {get function(){} };"); parse("var x = {get 'function'(){} };"); parse("var x = {get 1(){} };"); parse("var x = {set function(a){} };"); parse("var x = {set 'function'(a){} };"); parse("var x = {set 1(a){} };"); parse("var x = {class: 1};"); parse("x.class;"); parse("var x = {let: 1};"); parse("x.let;"); parse("var x = {yield: 1};"); parse("x.yield;"); mode = LanguageMode.ECMASCRIPT5_STRICT; parse("var x = {function: 1};"); parse("x.function;"); parse("var x = {get function(){} };"); parse("var x = {get 'function'(){} };"); parse("var x = {get 1(){} };"); parse("var x = {set function(a){} };"); parse("var x = {set 'function'(a){} };"); parse("var x = {set 1(a){} };"); parse("var x = {class: 1};"); parse("x.class;"); parse("var x = {let: 1};"); parse("x.let;"); parse("var x = {yield: 1};"); parse("x.yield;"); } public void testGetPropFunctionName() { parseError("function a.b() {}", "missing ( before function parameters."); parseError("var x = function a.b() {}", "missing ( before function parameters."); } public void testGetPropFunctionNameIdeMode() { // In IDE mode, we try to fix up the tree, but sometimes // this leads to even more errors. isIdeMode = true; parseError("function a.b() {}", "missing ( before function parameters.", "missing formal parameter", "missing ) after formal parameters", "missing { before function body", "syntax error", "missing ; before statement", "missing ; before statement", "missing } after function body", "Unsupported syntax: ERROR", "Unsupported syntax: ERROR"); parseError("var x = function a.b() {}", "missing ( before function parameters.", "missing formal parameter", "missing ) after formal parameters", "missing { before function body", "syntax error", "missing ; before statement", "missing ; before statement", "missing } after function body", "Unsupported syntax: ERROR", "Unsupported syntax: ERROR"); } public void testIdeModePartialTree() { Node partialTree = parseError("function Foo() {} f.", "missing name after . operator"); assertNull(partialTree); isIdeMode = true; partialTree = parseError("function Foo() {} f.", "missing name after . operator"); assertNotNull(partialTree); } public void testForEach() { parseError( "function f(stamp, status) {\n" + " for each ( var curTiming in this.timeLog.timings ) {\n" + " if ( curTiming.callId == stamp ) {\n" + " curTiming.flag = status;\n" + " break;\n" + " }\n" + " }\n" + "};", "unsupported language extension: for each"); } public void testMisplacedTypeAnnotation1() { // misuse with COMMA parse( "var o = {};" + "/** @type {string} */ o.prop1 = 1, o.prop2 = 2;", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation2() { // missing parentheses for the cast. parse( "var o = /** @type {string} */ getValue();", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation3() { // missing parentheses for the cast. parse( "var o = 1 + /** @type {string} */ value;", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation4() { // missing parentheses for the cast. parse( "var o = /** @type {!Array.<string>} */ ['hello', 'you'];", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation5() { // missing parentheses for the cast. parse( "var o = (/** @type {!Foo} */ {});", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation6() { parse("var o = /** @type {function():string} */ function() {return 'str';}", MISPLACED_TYPE_ANNOTATION); } public void testValidTypeAnnotation1() { parse("/** @type {string} */ var o = 'str';"); parse("var /** @type {string} */ o = 'str', /** @type {number} */ p = 0;"); parse("/** @type {function():string} */ function o() { return 'str'; }"); parse("var o = {}; /** @type {string} */ o.prop = 'str';"); parse("var o = {}; /** @type {string} */ o['prop'] = 'str';"); parse("var o = { /** @type {string} */ prop : 'str' };"); parse("var o = { /** @type {string} */ 'prop' : 'str' };"); parse("var o = { /** @type {string} */ 1 : 'str' };"); } public void testValidTypeAnnotation2() { mode = LanguageMode.ECMASCRIPT5; parse("var o = { /** @type {string} */ get prop() { return 'str' }};"); parse("var o = { /** @type {string} */ set prop(s) {}};"); } public void testValidTypeAnnotation3() { // This one we don't currently support in the type checker but // we would like to. parse("try {} catch (/** @type {Error} */ e) {}"); } /** * Verify that the given code has the given parse errors. * @return If in IDE mode, returns a partial tree. */ private Node parseError(String string, String... errors) { TestErrorReporter testErrorReporter = new TestErrorReporter(errors, null); Node script = null; try { StaticSourceFile file = new SimpleSourceFile("input", false); script = ParserRunner.parse( file, string, ParserRunner.createConfig(isIdeMode, mode, false), testErrorReporter, Logger.getAnonymousLogger()).ast; } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } private Node parse(String string, String... warnings) { TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings); Node script = null; try { StaticSourceFile file = new SimpleSourceFile("input", false); script = ParserRunner.parse( file, string, ParserRunner.createConfig(true, mode, false), testErrorReporter, Logger.getAnonymousLogger()).ast; } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } private static class ParserResult { private final String code; private final Node node; private ParserResult(String code, Node node) { this.code = code; this.node = node; } } }
// You are a professional Java test case writer, please create a test case named `testSuspiciousBlockCommentWarning3` for the issue `Closure-1037`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1037 // // ## Issue-Title: // Inconsistent handling of non-JSDoc comments // // ## Issue-Description: // **What steps will reproduce the problem?** // **1.** // **2.** // **3.** // **What is the expected output? What do you see instead?** // // When given: // // /\* @preserve Foo License \*/ // alert("foo"); // // It spits out: // // stdin:1: WARNING - Parse error. Non-JSDoc comment has annotations. Did you mean to start it with '/\*\*'? // /\* @license Foo License \*/ // ^ // // 0 error(s), 1 warning(s) // alert("foo"); // // If I take the suggestion and change the opening of the comment to '/\*\*', everything is great. However, if I change it to '/\*!', the warning goes away, but it doesn't preserve the comment either. // // I expect it to print the above warning, or preserve the comment. That it does neither when starting with "/\*!" (and every other character I tried) is confusing. // // **What version of the product are you using? On what operating system?** // // Tested with my compilation of the "v20130603" tag: // // Closure Compiler (http://code.google.com/closure/compiler) // Version: v20130603 // Built on: 2013/07/07 15:04 // // And with the provided binary: // // Closure Compiler (http://code.google.com/closure/compiler) // Version: v20130411-90-g4e19b4e // Built on: 2013/06/03 12:07 // // I'm on Parabola GNU/Linux-libre with Java: // // java version "1.7.0\_40" // OpenJDK Runtime Environment (IcedTea 2.4.0) (ArchLinux build 7.u40\_2.4.0-1-i686) // OpenJDK Server VM (build 24.0-b40, mixed mode) // // **Please provide any additional information below.** // // public void testSuspiciousBlockCommentWarning3() {
695
122
693
test/com/google/javascript/jscomp/parsing/ParserTest.java
test
```markdown ## Issue-ID: Closure-1037 ## Issue-Title: Inconsistent handling of non-JSDoc comments ## Issue-Description: **What steps will reproduce the problem?** **1.** **2.** **3.** **What is the expected output? What do you see instead?** When given: /\* @preserve Foo License \*/ alert("foo"); It spits out: stdin:1: WARNING - Parse error. Non-JSDoc comment has annotations. Did you mean to start it with '/\*\*'? /\* @license Foo License \*/ ^ 0 error(s), 1 warning(s) alert("foo"); If I take the suggestion and change the opening of the comment to '/\*\*', everything is great. However, if I change it to '/\*!', the warning goes away, but it doesn't preserve the comment either. I expect it to print the above warning, or preserve the comment. That it does neither when starting with "/\*!" (and every other character I tried) is confusing. **What version of the product are you using? On what operating system?** Tested with my compilation of the "v20130603" tag: Closure Compiler (http://code.google.com/closure/compiler) Version: v20130603 Built on: 2013/07/07 15:04 And with the provided binary: Closure Compiler (http://code.google.com/closure/compiler) Version: v20130411-90-g4e19b4e Built on: 2013/06/03 12:07 I'm on Parabola GNU/Linux-libre with Java: java version "1.7.0\_40" OpenJDK Runtime Environment (IcedTea 2.4.0) (ArchLinux build 7.u40\_2.4.0-1-i686) OpenJDK Server VM (build 24.0-b40, mixed mode) **Please provide any additional information below.** ``` You are a professional Java test case writer, please create a test case named `testSuspiciousBlockCommentWarning3` for the issue `Closure-1037`, utilizing the provided issue report information and the following function signature. ```java public void testSuspiciousBlockCommentWarning3() { ```
693
[ "com.google.javascript.jscomp.parsing.IRFactory" ]
b7f731abbcea67c4e478eeb04ce33cedf1668427321c1d6b8022a8529117edcd
public void testSuspiciousBlockCommentWarning3()
// You are a professional Java test case writer, please create a test case named `testSuspiciousBlockCommentWarning3` for the issue `Closure-1037`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1037 // // ## Issue-Title: // Inconsistent handling of non-JSDoc comments // // ## Issue-Description: // **What steps will reproduce the problem?** // **1.** // **2.** // **3.** // **What is the expected output? What do you see instead?** // // When given: // // /\* @preserve Foo License \*/ // alert("foo"); // // It spits out: // // stdin:1: WARNING - Parse error. Non-JSDoc comment has annotations. Did you mean to start it with '/\*\*'? // /\* @license Foo License \*/ // ^ // // 0 error(s), 1 warning(s) // alert("foo"); // // If I take the suggestion and change the opening of the comment to '/\*\*', everything is great. However, if I change it to '/\*!', the warning goes away, but it doesn't preserve the comment either. // // I expect it to print the above warning, or preserve the comment. That it does neither when starting with "/\*!" (and every other character I tried) is confusing. // // **What version of the product are you using? On what operating system?** // // Tested with my compilation of the "v20130603" tag: // // Closure Compiler (http://code.google.com/closure/compiler) // Version: v20130603 // Built on: 2013/07/07 15:04 // // And with the provided binary: // // Closure Compiler (http://code.google.com/closure/compiler) // Version: v20130411-90-g4e19b4e // Built on: 2013/06/03 12:07 // // I'm on Parabola GNU/Linux-libre with Java: // // java version "1.7.0\_40" // OpenJDK Runtime Environment (IcedTea 2.4.0) (ArchLinux build 7.u40\_2.4.0-1-i686) // OpenJDK Server VM (build 24.0-b40, mixed mode) // // **Please provide any additional information below.** // //
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.javascript.jscomp.parsing.Config.LanguageMode; import com.google.javascript.jscomp.testing.TestErrorReporter; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.head.ScriptRuntime; import com.google.javascript.rhino.jstype.SimpleSourceFile; import com.google.javascript.rhino.jstype.StaticSourceFile; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import java.io.IOException; import java.util.List; import java.util.logging.Logger; public class ParserTest extends BaseJSTypeTestCase { private static final String SUSPICIOUS_COMMENT_WARNING = IRFactory.SUSPICIOUS_COMMENT_WARNING; private static final String TRAILING_COMMA_MESSAGE = ScriptRuntime.getMessage0("msg.extra.trailing.comma"); private static final String BAD_PROPERTY_MESSAGE = ScriptRuntime.getMessage0("msg.bad.prop"); private static final String MISSING_GT_MESSAGE = "Bad type annotation. " + com.google.javascript.rhino.SimpleErrorReporter.getMessage0( "msg.jsdoc.missing.gt"); private static final String MISPLACED_TYPE_ANNOTATION = IRFactory.MISPLACED_TYPE_ANNOTATION; private Config.LanguageMode mode; private boolean isIdeMode = false; @Override protected void setUp() throws Exception { super.setUp(); mode = LanguageMode.ECMASCRIPT3; isIdeMode = false; } public void testLinenoCharnoAssign1() throws Exception { Node assign = parse("a = b").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(1, assign.getLineno()); assertEquals(0, assign.getCharno()); } public void testLinenoCharnoAssign2() throws Exception { Node assign = parse("\n a.g.h.k = 45").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assign.getType()); assertEquals(2, assign.getLineno()); assertEquals(1, assign.getCharno()); } public void testLinenoCharnoCall() throws Exception { Node call = parse("\n foo(123);").getFirstChild().getFirstChild(); assertEquals(Token.CALL, call.getType()); assertEquals(2, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetProp1() throws Exception { Node getprop = parse("\n foo.bar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(2, name.getLineno()); assertEquals(5, name.getCharno()); } public void testLinenoCharnoGetProp2() throws Exception { Node getprop = parse("\n foo.\nbar").getFirstChild().getFirstChild(); assertEquals(Token.GETPROP, getprop.getType()); assertEquals(2, getprop.getLineno()); assertEquals(1, getprop.getCharno()); Node name = getprop.getFirstChild().getNext(); assertEquals(Token.STRING, name.getType()); assertEquals(3, name.getLineno()); assertEquals(0, name.getCharno()); } public void testLinenoCharnoGetelem1() throws Exception { Node call = parse("\n foo[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(2, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem2() throws Exception { Node call = parse("\n \n foo()[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoGetelem3() throws Exception { Node call = parse("\n \n (8 + kl)[123]").getFirstChild().getFirstChild(); assertEquals(Token.GETELEM, call.getType()); assertEquals(3, call.getLineno()); assertEquals(1, call.getCharno()); } public void testLinenoCharnoForComparison() throws Exception { Node lt = parse("for (; i < j;){}").getFirstChild().getFirstChild().getNext(); assertEquals(Token.LT, lt.getType()); assertEquals(1, lt.getLineno()); assertEquals(7, lt.getCharno()); } public void testLinenoCharnoHook() throws Exception { Node n = parse("\n a ? 9 : 0").getFirstChild().getFirstChild(); assertEquals(Token.HOOK, n.getType()); assertEquals(2, n.getLineno()); assertEquals(1, n.getCharno()); } public void testLinenoCharnoArrayLiteral() throws Exception { Node n = parse("\n [8, 9]").getFirstChild().getFirstChild(); assertEquals(Token.ARRAYLIT, n.getType()); assertEquals(2, n.getLineno()); assertEquals(2, n.getCharno()); n = n.getFirstChild(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(3, n.getCharno()); n = n.getNext(); assertEquals(Token.NUMBER, n.getType()); assertEquals(2, n.getLineno()); assertEquals(6, n.getCharno()); } public void testLinenoCharnoObjectLiteral() throws Exception { Node n = parse("\n\n var a = {a:0\n,b :1};") .getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, n.getType()); assertEquals(3, n.getLineno()); assertEquals(9, n.getCharno()); Node key = n.getFirstChild(); assertEquals(Token.STRING_KEY, key.getType()); assertEquals(3, key.getLineno()); assertEquals(10, key.getCharno()); Node value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(3, value.getLineno()); assertEquals(12, value.getCharno()); key = key.getNext(); assertEquals(Token.STRING_KEY, key.getType()); assertEquals(4, key.getLineno()); assertEquals(1, key.getCharno()); value = key.getFirstChild(); assertEquals(Token.NUMBER, value.getType()); assertEquals(4, value.getLineno()); assertEquals(4, value.getCharno()); } public void testLinenoCharnoAdd() throws Exception { testLinenoCharnoBinop("+"); } public void testLinenoCharnoSub() throws Exception { testLinenoCharnoBinop("-"); } public void testLinenoCharnoMul() throws Exception { testLinenoCharnoBinop("*"); } public void testLinenoCharnoDiv() throws Exception { testLinenoCharnoBinop("/"); } public void testLinenoCharnoMod() throws Exception { testLinenoCharnoBinop("%"); } public void testLinenoCharnoShift() throws Exception { testLinenoCharnoBinop("<<"); } public void testLinenoCharnoBinaryAnd() throws Exception { testLinenoCharnoBinop("&"); } public void testLinenoCharnoAnd() throws Exception { testLinenoCharnoBinop("&&"); } public void testLinenoCharnoBinaryOr() throws Exception { testLinenoCharnoBinop("|"); } public void testLinenoCharnoOr() throws Exception { testLinenoCharnoBinop("||"); } public void testLinenoCharnoLt() throws Exception { testLinenoCharnoBinop("<"); } public void testLinenoCharnoLe() throws Exception { testLinenoCharnoBinop("<="); } public void testLinenoCharnoGt() throws Exception { testLinenoCharnoBinop(">"); } public void testLinenoCharnoGe() throws Exception { testLinenoCharnoBinop(">="); } private void testLinenoCharnoBinop(String binop) { Node op = parse("var a = 89 " + binop + " 76").getFirstChild(). getFirstChild().getFirstChild(); assertEquals(1, op.getLineno()); assertEquals(8, op.getCharno()); } public void testJSDocAttachment1() { Node varNode = parse("/** @type number */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment2() { Node varNode = parse("/** @type number */var a,b;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); // First NAME Node nameNode1 = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode1.getType()); assertNull(nameNode1.getJSDocInfo()); // Second NAME Node nameNode2 = nameNode1.getNext(); assertEquals(Token.NAME, nameNode2.getType()); assertNull(nameNode2.getJSDocInfo()); } public void testJSDocAttachment3() { Node assignNode = parse( "/** @type number */goog.FOO = 5;").getFirstChild().getFirstChild(); assertEquals(Token.ASSIGN, assignNode.getType()); JSDocInfo info = assignNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment4() { Node varNode = parse( "var a, /** @define {number} */ b = 5;").getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNull(a.getJSDocInfo()); // b Node b = a.getNext(); JSDocInfo info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } public void testJSDocAttachment5() { Node varNode = parse( "var /** @type number */a, /** @define {number} */b = 5;") .getFirstChild(); // ASSIGN assertEquals(Token.VAR, varNode.getType()); assertNull(varNode.getJSDocInfo()); // a Node a = varNode.getFirstChild(); assertNotNull(a.getJSDocInfo()); JSDocInfo info = a.getJSDocInfo(); assertNotNull(info); assertFalse(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); // b Node b = a.getNext(); info = b.getJSDocInfo(); assertNotNull(info); assertTrue(info.isDefine()); assertTypeEquals(NUMBER_TYPE, info.getType()); } /** * Tests that a JSDoc comment in an unexpected place of the code does not * propagate to following code due to {@link JSDocInfo} aggregation. */ public void testJSDocAttachment6() throws Exception { Node functionNode = parse( "var a = /** @param {number} index */5;" + "/** @return boolean */function f(index){}") .getFirstChild().getNext(); assertEquals(Token.FUNCTION, functionNode.getType()); JSDocInfo info = functionNode.getJSDocInfo(); assertNotNull(info); assertFalse(info.hasParameter("index")); assertTrue(info.hasReturnType()); assertTypeEquals(UNKNOWN_TYPE, info.getReturnType()); } public void testJSDocAttachment7() { Node varNode = parse("/** */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment8() { Node varNode = parse("/** x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment9() { Node varNode = parse("/** \n x */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment10() { Node varNode = parse("/** x\n */var a;").getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment11() { Node varNode = parse("/** @type {{x : number, 'y' : string, z}} */var a;") .getFirstChild(); // VAR assertEquals(Token.VAR, varNode.getType()); JSDocInfo info = varNode.getJSDocInfo(); assertNotNull(info); assertTypeEquals(createRecordTypeBuilder(). addProperty("x", NUMBER_TYPE, null). addProperty("y", STRING_TYPE, null). addProperty("z", UNKNOWN_TYPE, null). build(), info.getType()); // NAME Node nameNode = varNode.getFirstChild(); assertEquals(Token.NAME, nameNode.getType()); assertNull(nameNode.getJSDocInfo()); } public void testJSDocAttachment12() { Node varNode = parse("var a = {/** @type {Object} */ b: c};") .getFirstChild(); Node objectLitNode = varNode.getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLitNode.getType()); assertNotNull(objectLitNode.getFirstChild().getJSDocInfo()); } public void testJSDocAttachment13() { Node varNode = parse("/** foo */ var a;").getFirstChild(); assertNotNull(varNode.getJSDocInfo()); } public void testJSDocAttachment14() { Node varNode = parse("/** */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testJSDocAttachment15() { Node varNode = parse("/** \n * \n */ var a;").getFirstChild(); assertNull(varNode.getJSDocInfo()); } public void testJSDocAttachment16() { Node exprCall = parse("/** @private */ x(); function f() {};").getFirstChild(); assertEquals(Token.EXPR_RESULT, exprCall.getType()); assertNull(exprCall.getNext().getJSDocInfo()); assertNotNull(exprCall.getFirstChild().getJSDocInfo()); } public void testJSDocAttachment17() { Node fn = parse( "function f() { " + " return /** @type {string} */ (g(1 /** @desc x */));" + "};").getFirstChild(); assertEquals(Token.FUNCTION, fn.getType()); Node cast = fn.getLastChild().getFirstChild().getFirstChild(); assertEquals(Token.CAST, cast.getType()); } public void testJSDocAttachment18() { Node fn = parse( "function f() { " + " var x = /** @type {string} */ (y);" + "};").getFirstChild(); assertEquals(Token.FUNCTION, fn.getType()); Node cast = fn.getLastChild().getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.CAST, cast.getType()); } public void testInlineJSDocAttachment1() { Node fn = parse("function f(/** string */ x) {}").getFirstChild(); assertTrue(fn.isFunction()); JSDocInfo info = fn.getFirstChild().getNext().getFirstChild().getJSDocInfo(); assertNotNull(info); assertTypeEquals(STRING_TYPE, info.getType()); } public void testInlineJSDocAttachment2() { Node fn = parse( "function f(/**\n" + " * {string}\n" + " */ x) {}").getFirstChild(); assertTrue(fn.isFunction()); JSDocInfo info = fn.getFirstChild().getNext().getFirstChild().getJSDocInfo(); assertNotNull(info); assertTypeEquals(STRING_TYPE, info.getType()); } public void testInlineJSDocAttachment3() { parse( "function f(/** @type {string} */ x) {}", "Bad type annotation. type not recognized due to syntax error"); } public void testInlineJSDocAttachment4() { parse( "function f(/**\n" + " * @type {string}\n" + " */ x) {}", "Bad type annotation. type not recognized due to syntax error"); } public void testIncorrectJSDocDoesNotAlterJSParsing1() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type Array.<number*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing2() throws Exception { assertNodeEquality( parse("var a = [1,2]"), parse("/** @type {Array.<number}*/var a = [1,2]", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing3() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {Array.<number} nums */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", MISSING_GT_MESSAGE)); } public void testIncorrectJSDocDoesNotAlterJSParsing4() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @return boolean */" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing5() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param boolean this is some string*/" + "C.prototype.say=function(nums) {alert(nums.join(','));};")); } public void testIncorrectJSDocDoesNotAlterJSParsing6() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @param {bool!*%E$} */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "Bad type annotation. expected closing }", "Bad type annotation. expecting a variable name in a @param tag")); } public void testIncorrectJSDocDoesNotAlterJSParsing7() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @see */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@see tag missing description")); } public void testIncorrectJSDocDoesNotAlterJSParsing8() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @author */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "@author tag missing author")); } public void testIncorrectJSDocDoesNotAlterJSParsing9() throws Exception { assertNodeEquality( parse("C.prototype.say=function(nums) {alert(nums.join(','));};"), parse("/** @someillegaltag */" + "C.prototype.say=function(nums) {alert(nums.join(','));};", "illegal use of unknown JSDoc tag \"someillegaltag\";" + " ignoring it")); } public void testUnescapedSlashInRegexpCharClass() throws Exception { // The tokenizer without the fix for this bug throws an error. parse("var foo = /[/]/;"); parse("var foo = /[hi there/]/;"); parse("var foo = /[/yo dude]/;"); parse("var foo = /\\/[@#$/watashi/wa/suteevu/desu]/;"); } private void assertNodeEquality(Node expected, Node found) { String message = expected.checkTreeEquals(found); if (message != null) { fail(message); } } @SuppressWarnings("unchecked") public void testParse() { Node a = Node.newString(Token.NAME, "a"); a.addChildToFront(Node.newString(Token.NAME, "b")); List<ParserResult> testCases = ImmutableList.of( new ParserResult( "3;", createScript(new Node(Token.EXPR_RESULT, Node.newNumber(3.0)))), new ParserResult( "var a = b;", createScript(new Node(Token.VAR, a))), new ParserResult( "\"hell\\\no\\ world\\\n\\\n!\"", createScript(new Node(Token.EXPR_RESULT, Node.newString(Token.STRING, "hello world!"))))); for (ParserResult testCase : testCases) { assertNodeEquality(testCase.node, parse(testCase.code)); } } private Node createScript(Node n) { Node script = new Node(Token.SCRIPT); script.addChildToBack(n); return script; } public void testTrailingCommaWarning1() { parse("var a = ['foo', 'bar'];"); } public void testTrailingCommaWarning2() { parse("var a = ['foo',,'bar'];"); } public void testTrailingCommaWarning3() { parse("var a = ['foo', 'bar',];", TRAILING_COMMA_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var a = ['foo', 'bar',];"); } public void testTrailingCommaWarning4() { parse("var a = [,];", TRAILING_COMMA_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var a = [,];"); } public void testTrailingCommaWarning5() { parse("var a = {'foo': 'bar'};"); } public void testTrailingCommaWarning6() { parse("var a = {'foo': 'bar',};", TRAILING_COMMA_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var a = {'foo': 'bar',};"); } public void testTrailingCommaWarning7() { parseError("var a = {,};", BAD_PROPERTY_MESSAGE); } public void testSuspiciousBlockCommentWarning1() { parse("/* @type {number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning2() { parse("/* \n * @type {number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning3() { parse("/* \n *@type {number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning4() { parse( " /*\n" + " * @type {number}\n" + " */\n" + " var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning5() { parse( " /*\n" + " * some random text here\n" + " * @type {number}\n" + " */\n" + " var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testSuspiciousBlockCommentWarning6() { parse("/* @type{number} */ var x = 3;", SUSPICIOUS_COMMENT_WARNING); } public void testCatchClauseForbidden() { parseError("try { } catch (e if true) {}", "Catch clauses are not supported"); } public void testConstForbidden() { parseError("const x = 3;", "Unsupported syntax: CONST"); } public void testDestructuringAssignForbidden() { parseError("var [x, y] = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden2() { parseError("var {x, y} = foo();", "missing : after property id"); } public void testDestructuringAssignForbidden3() { parseError("var {x: x, y: y} = foo();", "destructuring assignment forbidden"); } public void testDestructuringAssignForbidden4() { parseError("[x, y] = foo();", "destructuring assignment forbidden", "invalid assignment target"); } public void testLetForbidden() { parseError("function f() { let (x = 3) { alert(x); }; }", "missing ; before statement", "syntax error"); } public void testYieldForbidden() { parseError("function f() { yield 3; }", "missing ; before statement"); } public void testBracelessFunctionForbidden() { parseError("var sq = function(x) x * x;", "missing { before function body"); } public void testGeneratorsForbidden() { parseError("var i = (x for (x in obj));", "Unsupported syntax: GENEXPR"); } public void testGettersForbidden1() { parseError("var x = {get foo() { return 3; }};", IRFactory.GETTER_ERROR_MESSAGE); } public void testGettersForbidden2() { parseError("var x = {get foo bar() { return 3; }};", "invalid property id"); } public void testGettersForbidden3() { parseError("var x = {a getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden4() { parseError("var x = {\"a\" getter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testGettersForbidden5() { parseError("var x = {a: 2, get foo() { return 3; }};", IRFactory.GETTER_ERROR_MESSAGE); } public void testSettersForbidden() { parseError("var x = {set foo() { return 3; }};", IRFactory.SETTER_ERROR_MESSAGE); } public void testSettersForbidden2() { parseError("var x = {a setter:function b() { return 3; }};", "missing : after property id", "syntax error"); } public void testFileOverviewJSDoc1() { Node n = parse("/** @fileoverview Hi mom! */ function Foo() {}"); assertEquals(Token.FUNCTION, n.getFirstChild().getType()); assertTrue(n.getJSDocInfo() != null); assertNull(n.getFirstChild().getJSDocInfo()); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); } public void testFileOverviewJSDocDoesNotHoseParsing() { assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview Hi mom! \n * * * */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x */ function Foo() {}") .getFirstChild().getType()); assertEquals( Token.FUNCTION, parse("/** @fileoverview \n * x \n */ function Foo() {}") .getFirstChild().getType()); } public void testFileOverviewJSDoc2() { Node n = parse("/** @fileoverview Hi mom! */ " + "/** @constructor */ function Foo() {}"); assertTrue(n.getJSDocInfo() != null); assertEquals("Hi mom!", n.getJSDocInfo().getFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo() != null); assertFalse(n.getFirstChild().getJSDocInfo().hasFileOverview()); assertTrue(n.getFirstChild().getJSDocInfo().isConstructor()); } public void testObjectLiteralDoc1() { Node n = parse("var x = {/** @type {number} */ 1: 2};"); Node objectLit = n.getFirstChild().getFirstChild().getFirstChild(); assertEquals(Token.OBJECTLIT, objectLit.getType()); Node number = objectLit.getFirstChild(); assertEquals(Token.STRING_KEY, number.getType()); assertNotNull(number.getJSDocInfo()); } public void testDuplicatedParam() { parse("function foo(x, x) {}", "Duplicate parameter name \"x\"."); } public void testGetter() { mode = LanguageMode.ECMASCRIPT3; parseError("var x = {get 1(){}};", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get 'a'(){}};", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get a(){}};", IRFactory.GETTER_ERROR_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var x = {get 1(){}};"); parse("var x = {get 'a'(){}};"); parse("var x = {get a(){}};"); parseError("var x = {get a(b){}};", "getters may not have parameters"); } public void testSetter() { mode = LanguageMode.ECMASCRIPT3; parseError("var x = {set 1(x){}};", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set 'a'(x){}};", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set a(x){}};", IRFactory.SETTER_ERROR_MESSAGE); mode = LanguageMode.ECMASCRIPT5; parse("var x = {set 1(x){}};"); parse("var x = {set 'a'(x){}};"); parse("var x = {set a(x){}};"); parseError("var x = {set a(){}};", "setters must have exactly one parameter"); } public void testLamestWarningEver() { // This used to be a warning. parse("var x = /** @type {undefined} */ (y);"); parse("var x = /** @type {void} */ (y);"); } public void testUnfinishedComment() { parseError("/** this is a comment ", "unterminated comment"); } public void testParseBlockDescription() { Node n = parse("/** This is a variable. */ var x;"); Node var = n.getFirstChild(); assertNotNull(var.getJSDocInfo()); assertEquals("This is a variable.", var.getJSDocInfo().getBlockDescription()); } public void testUnnamedFunctionStatement() { // Statements parseError("function() {};", "unnamed function statement"); parseError("if (true) { function() {}; }", "unnamed function statement"); parse("function f() {};"); // Expressions parse("(function f() {});"); parse("(function () {});"); } public void testReservedKeywords() { mode = LanguageMode.ECMASCRIPT3; parseError("var boolean;", "identifier is a reserved word"); parseError("function boolean() {};", "identifier is a reserved word"); parseError("boolean = 1;", "identifier is a reserved word"); parseError("class = 1;", "identifier is a reserved word"); parseError("public = 2;", "identifier is a reserved word"); mode = LanguageMode.ECMASCRIPT5; parse("var boolean;"); parse("function boolean() {};"); parse("boolean = 1;"); parseError("class = 1;", "identifier is a reserved word"); parse("public = 2;"); mode = LanguageMode.ECMASCRIPT5_STRICT; parse("var boolean;"); parse("function boolean() {};"); parse("boolean = 1;"); parseError("class = 1;", "identifier is a reserved word"); parseError("public = 2;", "identifier is a reserved word"); } public void testKeywordsAsProperties() { mode = LanguageMode.ECMASCRIPT3; parse("var x = {function: 1};", IRFactory.INVALID_ES3_PROP_NAME); parse("x.function;", IRFactory.INVALID_ES3_PROP_NAME); parseError("var x = {get x(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get function(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get 'function'(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {get 1(){} };", IRFactory.GETTER_ERROR_MESSAGE); parseError("var x = {set function(a){} };", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set 'function'(a){} };", IRFactory.SETTER_ERROR_MESSAGE); parseError("var x = {set 1(a){} };", IRFactory.SETTER_ERROR_MESSAGE); parse("var x = {class: 1};", IRFactory.INVALID_ES3_PROP_NAME); parse("var x = {'class': 1};"); parse("x.class;", IRFactory.INVALID_ES3_PROP_NAME); parse("x['class'];"); parse("var x = {let: 1};"); // 'let' is not reserved in ES3 parse("x.let;"); parse("var x = {yield: 1};"); // 'yield' is not reserved in ES3 parse("x.yield;"); mode = LanguageMode.ECMASCRIPT5; parse("var x = {function: 1};"); parse("x.function;"); parse("var x = {get function(){} };"); parse("var x = {get 'function'(){} };"); parse("var x = {get 1(){} };"); parse("var x = {set function(a){} };"); parse("var x = {set 'function'(a){} };"); parse("var x = {set 1(a){} };"); parse("var x = {class: 1};"); parse("x.class;"); parse("var x = {let: 1};"); parse("x.let;"); parse("var x = {yield: 1};"); parse("x.yield;"); mode = LanguageMode.ECMASCRIPT5_STRICT; parse("var x = {function: 1};"); parse("x.function;"); parse("var x = {get function(){} };"); parse("var x = {get 'function'(){} };"); parse("var x = {get 1(){} };"); parse("var x = {set function(a){} };"); parse("var x = {set 'function'(a){} };"); parse("var x = {set 1(a){} };"); parse("var x = {class: 1};"); parse("x.class;"); parse("var x = {let: 1};"); parse("x.let;"); parse("var x = {yield: 1};"); parse("x.yield;"); } public void testGetPropFunctionName() { parseError("function a.b() {}", "missing ( before function parameters."); parseError("var x = function a.b() {}", "missing ( before function parameters."); } public void testGetPropFunctionNameIdeMode() { // In IDE mode, we try to fix up the tree, but sometimes // this leads to even more errors. isIdeMode = true; parseError("function a.b() {}", "missing ( before function parameters.", "missing formal parameter", "missing ) after formal parameters", "missing { before function body", "syntax error", "missing ; before statement", "missing ; before statement", "missing } after function body", "Unsupported syntax: ERROR", "Unsupported syntax: ERROR"); parseError("var x = function a.b() {}", "missing ( before function parameters.", "missing formal parameter", "missing ) after formal parameters", "missing { before function body", "syntax error", "missing ; before statement", "missing ; before statement", "missing } after function body", "Unsupported syntax: ERROR", "Unsupported syntax: ERROR"); } public void testIdeModePartialTree() { Node partialTree = parseError("function Foo() {} f.", "missing name after . operator"); assertNull(partialTree); isIdeMode = true; partialTree = parseError("function Foo() {} f.", "missing name after . operator"); assertNotNull(partialTree); } public void testForEach() { parseError( "function f(stamp, status) {\n" + " for each ( var curTiming in this.timeLog.timings ) {\n" + " if ( curTiming.callId == stamp ) {\n" + " curTiming.flag = status;\n" + " break;\n" + " }\n" + " }\n" + "};", "unsupported language extension: for each"); } public void testMisplacedTypeAnnotation1() { // misuse with COMMA parse( "var o = {};" + "/** @type {string} */ o.prop1 = 1, o.prop2 = 2;", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation2() { // missing parentheses for the cast. parse( "var o = /** @type {string} */ getValue();", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation3() { // missing parentheses for the cast. parse( "var o = 1 + /** @type {string} */ value;", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation4() { // missing parentheses for the cast. parse( "var o = /** @type {!Array.<string>} */ ['hello', 'you'];", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation5() { // missing parentheses for the cast. parse( "var o = (/** @type {!Foo} */ {});", MISPLACED_TYPE_ANNOTATION); } public void testMisplacedTypeAnnotation6() { parse("var o = /** @type {function():string} */ function() {return 'str';}", MISPLACED_TYPE_ANNOTATION); } public void testValidTypeAnnotation1() { parse("/** @type {string} */ var o = 'str';"); parse("var /** @type {string} */ o = 'str', /** @type {number} */ p = 0;"); parse("/** @type {function():string} */ function o() { return 'str'; }"); parse("var o = {}; /** @type {string} */ o.prop = 'str';"); parse("var o = {}; /** @type {string} */ o['prop'] = 'str';"); parse("var o = { /** @type {string} */ prop : 'str' };"); parse("var o = { /** @type {string} */ 'prop' : 'str' };"); parse("var o = { /** @type {string} */ 1 : 'str' };"); } public void testValidTypeAnnotation2() { mode = LanguageMode.ECMASCRIPT5; parse("var o = { /** @type {string} */ get prop() { return 'str' }};"); parse("var o = { /** @type {string} */ set prop(s) {}};"); } public void testValidTypeAnnotation3() { // This one we don't currently support in the type checker but // we would like to. parse("try {} catch (/** @type {Error} */ e) {}"); } /** * Verify that the given code has the given parse errors. * @return If in IDE mode, returns a partial tree. */ private Node parseError(String string, String... errors) { TestErrorReporter testErrorReporter = new TestErrorReporter(errors, null); Node script = null; try { StaticSourceFile file = new SimpleSourceFile("input", false); script = ParserRunner.parse( file, string, ParserRunner.createConfig(isIdeMode, mode, false), testErrorReporter, Logger.getAnonymousLogger()).ast; } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } private Node parse(String string, String... warnings) { TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings); Node script = null; try { StaticSourceFile file = new SimpleSourceFile("input", false); script = ParserRunner.parse( file, string, ParserRunner.createConfig(true, mode, false), testErrorReporter, Logger.getAnonymousLogger()).ast; } catch (IOException e) { throw new RuntimeException(e); } // verifying that all warnings were seen assertTrue(testErrorReporter.hasEncounteredAllErrors()); assertTrue(testErrorReporter.hasEncounteredAllWarnings()); return script; } private static class ParserResult { private final String code; private final Node node; private ParserResult(String code, Node node) { this.code = code; this.node = node; } } }
public void testArrayEquals() { assertFalse(MathUtils.equals(new double[] { 1d }, null)); assertFalse(MathUtils.equals(null, new double[] { 1d })); assertTrue(MathUtils.equals((double[]) null, (double[]) null)); assertFalse(MathUtils.equals(new double[] { 1d }, new double[0])); assertTrue(MathUtils.equals(new double[] { 1d }, new double[] { 1d })); assertTrue(MathUtils.equals(new double[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }, new double[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d })); assertFalse(MathUtils.equals(new double[] { Double.NaN }, new double[] { Double.NaN })); assertFalse(MathUtils.equals(new double[] { Double.POSITIVE_INFINITY }, new double[] { Double.NEGATIVE_INFINITY })); assertFalse(MathUtils.equals(new double[] { 1d }, new double[] { FastMath.nextAfter(FastMath.nextAfter(1d, 2d), 2d) })); }
org.apache.commons.math.util.MathUtilsTest::testArrayEquals
src/test/java/org/apache/commons/math/util/MathUtilsTest.java
462
src/test/java/org/apache/commons/math/util/MathUtilsTest.java
testArrayEquals
/* * 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 java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.math.TestUtils; import org.apache.commons.math.exception.NonMonotonousSequenceException; import org.apache.commons.math.random.RandomDataImpl; /** * Test cases for the MathUtils class. * @version $Revision$ $Date: 2007-08-16 15:36:33 -0500 (Thu, 16 Aug * 2007) $ */ public final class MathUtilsTest extends TestCase { public MathUtilsTest(String name) { super(name); } /** cached binomial coefficients */ private static final List<Map<Integer, Long>> binomialCache = new ArrayList<Map<Integer, Long>>(); /** * Exact (caching) recursive implementation to test against */ private long binomialCoefficient(int n, int k) throws ArithmeticException { if (binomialCache.size() > n) { Long cachedResult = binomialCache.get(n).get(Integer.valueOf(k)); if (cachedResult != null) { return cachedResult.longValue(); } } long result = -1; if ((n == k) || (k == 0)) { result = 1; } else if ((k == 1) || (k == n - 1)) { result = n; } else { // Reduce stack depth for larger values of n if (k < n - 100) { binomialCoefficient(n - 100, k); } if (k > 100) { binomialCoefficient(n - 100, k - 100); } result = MathUtils.addAndCheck(binomialCoefficient(n - 1, k - 1), binomialCoefficient(n - 1, k)); } if (result == -1) { throw new ArithmeticException( "error computing binomial coefficient"); } for (int i = binomialCache.size(); i < n + 1; i++) { binomialCache.add(new HashMap<Integer, Long>()); } binomialCache.get(n).put(Integer.valueOf(k), Long.valueOf(result)); return result; } /** * Exact direct multiplication implementation to test against */ private long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } /** Verify that b(0,0) = 1 */ public void test0Choose0() { assertEquals(MathUtils.binomialCoefficientDouble(0, 0), 1d, 0); assertEquals(MathUtils.binomialCoefficientLog(0, 0), 0d, 0); assertEquals(MathUtils.binomialCoefficient(0, 0), 1); } public void testAddAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; assertEquals(big, MathUtils.addAndCheck(big, 0)); try { MathUtils.addAndCheck(big, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } try { MathUtils.addAndCheck(bigNeg, -1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } } public void testAddAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; assertEquals(max, MathUtils.addAndCheck(max, 0L)); assertEquals(min, MathUtils.addAndCheck(min, 0L)); assertEquals(max, MathUtils.addAndCheck(0L, max)); assertEquals(min, MathUtils.addAndCheck(0L, min)); assertEquals(1, MathUtils.addAndCheck(-1L, 2L)); assertEquals(1, MathUtils.addAndCheck(2L, -1L)); assertEquals(-3, MathUtils.addAndCheck(-2L, -1L)); assertEquals(min, MathUtils.addAndCheck(min + 1, -1L)); testAddAndCheckLongFailure(max, 1L); testAddAndCheckLongFailure(min, -1L); testAddAndCheckLongFailure(1L, max); testAddAndCheckLongFailure(-1L, min); } private void testAddAndCheckLongFailure(long a, long b) { try { MathUtils.addAndCheck(a, b); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // success } } public void testBinomialCoefficient() { long[] bcoef5 = { 1, 5, 10, 10, 5, 1 }; long[] bcoef6 = { 1, 6, 15, 20, 15, 6, 1 }; for (int i = 0; i < 6; i++) { assertEquals("5 choose " + i, bcoef5[i], MathUtils.binomialCoefficient(5, i)); } for (int i = 0; i < 7; i++) { assertEquals("6 choose " + i, bcoef6[i], MathUtils.binomialCoefficient(6, i)); } for (int n = 1; n < 10; n++) { for (int k = 0; k <= n; k++) { assertEquals(n + " choose " + k, binomialCoefficient(n, k), MathUtils.binomialCoefficient(n, k)); assertEquals(n + " choose " + k, binomialCoefficient(n, k), MathUtils.binomialCoefficientDouble(n, k), Double.MIN_VALUE); assertEquals(n + " choose " + k, FastMath.log(binomialCoefficient(n, k)), MathUtils.binomialCoefficientLog(n, k), 10E-12); } } int[] n = { 34, 66, 100, 1500, 1500 }; int[] k = { 17, 33, 10, 1500 - 4, 4 }; for (int i = 0; i < n.length; i++) { long expected = binomialCoefficient(n[i], k[i]); assertEquals(n[i] + " choose " + k[i], expected, MathUtils.binomialCoefficient(n[i], k[i])); assertEquals(n[i] + " choose " + k[i], expected, MathUtils.binomialCoefficientDouble(n[i], k[i]), 0.0); assertEquals("log(" + n[i] + " choose " + k[i] + ")", FastMath.log(expected), MathUtils.binomialCoefficientLog(n[i], k[i]), 0.0); } } /** * Tests correctness for large n and sharpness of upper bound in API doc * JIRA: MATH-241 */ public void testBinomialCoefficientLarge() throws Exception { // This tests all legal and illegal values for n <= 200. for (int n = 0; n <= 200; n++) { for (int k = 0; k <= n; k++) { long ourResult = -1; long exactResult = -1; boolean shouldThrow = false; boolean didThrow = false; try { ourResult = MathUtils.binomialCoefficient(n, k); } catch (ArithmeticException ex) { didThrow = true; } try { exactResult = binomialCoefficient(n, k); } catch (ArithmeticException ex) { shouldThrow = true; } assertEquals(n + " choose " + k, exactResult, ourResult); assertEquals(n + " choose " + k, shouldThrow, didThrow); assertTrue(n + " choose " + k, (n > 66 || !didThrow)); if (!shouldThrow && exactResult > 1) { assertEquals(n + " choose " + k, 1., MathUtils.binomialCoefficientDouble(n, k) / exactResult, 1e-10); assertEquals(n + " choose " + k, 1, MathUtils.binomialCoefficientLog(n, k) / FastMath.log(exactResult), 1e-10); } } } long ourResult = MathUtils.binomialCoefficient(300, 3); long exactResult = binomialCoefficient(300, 3); assertEquals(exactResult, ourResult); ourResult = MathUtils.binomialCoefficient(700, 697); exactResult = binomialCoefficient(700, 697); assertEquals(exactResult, ourResult); // This one should throw try { MathUtils.binomialCoefficient(700, 300); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // Expected } int n = 10000; ourResult = MathUtils.binomialCoefficient(n, 3); exactResult = binomialCoefficient(n, 3); assertEquals(exactResult, ourResult); assertEquals(1, MathUtils.binomialCoefficientDouble(n, 3) / exactResult, 1e-10); assertEquals(1, MathUtils.binomialCoefficientLog(n, 3) / FastMath.log(exactResult), 1e-10); } public void testBinomialCoefficientFail() { try { MathUtils.binomialCoefficient(4, 5); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientDouble(4, 5); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientLog(4, 5); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficient(-1, -2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientDouble(-1, -2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientLog(-1, -2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficient(67, 30); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // ignored } try { MathUtils.binomialCoefficient(67, 34); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // ignored } double x = MathUtils.binomialCoefficientDouble(1030, 515); assertTrue("expecting infinite binomial coefficient", Double .isInfinite(x)); } public void testCompareTo() { assertEquals(0, MathUtils.compareTo(152.33, 152.32, .011)); assertTrue(MathUtils.compareTo(152.308, 152.32, .011) < 0); assertTrue(MathUtils.compareTo(152.33, 152.318, .011) > 0); } public void testCosh() { double x = 3.0; double expected = 10.06766; assertEquals(expected, MathUtils.cosh(x), 1.0e-5); } public void testCoshNaN() { assertTrue(Double.isNaN(MathUtils.cosh(Double.NaN))); } public void testEqualsIncludingNaN() { double[] testArray = { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }; for (int i = 0; i < testArray.length; i++) { for (int j = 0; j < testArray.length; j++) { if (i == j) { assertTrue(MathUtils.equalsIncludingNaN(testArray[i], testArray[j])); assertTrue(MathUtils.equalsIncludingNaN(testArray[j], testArray[i])); } else { assertTrue(!MathUtils.equalsIncludingNaN(testArray[i], testArray[j])); assertTrue(!MathUtils.equalsIncludingNaN(testArray[j], testArray[i])); } } } } public void testEqualsWithAllowedDelta() { assertTrue(MathUtils.equals(153.0000, 153.0000, .0625)); assertTrue(MathUtils.equals(153.0000, 153.0625, .0625)); assertTrue(MathUtils.equals(152.9375, 153.0000, .0625)); assertFalse(MathUtils.equals(Double.NaN, Double.NaN, 1.0)); assertTrue(MathUtils.equals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertTrue(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1.0)); assertFalse(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertFalse(MathUtils.equals(153.0000, 153.0625, .0624)); assertFalse(MathUtils.equals(152.9374, 153.0000, .0625)); } public void testEqualsIncludingNaNWithAllowedDelta() { assertTrue(MathUtils.equalsIncludingNaN(153.0000, 153.0000, .0625)); assertTrue(MathUtils.equalsIncludingNaN(153.0000, 153.0625, .0625)); assertTrue(MathUtils.equalsIncludingNaN(152.9375, 153.0000, .0625)); assertTrue(MathUtils.equalsIncludingNaN(Double.NaN, Double.NaN, 1.0)); assertTrue(MathUtils.equalsIncludingNaN(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertTrue(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1.0)); assertFalse(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertFalse(MathUtils.equalsIncludingNaN(153.0000, 153.0625, .0624)); assertFalse(MathUtils.equalsIncludingNaN(152.9374, 153.0000, .0625)); } public void testEqualsWithAllowedUlps() { assertTrue(MathUtils.equals(0.0, -0.0, 1)); assertTrue(MathUtils.equals(1.0, 1 + FastMath.ulp(1d), 1)); assertFalse(MathUtils.equals(1.0, 1 + 2 * FastMath.ulp(1d), 1)); final double nUp1 = FastMath.nextAfter(1d, Double.POSITIVE_INFINITY); final double nnUp1 = FastMath.nextAfter(nUp1, Double.POSITIVE_INFINITY); assertTrue(MathUtils.equals(1.0, nUp1, 1)); assertTrue(MathUtils.equals(nUp1, nnUp1, 1)); assertFalse(MathUtils.equals(1.0, nnUp1, 1)); assertTrue(MathUtils.equals(0.0, FastMath.ulp(0d), 1)); assertTrue(MathUtils.equals(0.0, -FastMath.ulp(0d), 1)); assertTrue(MathUtils.equals(153.0, 153.0, 1)); assertTrue(MathUtils.equals(153.0, 153.00000000000003, 1)); assertFalse(MathUtils.equals(153.0, 153.00000000000006, 1)); assertTrue(MathUtils.equals(153.0, 152.99999999999997, 1)); assertFalse(MathUtils.equals(153, 152.99999999999994, 1)); assertTrue(MathUtils.equals(-128.0, -127.99999999999999, 1)); assertFalse(MathUtils.equals(-128.0, -127.99999999999997, 1)); assertTrue(MathUtils.equals(-128.0, -128.00000000000003, 1)); assertFalse(MathUtils.equals(-128.0, -128.00000000000006, 1)); assertTrue(MathUtils.equals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equals(Double.MAX_VALUE, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); assertTrue(MathUtils.equals(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY, 1)); assertFalse(MathUtils.equals(Double.NaN, Double.NaN, 1)); assertFalse(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 100000)); } public void testEqualsIncludingNaNWithAllowedUlps() { assertTrue(MathUtils.equalsIncludingNaN(0.0, -0.0, 1)); assertTrue(MathUtils.equalsIncludingNaN(1.0, 1 + FastMath.ulp(1d), 1)); assertFalse(MathUtils.equalsIncludingNaN(1.0, 1 + 2 * FastMath.ulp(1d), 1)); final double nUp1 = FastMath.nextAfter(1d, Double.POSITIVE_INFINITY); final double nnUp1 = FastMath.nextAfter(nUp1, Double.POSITIVE_INFINITY); assertTrue(MathUtils.equalsIncludingNaN(1.0, nUp1, 1)); assertTrue(MathUtils.equalsIncludingNaN(nUp1, nnUp1, 1)); assertFalse(MathUtils.equalsIncludingNaN(1.0, nnUp1, 1)); assertTrue(MathUtils.equalsIncludingNaN(0.0, FastMath.ulp(0d), 1)); assertTrue(MathUtils.equalsIncludingNaN(0.0, -FastMath.ulp(0d), 1)); assertTrue(MathUtils.equalsIncludingNaN(153.0, 153.0, 1)); assertTrue(MathUtils.equalsIncludingNaN(153.0, 153.00000000000003, 1)); assertFalse(MathUtils.equalsIncludingNaN(153.0, 153.00000000000006, 1)); assertTrue(MathUtils.equalsIncludingNaN(153.0, 152.99999999999997, 1)); assertFalse(MathUtils.equalsIncludingNaN(153, 152.99999999999994, 1)); assertTrue(MathUtils.equalsIncludingNaN(-128.0, -127.99999999999999, 1)); assertFalse(MathUtils.equalsIncludingNaN(-128.0, -127.99999999999997, 1)); assertTrue(MathUtils.equalsIncludingNaN(-128.0, -128.00000000000003, 1)); assertFalse(MathUtils.equalsIncludingNaN(-128.0, -128.00000000000006, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.MAX_VALUE, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.NaN, Double.NaN, 1)); assertFalse(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 100000)); } /** * @deprecated To be removed in release 3.0 (replaced by {@link * #testArrayEqualsIncludingNaN()}. */ public void testArrayEquals() { assertFalse(MathUtils.equals(new double[] { 1d }, null)); assertFalse(MathUtils.equals(null, new double[] { 1d })); assertTrue(MathUtils.equals((double[]) null, (double[]) null)); assertFalse(MathUtils.equals(new double[] { 1d }, new double[0])); assertTrue(MathUtils.equals(new double[] { 1d }, new double[] { 1d })); assertTrue(MathUtils.equals(new double[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }, new double[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d })); assertFalse(MathUtils.equals(new double[] { Double.NaN }, new double[] { Double.NaN })); assertFalse(MathUtils.equals(new double[] { Double.POSITIVE_INFINITY }, new double[] { Double.NEGATIVE_INFINITY })); assertFalse(MathUtils.equals(new double[] { 1d }, new double[] { FastMath.nextAfter(FastMath.nextAfter(1d, 2d), 2d) })); } public void testArrayEqualsIncludingNaN() { assertFalse(MathUtils.equalsIncludingNaN(new double[] { 1d }, null)); assertFalse(MathUtils.equalsIncludingNaN(null, new double[] { 1d })); assertTrue(MathUtils.equalsIncludingNaN((double[]) null, (double[]) null)); assertFalse(MathUtils.equalsIncludingNaN(new double[] { 1d }, new double[0])); assertTrue(MathUtils.equalsIncludingNaN(new double[] { 1d }, new double[] { 1d })); assertTrue(MathUtils.equalsIncludingNaN(new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }, new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d })); assertFalse(MathUtils.equalsIncludingNaN(new double[] { Double.POSITIVE_INFINITY }, new double[] { Double.NEGATIVE_INFINITY })); assertFalse(MathUtils.equalsIncludingNaN(new double[] { 1d }, new double[] { FastMath.nextAfter(FastMath.nextAfter(1d, 2d), 2d) })); } public void testFactorial() { for (int i = 1; i < 21; i++) { assertEquals(i + "! ", factorial(i), MathUtils.factorial(i)); assertEquals(i + "! ", factorial(i), MathUtils.factorialDouble(i), Double.MIN_VALUE); assertEquals(i + "! ", FastMath.log(factorial(i)), MathUtils.factorialLog(i), 10E-12); } assertEquals("0", 1, MathUtils.factorial(0)); assertEquals("0", 1.0d, MathUtils.factorialDouble(0), 1E-14); assertEquals("0", 0.0d, MathUtils.factorialLog(0), 1E-14); } public void testFactorialFail() { try { MathUtils.factorial(-1); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.factorialDouble(-1); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.factorialLog(-1); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.factorial(21); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // ignored } assertTrue("expecting infinite factorial value", Double.isInfinite(MathUtils.factorialDouble(171))); } public void testGcd() { int a = 30; int b = 50; int c = 77; assertEquals(0, MathUtils.gcd(0, 0)); assertEquals(b, MathUtils.gcd(0, b)); assertEquals(a, MathUtils.gcd(a, 0)); assertEquals(b, MathUtils.gcd(0, -b)); assertEquals(a, MathUtils.gcd(-a, 0)); assertEquals(10, MathUtils.gcd(a, b)); assertEquals(10, MathUtils.gcd(-a, b)); assertEquals(10, MathUtils.gcd(a, -b)); assertEquals(10, MathUtils.gcd(-a, -b)); assertEquals(1, MathUtils.gcd(a, c)); assertEquals(1, MathUtils.gcd(-a, c)); assertEquals(1, MathUtils.gcd(a, -c)); assertEquals(1, MathUtils.gcd(-a, -c)); assertEquals(3 * (1<<15), MathUtils.gcd(3 * (1<<20), 9 * (1<<15))); assertEquals(Integer.MAX_VALUE, MathUtils.gcd(Integer.MAX_VALUE, 0)); assertEquals(Integer.MAX_VALUE, MathUtils.gcd(-Integer.MAX_VALUE, 0)); assertEquals(1<<30, MathUtils.gcd(1<<30, -Integer.MIN_VALUE)); try { // gcd(Integer.MIN_VALUE, 0) > Integer.MAX_VALUE MathUtils.gcd(Integer.MIN_VALUE, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(0, Integer.MIN_VALUE) > Integer.MAX_VALUE MathUtils.gcd(0, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(Integer.MIN_VALUE, Integer.MIN_VALUE) > Integer.MAX_VALUE MathUtils.gcd(Integer.MIN_VALUE, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testGcdLong(){ long a = 30; long b = 50; long c = 77; assertEquals(0, MathUtils.gcd(0L, 0)); assertEquals(b, MathUtils.gcd(0, b)); assertEquals(a, MathUtils.gcd(a, 0)); assertEquals(b, MathUtils.gcd(0, -b)); assertEquals(a, MathUtils.gcd(-a, 0)); assertEquals(10, MathUtils.gcd(a, b)); assertEquals(10, MathUtils.gcd(-a, b)); assertEquals(10, MathUtils.gcd(a, -b)); assertEquals(10, MathUtils.gcd(-a, -b)); assertEquals(1, MathUtils.gcd(a, c)); assertEquals(1, MathUtils.gcd(-a, c)); assertEquals(1, MathUtils.gcd(a, -c)); assertEquals(1, MathUtils.gcd(-a, -c)); assertEquals(3L * (1L<<45), MathUtils.gcd(3L * (1L<<50), 9L * (1L<<45))); assertEquals(1L<<45, MathUtils.gcd(1L<<45, Long.MIN_VALUE)); assertEquals(Long.MAX_VALUE, MathUtils.gcd(Long.MAX_VALUE, 0L)); assertEquals(Long.MAX_VALUE, MathUtils.gcd(-Long.MAX_VALUE, 0L)); assertEquals(1, MathUtils.gcd(60247241209L, 153092023L)); try { // gcd(Long.MIN_VALUE, 0) > Long.MAX_VALUE MathUtils.gcd(Long.MIN_VALUE, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(0, Long.MIN_VALUE) > Long.MAX_VALUE MathUtils.gcd(0, Long.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(Long.MIN_VALUE, Long.MIN_VALUE) > Long.MAX_VALUE MathUtils.gcd(Long.MIN_VALUE, Long.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testGcdConsistency() { int[] primeList = {19, 23, 53, 67, 73, 79, 101, 103, 111, 131}; ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 0; i < primeList.length; i++) { primes.add(Integer.valueOf(primeList[i])); } RandomDataImpl randomData = new RandomDataImpl(); for (int i = 0; i < 20; i++) { Object[] sample = randomData.nextSample(primes, 4); int p1 = ((Integer) sample[0]).intValue(); int p2 = ((Integer) sample[1]).intValue(); int p3 = ((Integer) sample[2]).intValue(); int p4 = ((Integer) sample[3]).intValue(); int i1 = p1 * p2 * p3; int i2 = p1 * p2 * p4; int gcd = p1 * p2; assertEquals(gcd, MathUtils.gcd(i1, i2)); long l1 = i1; long l2 = i2; assertEquals(gcd, MathUtils.gcd(l1, l2)); } } public void testHash() { double[] testArray = { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d, 1E-14, (1 + 1E-14), Double.MIN_VALUE, Double.MAX_VALUE }; for (int i = 0; i < testArray.length; i++) { for (int j = 0; j < testArray.length; j++) { if (i == j) { assertEquals(MathUtils.hash(testArray[i]), MathUtils.hash(testArray[j])); assertEquals(MathUtils.hash(testArray[j]), MathUtils.hash(testArray[i])); } else { assertTrue(MathUtils.hash(testArray[i]) != MathUtils.hash(testArray[j])); assertTrue(MathUtils.hash(testArray[j]) != MathUtils.hash(testArray[i])); } } } } public void testArrayHash() { assertEquals(0, MathUtils.hash((double[]) null)); assertEquals(MathUtils.hash(new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }), MathUtils.hash(new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d })); assertFalse(MathUtils.hash(new double[] { 1d }) == MathUtils.hash(new double[] { FastMath.nextAfter(1d, 2d) })); assertFalse(MathUtils.hash(new double[] { 1d }) == MathUtils.hash(new double[] { 1d, 1d })); } /** * Make sure that permuted arrays do not hash to the same value. */ public void testPermutedArrayHash() { double[] original = new double[10]; double[] permuted = new double[10]; RandomDataImpl random = new RandomDataImpl(); // Generate 10 distinct random values for (int i = 0; i < 10; i++) { original[i] = random.nextUniform(i + 0.5, i + 0.75); } // Generate a random permutation, making sure it is not the identity boolean isIdentity = true; do { int[] permutation = random.nextPermutation(10, 10); for (int i = 0; i < 10; i++) { if (i != permutation[i]) { isIdentity = false; } permuted[i] = original[permutation[i]]; } } while (isIdentity); // Verify that permuted array has different hash assertFalse(MathUtils.hash(original) == MathUtils.hash(permuted)); } public void testIndicatorByte() { assertEquals((byte)1, MathUtils.indicator((byte)2)); assertEquals((byte)1, MathUtils.indicator((byte)0)); assertEquals((byte)(-1), MathUtils.indicator((byte)(-2))); } public void testIndicatorDouble() { double delta = 0.0; assertEquals(1.0, MathUtils.indicator(2.0), delta); assertEquals(1.0, MathUtils.indicator(0.0), delta); assertEquals(-1.0, MathUtils.indicator(-2.0), delta); assertEquals(Double.NaN, MathUtils.indicator(Double.NaN)); } public void testIndicatorFloat() { float delta = 0.0F; assertEquals(1.0F, MathUtils.indicator(2.0F), delta); assertEquals(1.0F, MathUtils.indicator(0.0F), delta); assertEquals(-1.0F, MathUtils.indicator(-2.0F), delta); } public void testIndicatorInt() { assertEquals(1, MathUtils.indicator((2))); assertEquals(1, MathUtils.indicator((0))); assertEquals((-1), MathUtils.indicator((-2))); } public void testIndicatorLong() { assertEquals(1L, MathUtils.indicator(2L)); assertEquals(1L, MathUtils.indicator(0L)); assertEquals(-1L, MathUtils.indicator(-2L)); } public void testIndicatorShort() { assertEquals((short)1, MathUtils.indicator((short)2)); assertEquals((short)1, MathUtils.indicator((short)0)); assertEquals((short)(-1), MathUtils.indicator((short)(-2))); } public void testLcm() { int a = 30; int b = 50; int c = 77; assertEquals(0, MathUtils.lcm(0, b)); assertEquals(0, MathUtils.lcm(a, 0)); assertEquals(b, MathUtils.lcm(1, b)); assertEquals(a, MathUtils.lcm(a, 1)); assertEquals(150, MathUtils.lcm(a, b)); assertEquals(150, MathUtils.lcm(-a, b)); assertEquals(150, MathUtils.lcm(a, -b)); assertEquals(150, MathUtils.lcm(-a, -b)); assertEquals(2310, MathUtils.lcm(a, c)); // Assert that no intermediate value overflows: // The naive implementation of lcm(a,b) would be (a*b)/gcd(a,b) assertEquals((1<<20)*15, MathUtils.lcm((1<<20)*3, (1<<20)*5)); // Special case assertEquals(0, MathUtils.lcm(0, 0)); try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Integer.MIN_VALUE, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Integer.MIN_VALUE, 1<<20); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { MathUtils.lcm(Integer.MAX_VALUE, Integer.MAX_VALUE - 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testLcmLong() { long a = 30; long b = 50; long c = 77; assertEquals(0, MathUtils.lcm(0, b)); assertEquals(0, MathUtils.lcm(a, 0)); assertEquals(b, MathUtils.lcm(1, b)); assertEquals(a, MathUtils.lcm(a, 1)); assertEquals(150, MathUtils.lcm(a, b)); assertEquals(150, MathUtils.lcm(-a, b)); assertEquals(150, MathUtils.lcm(a, -b)); assertEquals(150, MathUtils.lcm(-a, -b)); assertEquals(2310, MathUtils.lcm(a, c)); assertEquals(Long.MAX_VALUE, MathUtils.lcm(60247241209L, 153092023L)); // Assert that no intermediate value overflows: // The naive implementation of lcm(a,b) would be (a*b)/gcd(a,b) assertEquals((1L<<50)*15, MathUtils.lcm((1L<<45)*3, (1L<<50)*5)); // Special case assertEquals(0L, MathUtils.lcm(0L, 0L)); try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Long.MIN_VALUE, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Long.MIN_VALUE, 1<<20); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } assertEquals((long) Integer.MAX_VALUE * (Integer.MAX_VALUE - 1), MathUtils.lcm((long)Integer.MAX_VALUE, Integer.MAX_VALUE - 1)); try { MathUtils.lcm(Long.MAX_VALUE, Long.MAX_VALUE - 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testLog() { assertEquals(2.0, MathUtils.log(2, 4), 0); assertEquals(3.0, MathUtils.log(2, 8), 0); assertTrue(Double.isNaN(MathUtils.log(-1, 1))); assertTrue(Double.isNaN(MathUtils.log(1, -1))); assertTrue(Double.isNaN(MathUtils.log(0, 0))); assertEquals(0, MathUtils.log(0, 10), 0); assertEquals(Double.NEGATIVE_INFINITY, MathUtils.log(10, 0), 0); } public void testMulAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; assertEquals(big, MathUtils.mulAndCheck(big, 1)); try { MathUtils.mulAndCheck(big, 2); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } try { MathUtils.mulAndCheck(bigNeg, 2); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } } public void testMulAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; assertEquals(max, MathUtils.mulAndCheck(max, 1L)); assertEquals(min, MathUtils.mulAndCheck(min, 1L)); assertEquals(0L, MathUtils.mulAndCheck(max, 0L)); assertEquals(0L, MathUtils.mulAndCheck(min, 0L)); assertEquals(max, MathUtils.mulAndCheck(1L, max)); assertEquals(min, MathUtils.mulAndCheck(1L, min)); assertEquals(0L, MathUtils.mulAndCheck(0L, max)); assertEquals(0L, MathUtils.mulAndCheck(0L, min)); assertEquals(1L, MathUtils.mulAndCheck(-1L, -1L)); assertEquals(min, MathUtils.mulAndCheck(min / 2, 2)); testMulAndCheckLongFailure(max, 2L); testMulAndCheckLongFailure(2L, max); testMulAndCheckLongFailure(min, 2L); testMulAndCheckLongFailure(2L, min); testMulAndCheckLongFailure(min, -1L); testMulAndCheckLongFailure(-1L, min); } private void testMulAndCheckLongFailure(long a, long b) { try { MathUtils.mulAndCheck(a, b); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // success } } public void testNextAfter() { // 0x402fffffffffffff 0x404123456789abcd -> 4030000000000000 assertEquals(16.0, FastMath.nextAfter(15.999999999999998, 34.27555555555555), 0.0); // 0xc02fffffffffffff 0x404123456789abcd -> c02ffffffffffffe assertEquals(-15.999999999999996, FastMath.nextAfter(-15.999999999999998, 34.27555555555555), 0.0); // 0x402fffffffffffff 0x400123456789abcd -> 402ffffffffffffe assertEquals(15.999999999999996, FastMath.nextAfter(15.999999999999998, 2.142222222222222), 0.0); // 0xc02fffffffffffff 0x400123456789abcd -> c02ffffffffffffe assertEquals(-15.999999999999996, FastMath.nextAfter(-15.999999999999998, 2.142222222222222), 0.0); // 0x4020000000000000 0x404123456789abcd -> 4020000000000001 assertEquals(8.000000000000002, FastMath.nextAfter(8.0, 34.27555555555555), 0.0); // 0xc020000000000000 0x404123456789abcd -> c01fffffffffffff assertEquals(-7.999999999999999, FastMath.nextAfter(-8.0, 34.27555555555555), 0.0); // 0x4020000000000000 0x400123456789abcd -> 401fffffffffffff assertEquals(7.999999999999999, FastMath.nextAfter(8.0, 2.142222222222222), 0.0); // 0xc020000000000000 0x400123456789abcd -> c01fffffffffffff assertEquals(-7.999999999999999, FastMath.nextAfter(-8.0, 2.142222222222222), 0.0); // 0x3f2e43753d36a223 0x3f2e43753d36a224 -> 3f2e43753d36a224 assertEquals(2.308922399667661E-4, FastMath.nextAfter(2.3089223996676606E-4, 2.308922399667661E-4), 0.0); // 0x3f2e43753d36a223 0x3f2e43753d36a223 -> 3f2e43753d36a224 assertEquals(2.308922399667661E-4, FastMath.nextAfter(2.3089223996676606E-4, 2.3089223996676606E-4), 0.0); // 0x3f2e43753d36a223 0x3f2e43753d36a222 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, 2.3089223996676603E-4), 0.0); // 0x3f2e43753d36a223 0xbf2e43753d36a224 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, -2.308922399667661E-4), 0.0); // 0x3f2e43753d36a223 0xbf2e43753d36a223 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, -2.3089223996676606E-4), 0.0); // 0x3f2e43753d36a223 0xbf2e43753d36a222 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, -2.3089223996676603E-4), 0.0); // 0xbf2e43753d36a223 0x3f2e43753d36a224 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, 2.308922399667661E-4), 0.0); // 0xbf2e43753d36a223 0x3f2e43753d36a223 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, 2.3089223996676606E-4), 0.0); // 0xbf2e43753d36a223 0x3f2e43753d36a222 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, 2.3089223996676603E-4), 0.0); // 0xbf2e43753d36a223 0xbf2e43753d36a224 -> bf2e43753d36a224 assertEquals(-2.308922399667661E-4, FastMath.nextAfter(-2.3089223996676606E-4, -2.308922399667661E-4), 0.0); // 0xbf2e43753d36a223 0xbf2e43753d36a223 -> bf2e43753d36a224 assertEquals(-2.308922399667661E-4, FastMath.nextAfter(-2.3089223996676606E-4, -2.3089223996676606E-4), 0.0); // 0xbf2e43753d36a223 0xbf2e43753d36a222 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, -2.3089223996676603E-4), 0.0); } public void testNextAfterSpecialCases() { assertTrue(Double.isInfinite(FastMath.nextAfter(Double.NEGATIVE_INFINITY, 0))); assertTrue(Double.isInfinite(FastMath.nextAfter(Double.POSITIVE_INFINITY, 0))); assertTrue(Double.isNaN(FastMath.nextAfter(Double.NaN, 0))); assertTrue(Double.isInfinite(FastMath.nextAfter(Double.MAX_VALUE, Double.POSITIVE_INFINITY))); assertTrue(Double.isInfinite(FastMath.nextAfter(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY))); assertEquals(Double.MIN_VALUE, FastMath.nextAfter(0, 1), 0); assertEquals(-Double.MIN_VALUE, FastMath.nextAfter(0, -1), 0); assertEquals(0, FastMath.nextAfter(Double.MIN_VALUE, -1), 0); assertEquals(0, FastMath.nextAfter(-Double.MIN_VALUE, 1), 0); } public void testScalb() { assertEquals( 0.0, MathUtils.scalb(0.0, 5), 1.0e-15); assertEquals(32.0, MathUtils.scalb(1.0, 5), 1.0e-15); assertEquals(1.0 / 32.0, MathUtils.scalb(1.0, -5), 1.0e-15); assertEquals(FastMath.PI, MathUtils.scalb(FastMath.PI, 0), 1.0e-15); assertTrue(Double.isInfinite(MathUtils.scalb(Double.POSITIVE_INFINITY, 1))); assertTrue(Double.isInfinite(MathUtils.scalb(Double.NEGATIVE_INFINITY, 1))); assertTrue(Double.isNaN(MathUtils.scalb(Double.NaN, 1))); } public void testNormalizeAngle() { for (double a = -15.0; a <= 15.0; a += 0.1) { for (double b = -15.0; b <= 15.0; b += 0.2) { double c = MathUtils.normalizeAngle(a, b); assertTrue((b - FastMath.PI) <= c); assertTrue(c <= (b + FastMath.PI)); double twoK = FastMath.rint((a - c) / FastMath.PI); assertEquals(c, a - twoK * FastMath.PI, 1.0e-14); } } } public void testNormalizeArray() { double[] testValues1 = new double[] {1, 1, 2}; TestUtils.assertEquals( new double[] {.25, .25, .5}, MathUtils.normalizeArray(testValues1, 1), Double.MIN_VALUE); double[] testValues2 = new double[] {-1, -1, 1}; TestUtils.assertEquals( new double[] {1, 1, -1}, MathUtils.normalizeArray(testValues2, 1), Double.MIN_VALUE); // Ignore NaNs double[] testValues3 = new double[] {-1, -1, Double.NaN, 1, Double.NaN}; TestUtils.assertEquals( new double[] {1, 1,Double.NaN, -1, Double.NaN}, MathUtils.normalizeArray(testValues3, 1), Double.MIN_VALUE); // Zero sum -> ArithmeticException double[] zeroSum = new double[] {-1, 1}; try { MathUtils.normalizeArray(zeroSum, 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // Infinite elements -> ArithmeticException double[] hasInf = new double[] {1, 2, 1, Double.NEGATIVE_INFINITY}; try { MathUtils.normalizeArray(hasInf, 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // Infinite target -> IllegalArgumentException try { MathUtils.normalizeArray(testValues1, Double.POSITIVE_INFINITY); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // NaN target -> IllegalArgumentException try { MathUtils.normalizeArray(testValues1, Double.NaN); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testRoundDouble() { double x = 1.234567890; assertEquals(1.23, MathUtils.round(x, 2), 0.0); assertEquals(1.235, MathUtils.round(x, 3), 0.0); assertEquals(1.2346, MathUtils.round(x, 4), 0.0); // JIRA MATH-151 assertEquals(39.25, MathUtils.round(39.245, 2), 0.0); assertEquals(39.24, MathUtils.round(39.245, 2, BigDecimal.ROUND_DOWN), 0.0); double xx = 39.0; xx = xx + 245d / 1000d; assertEquals(39.25, MathUtils.round(xx, 2), 0.0); // BZ 35904 assertEquals(30.1d, MathUtils.round(30.095d, 2), 0.0d); assertEquals(30.1d, MathUtils.round(30.095d, 1), 0.0d); assertEquals(33.1d, MathUtils.round(33.095d, 1), 0.0d); assertEquals(33.1d, MathUtils.round(33.095d, 2), 0.0d); assertEquals(50.09d, MathUtils.round(50.085d, 2), 0.0d); assertEquals(50.19d, MathUtils.round(50.185d, 2), 0.0d); assertEquals(50.01d, MathUtils.round(50.005d, 2), 0.0d); assertEquals(30.01d, MathUtils.round(30.005d, 2), 0.0d); assertEquals(30.65d, MathUtils.round(30.645d, 2), 0.0d); assertEquals(1.24, MathUtils.round(x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.234, MathUtils.round(-x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.2345, MathUtils.round(-x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.234, MathUtils.round(x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.2345, MathUtils.round(x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.234, MathUtils.round(-x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.2345, MathUtils.round(-x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.234, MathUtils.round(x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.2345, MathUtils.round(x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.24, MathUtils.round(-x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.234, MathUtils.round(1.2345, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.234, MathUtils.round(-1.2345, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.234, MathUtils.round(1.2345, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.234, MathUtils.round(-1.2345, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.236, MathUtils.round(1.2355, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.236, MathUtils.round(-1.2355, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235, MathUtils.round(1.2345, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235, MathUtils.round(-1.2345, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23, MathUtils.round(-1.23, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); assertEquals(1.23, MathUtils.round(1.23, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); try { MathUtils.round(1.234, 2, BigDecimal.ROUND_UNNECESSARY); fail(); } catch (ArithmeticException ex) { // success } assertEquals(1.24, MathUtils.round(x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.24, MathUtils.round(-x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_UP), 0.0); try { MathUtils.round(1.234, 2, 1923); fail(); } catch (IllegalArgumentException ex) { // success } // MATH-151 assertEquals(39.25, MathUtils.round(39.245, 2, BigDecimal.ROUND_HALF_UP), 0.0); // special values TestUtils.assertEquals(Double.NaN, MathUtils.round(Double.NaN, 2), 0.0); assertEquals(0.0, MathUtils.round(0.0, 2), 0.0); assertEquals(Double.POSITIVE_INFINITY, MathUtils.round(Double.POSITIVE_INFINITY, 2), 0.0); assertEquals(Double.NEGATIVE_INFINITY, MathUtils.round(Double.NEGATIVE_INFINITY, 2), 0.0); } public void testRoundFloat() { float x = 1.234567890f; assertEquals(1.23f, MathUtils.round(x, 2), 0.0); assertEquals(1.235f, MathUtils.round(x, 3), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4), 0.0); // BZ 35904 assertEquals(30.1f, MathUtils.round(30.095f, 2), 0.0f); assertEquals(30.1f, MathUtils.round(30.095f, 1), 0.0f); assertEquals(50.09f, MathUtils.round(50.085f, 2), 0.0f); assertEquals(50.19f, MathUtils.round(50.185f, 2), 0.0f); assertEquals(50.01f, MathUtils.round(50.005f, 2), 0.0f); assertEquals(30.01f, MathUtils.round(30.005f, 2), 0.0f); assertEquals(30.65f, MathUtils.round(30.645f, 2), 0.0f); assertEquals(1.24f, MathUtils.round(x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.234f, MathUtils.round(-x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.2345f, MathUtils.round(-x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.234f, MathUtils.round(x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.2345f, MathUtils.round(x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.234f, MathUtils.round(-x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.2345f, MathUtils.round(-x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.234f, MathUtils.round(x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.2345f, MathUtils.round(x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.24f, MathUtils.round(-x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.234f, MathUtils.round(1.2345f, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.234f, MathUtils.round(-1.2345f, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.234f, MathUtils.round(1.2345f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.234f, MathUtils.round(-1.2345f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.236f, MathUtils.round(1.2355f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.236f, MathUtils.round(-1.2355f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235f, MathUtils.round(1.2345f, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235f, MathUtils.round(-1.2345f, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23f, MathUtils.round(-1.23f, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); assertEquals(1.23f, MathUtils.round(1.23f, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); try { MathUtils.round(1.234f, 2, BigDecimal.ROUND_UNNECESSARY); fail(); } catch (ArithmeticException ex) { // success } assertEquals(1.24f, MathUtils.round(x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.24f, MathUtils.round(-x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_UP), 0.0); try { MathUtils.round(1.234f, 2, 1923); fail(); } catch (IllegalArgumentException ex) { // success } // special values TestUtils.assertEquals(Float.NaN, MathUtils.round(Float.NaN, 2), 0.0f); assertEquals(0.0f, MathUtils.round(0.0f, 2), 0.0f); assertEquals(Float.POSITIVE_INFINITY, MathUtils.round(Float.POSITIVE_INFINITY, 2), 0.0f); assertEquals(Float.NEGATIVE_INFINITY, MathUtils.round(Float.NEGATIVE_INFINITY, 2), 0.0f); } public void testSignByte() { assertEquals((byte) 1, MathUtils.sign((byte) 2)); assertEquals((byte) 0, MathUtils.sign((byte) 0)); assertEquals((byte) (-1), MathUtils.sign((byte) (-2))); } public void testSignDouble() { double delta = 0.0; assertEquals(1.0, MathUtils.sign(2.0), delta); assertEquals(0.0, MathUtils.sign(0.0), delta); assertEquals(-1.0, MathUtils.sign(-2.0), delta); TestUtils.assertSame(-0. / 0., MathUtils.sign(Double.NaN)); } public void testSignFloat() { float delta = 0.0F; assertEquals(1.0F, MathUtils.sign(2.0F), delta); assertEquals(0.0F, MathUtils.sign(0.0F), delta); assertEquals(-1.0F, MathUtils.sign(-2.0F), delta); TestUtils.assertSame(Float.NaN, MathUtils.sign(Float.NaN)); } public void testSignInt() { assertEquals(1, MathUtils.sign(2)); assertEquals(0, MathUtils.sign(0)); assertEquals((-1), MathUtils.sign((-2))); } public void testSignLong() { assertEquals(1L, MathUtils.sign(2L)); assertEquals(0L, MathUtils.sign(0L)); assertEquals(-1L, MathUtils.sign(-2L)); } public void testSignShort() { assertEquals((short) 1, MathUtils.sign((short) 2)); assertEquals((short) 0, MathUtils.sign((short) 0)); assertEquals((short) (-1), MathUtils.sign((short) (-2))); } public void testSinh() { double x = 3.0; double expected = 10.01787; assertEquals(expected, MathUtils.sinh(x), 1.0e-5); } public void testSinhNaN() { assertTrue(Double.isNaN(MathUtils.sinh(Double.NaN))); } public void testSubAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; assertEquals(big, MathUtils.subAndCheck(big, 0)); assertEquals(bigNeg + 1, MathUtils.subAndCheck(bigNeg, -1)); assertEquals(-1, MathUtils.subAndCheck(bigNeg, -big)); try { MathUtils.subAndCheck(big, -1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } try { MathUtils.subAndCheck(bigNeg, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } } public void testSubAndCheckErrorMessage() { int big = Integer.MAX_VALUE; try { MathUtils.subAndCheck(big, -1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { assertTrue(ex.getMessage().length() > 1); } } public void testSubAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; assertEquals(max, MathUtils.subAndCheck(max, 0)); assertEquals(min, MathUtils.subAndCheck(min, 0)); assertEquals(-max, MathUtils.subAndCheck(0, max)); assertEquals(min + 1, MathUtils.subAndCheck(min, -1)); // min == -1-max assertEquals(-1, MathUtils.subAndCheck(-max - 1, -max)); assertEquals(max, MathUtils.subAndCheck(-1, -1 - max)); testSubAndCheckLongFailure(0L, min); testSubAndCheckLongFailure(max, -1L); testSubAndCheckLongFailure(min, 1L); } private void testSubAndCheckLongFailure(long a, long b) { try { MathUtils.subAndCheck(a, b); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // success } } public void testPow() { assertEquals(1801088541, MathUtils.pow(21, 7)); assertEquals(1, MathUtils.pow(21, 0)); try { MathUtils.pow(21, -7); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(1801088541, MathUtils.pow(21, 7l)); assertEquals(1, MathUtils.pow(21, 0l)); try { MathUtils.pow(21, -7l); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(1801088541l, MathUtils.pow(21l, 7)); assertEquals(1l, MathUtils.pow(21l, 0)); try { MathUtils.pow(21l, -7); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(1801088541l, MathUtils.pow(21l, 7l)); assertEquals(1l, MathUtils.pow(21l, 0l)); try { MathUtils.pow(21l, -7l); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } BigInteger twentyOne = BigInteger.valueOf(21l); assertEquals(BigInteger.valueOf(1801088541l), MathUtils.pow(twentyOne, 7)); assertEquals(BigInteger.ONE, MathUtils.pow(twentyOne, 0)); try { MathUtils.pow(twentyOne, -7); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(BigInteger.valueOf(1801088541l), MathUtils.pow(twentyOne, 7l)); assertEquals(BigInteger.ONE, MathUtils.pow(twentyOne, 0l)); try { MathUtils.pow(twentyOne, -7l); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(BigInteger.valueOf(1801088541l), MathUtils.pow(twentyOne, BigInteger.valueOf(7l))); assertEquals(BigInteger.ONE, MathUtils.pow(twentyOne, BigInteger.ZERO)); try { MathUtils.pow(twentyOne, BigInteger.valueOf(-7l)); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } BigInteger bigOne = new BigInteger("1543786922199448028351389769265814882661837148" + "4763915343722775611762713982220306372888519211" + "560905579993523402015636025177602059044911261"); assertEquals(bigOne, MathUtils.pow(twentyOne, 103)); assertEquals(bigOne, MathUtils.pow(twentyOne, 103l)); assertEquals(bigOne, MathUtils.pow(twentyOne, BigInteger.valueOf(103l))); } public void testL1DistanceDouble() { double[] p1 = { 2.5, 0.0 }; double[] p2 = { -0.5, 4.0 }; assertEquals(7.0, MathUtils.distance1(p1, p2)); } public void testL1DistanceInt() { int[] p1 = { 3, 0 }; int[] p2 = { 0, 4 }; assertEquals(7, MathUtils.distance1(p1, p2)); } public void testL2DistanceDouble() { double[] p1 = { 2.5, 0.0 }; double[] p2 = { -0.5, 4.0 }; assertEquals(5.0, MathUtils.distance(p1, p2)); } public void testL2DistanceInt() { int[] p1 = { 3, 0 }; int[] p2 = { 0, 4 }; assertEquals(5.0, MathUtils.distance(p1, p2)); } public void testLInfDistanceDouble() { double[] p1 = { 2.5, 0.0 }; double[] p2 = { -0.5, 4.0 }; assertEquals(4.0, MathUtils.distanceInf(p1, p2)); } public void testLInfDistanceInt() { int[] p1 = { 3, 0 }; int[] p2 = { 0, 4 }; assertEquals(4, MathUtils.distanceInf(p1, p2)); } public void testCheckOrder() { MathUtils.checkOrder(new double[] {-15, -5.5, -1, 2, 15}, MathUtils.OrderDirection.INCREASING, true); MathUtils.checkOrder(new double[] {-15, -5.5, -1, 2, 2}, MathUtils.OrderDirection.INCREASING, false); MathUtils.checkOrder(new double[] {3, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, true); MathUtils.checkOrder(new double[] {3, 0, 0, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, false); try { MathUtils.checkOrder(new double[] {-15, -5.5, -1, -1, 2, 15}, MathUtils.OrderDirection.INCREASING, true); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } try { MathUtils.checkOrder(new double[] {-15, -5.5, -1, -2, 2}, MathUtils.OrderDirection.INCREASING, false); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } try { MathUtils.checkOrder(new double[] {3, 3, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, true); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } try { MathUtils.checkOrder(new double[] {3, -1, 0, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, false); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } } }
// You are a professional Java test case writer, please create a test case named `testArrayEquals` for the issue `Math-MATH-370`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-370 // // ## Issue-Title: // NaN in "equals" methods // // ## Issue-Description: // // In "MathUtils", some "equals" methods will return true if both argument are NaN. // // Unless I'm mistaken, this contradicts the IEEE standard. // // // If nobody objects, I'm going to make the changes. // // // // // public void testArrayEquals() {
462
/** * @deprecated To be removed in release 3.0 (replaced by {@link * #testArrayEqualsIncludingNaN()}. */
63
441
src/test/java/org/apache/commons/math/util/MathUtilsTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-370 ## Issue-Title: NaN in "equals" methods ## Issue-Description: In "MathUtils", some "equals" methods will return true if both argument are NaN. Unless I'm mistaken, this contradicts the IEEE standard. If nobody objects, I'm going to make the changes. ``` You are a professional Java test case writer, please create a test case named `testArrayEquals` for the issue `Math-MATH-370`, utilizing the provided issue report information and the following function signature. ```java public void testArrayEquals() { ```
441
[ "org.apache.commons.math.util.MathUtils" ]
b89ebd6fd1f0c0fe05c5dc4eb681591ac08ef76fdd4660f02448d4aad816ec04
public void testArrayEquals()
// You are a professional Java test case writer, please create a test case named `testArrayEquals` for the issue `Math-MATH-370`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-370 // // ## Issue-Title: // NaN in "equals" methods // // ## Issue-Description: // // In "MathUtils", some "equals" methods will return true if both argument are NaN. // // Unless I'm mistaken, this contradicts the IEEE standard. // // // If nobody objects, I'm going to make the changes. // // // // //
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 java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.math.TestUtils; import org.apache.commons.math.exception.NonMonotonousSequenceException; import org.apache.commons.math.random.RandomDataImpl; /** * Test cases for the MathUtils class. * @version $Revision$ $Date: 2007-08-16 15:36:33 -0500 (Thu, 16 Aug * 2007) $ */ public final class MathUtilsTest extends TestCase { public MathUtilsTest(String name) { super(name); } /** cached binomial coefficients */ private static final List<Map<Integer, Long>> binomialCache = new ArrayList<Map<Integer, Long>>(); /** * Exact (caching) recursive implementation to test against */ private long binomialCoefficient(int n, int k) throws ArithmeticException { if (binomialCache.size() > n) { Long cachedResult = binomialCache.get(n).get(Integer.valueOf(k)); if (cachedResult != null) { return cachedResult.longValue(); } } long result = -1; if ((n == k) || (k == 0)) { result = 1; } else if ((k == 1) || (k == n - 1)) { result = n; } else { // Reduce stack depth for larger values of n if (k < n - 100) { binomialCoefficient(n - 100, k); } if (k > 100) { binomialCoefficient(n - 100, k - 100); } result = MathUtils.addAndCheck(binomialCoefficient(n - 1, k - 1), binomialCoefficient(n - 1, k)); } if (result == -1) { throw new ArithmeticException( "error computing binomial coefficient"); } for (int i = binomialCache.size(); i < n + 1; i++) { binomialCache.add(new HashMap<Integer, Long>()); } binomialCache.get(n).put(Integer.valueOf(k), Long.valueOf(result)); return result; } /** * Exact direct multiplication implementation to test against */ private long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } /** Verify that b(0,0) = 1 */ public void test0Choose0() { assertEquals(MathUtils.binomialCoefficientDouble(0, 0), 1d, 0); assertEquals(MathUtils.binomialCoefficientLog(0, 0), 0d, 0); assertEquals(MathUtils.binomialCoefficient(0, 0), 1); } public void testAddAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; assertEquals(big, MathUtils.addAndCheck(big, 0)); try { MathUtils.addAndCheck(big, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } try { MathUtils.addAndCheck(bigNeg, -1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } } public void testAddAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; assertEquals(max, MathUtils.addAndCheck(max, 0L)); assertEquals(min, MathUtils.addAndCheck(min, 0L)); assertEquals(max, MathUtils.addAndCheck(0L, max)); assertEquals(min, MathUtils.addAndCheck(0L, min)); assertEquals(1, MathUtils.addAndCheck(-1L, 2L)); assertEquals(1, MathUtils.addAndCheck(2L, -1L)); assertEquals(-3, MathUtils.addAndCheck(-2L, -1L)); assertEquals(min, MathUtils.addAndCheck(min + 1, -1L)); testAddAndCheckLongFailure(max, 1L); testAddAndCheckLongFailure(min, -1L); testAddAndCheckLongFailure(1L, max); testAddAndCheckLongFailure(-1L, min); } private void testAddAndCheckLongFailure(long a, long b) { try { MathUtils.addAndCheck(a, b); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // success } } public void testBinomialCoefficient() { long[] bcoef5 = { 1, 5, 10, 10, 5, 1 }; long[] bcoef6 = { 1, 6, 15, 20, 15, 6, 1 }; for (int i = 0; i < 6; i++) { assertEquals("5 choose " + i, bcoef5[i], MathUtils.binomialCoefficient(5, i)); } for (int i = 0; i < 7; i++) { assertEquals("6 choose " + i, bcoef6[i], MathUtils.binomialCoefficient(6, i)); } for (int n = 1; n < 10; n++) { for (int k = 0; k <= n; k++) { assertEquals(n + " choose " + k, binomialCoefficient(n, k), MathUtils.binomialCoefficient(n, k)); assertEquals(n + " choose " + k, binomialCoefficient(n, k), MathUtils.binomialCoefficientDouble(n, k), Double.MIN_VALUE); assertEquals(n + " choose " + k, FastMath.log(binomialCoefficient(n, k)), MathUtils.binomialCoefficientLog(n, k), 10E-12); } } int[] n = { 34, 66, 100, 1500, 1500 }; int[] k = { 17, 33, 10, 1500 - 4, 4 }; for (int i = 0; i < n.length; i++) { long expected = binomialCoefficient(n[i], k[i]); assertEquals(n[i] + " choose " + k[i], expected, MathUtils.binomialCoefficient(n[i], k[i])); assertEquals(n[i] + " choose " + k[i], expected, MathUtils.binomialCoefficientDouble(n[i], k[i]), 0.0); assertEquals("log(" + n[i] + " choose " + k[i] + ")", FastMath.log(expected), MathUtils.binomialCoefficientLog(n[i], k[i]), 0.0); } } /** * Tests correctness for large n and sharpness of upper bound in API doc * JIRA: MATH-241 */ public void testBinomialCoefficientLarge() throws Exception { // This tests all legal and illegal values for n <= 200. for (int n = 0; n <= 200; n++) { for (int k = 0; k <= n; k++) { long ourResult = -1; long exactResult = -1; boolean shouldThrow = false; boolean didThrow = false; try { ourResult = MathUtils.binomialCoefficient(n, k); } catch (ArithmeticException ex) { didThrow = true; } try { exactResult = binomialCoefficient(n, k); } catch (ArithmeticException ex) { shouldThrow = true; } assertEquals(n + " choose " + k, exactResult, ourResult); assertEquals(n + " choose " + k, shouldThrow, didThrow); assertTrue(n + " choose " + k, (n > 66 || !didThrow)); if (!shouldThrow && exactResult > 1) { assertEquals(n + " choose " + k, 1., MathUtils.binomialCoefficientDouble(n, k) / exactResult, 1e-10); assertEquals(n + " choose " + k, 1, MathUtils.binomialCoefficientLog(n, k) / FastMath.log(exactResult), 1e-10); } } } long ourResult = MathUtils.binomialCoefficient(300, 3); long exactResult = binomialCoefficient(300, 3); assertEquals(exactResult, ourResult); ourResult = MathUtils.binomialCoefficient(700, 697); exactResult = binomialCoefficient(700, 697); assertEquals(exactResult, ourResult); // This one should throw try { MathUtils.binomialCoefficient(700, 300); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // Expected } int n = 10000; ourResult = MathUtils.binomialCoefficient(n, 3); exactResult = binomialCoefficient(n, 3); assertEquals(exactResult, ourResult); assertEquals(1, MathUtils.binomialCoefficientDouble(n, 3) / exactResult, 1e-10); assertEquals(1, MathUtils.binomialCoefficientLog(n, 3) / FastMath.log(exactResult), 1e-10); } public void testBinomialCoefficientFail() { try { MathUtils.binomialCoefficient(4, 5); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientDouble(4, 5); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientLog(4, 5); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficient(-1, -2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientDouble(-1, -2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficientLog(-1, -2); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.binomialCoefficient(67, 30); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // ignored } try { MathUtils.binomialCoefficient(67, 34); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // ignored } double x = MathUtils.binomialCoefficientDouble(1030, 515); assertTrue("expecting infinite binomial coefficient", Double .isInfinite(x)); } public void testCompareTo() { assertEquals(0, MathUtils.compareTo(152.33, 152.32, .011)); assertTrue(MathUtils.compareTo(152.308, 152.32, .011) < 0); assertTrue(MathUtils.compareTo(152.33, 152.318, .011) > 0); } public void testCosh() { double x = 3.0; double expected = 10.06766; assertEquals(expected, MathUtils.cosh(x), 1.0e-5); } public void testCoshNaN() { assertTrue(Double.isNaN(MathUtils.cosh(Double.NaN))); } public void testEqualsIncludingNaN() { double[] testArray = { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }; for (int i = 0; i < testArray.length; i++) { for (int j = 0; j < testArray.length; j++) { if (i == j) { assertTrue(MathUtils.equalsIncludingNaN(testArray[i], testArray[j])); assertTrue(MathUtils.equalsIncludingNaN(testArray[j], testArray[i])); } else { assertTrue(!MathUtils.equalsIncludingNaN(testArray[i], testArray[j])); assertTrue(!MathUtils.equalsIncludingNaN(testArray[j], testArray[i])); } } } } public void testEqualsWithAllowedDelta() { assertTrue(MathUtils.equals(153.0000, 153.0000, .0625)); assertTrue(MathUtils.equals(153.0000, 153.0625, .0625)); assertTrue(MathUtils.equals(152.9375, 153.0000, .0625)); assertFalse(MathUtils.equals(Double.NaN, Double.NaN, 1.0)); assertTrue(MathUtils.equals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertTrue(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1.0)); assertFalse(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertFalse(MathUtils.equals(153.0000, 153.0625, .0624)); assertFalse(MathUtils.equals(152.9374, 153.0000, .0625)); } public void testEqualsIncludingNaNWithAllowedDelta() { assertTrue(MathUtils.equalsIncludingNaN(153.0000, 153.0000, .0625)); assertTrue(MathUtils.equalsIncludingNaN(153.0000, 153.0625, .0625)); assertTrue(MathUtils.equalsIncludingNaN(152.9375, 153.0000, .0625)); assertTrue(MathUtils.equalsIncludingNaN(Double.NaN, Double.NaN, 1.0)); assertTrue(MathUtils.equalsIncludingNaN(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertTrue(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1.0)); assertFalse(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0)); assertFalse(MathUtils.equalsIncludingNaN(153.0000, 153.0625, .0624)); assertFalse(MathUtils.equalsIncludingNaN(152.9374, 153.0000, .0625)); } public void testEqualsWithAllowedUlps() { assertTrue(MathUtils.equals(0.0, -0.0, 1)); assertTrue(MathUtils.equals(1.0, 1 + FastMath.ulp(1d), 1)); assertFalse(MathUtils.equals(1.0, 1 + 2 * FastMath.ulp(1d), 1)); final double nUp1 = FastMath.nextAfter(1d, Double.POSITIVE_INFINITY); final double nnUp1 = FastMath.nextAfter(nUp1, Double.POSITIVE_INFINITY); assertTrue(MathUtils.equals(1.0, nUp1, 1)); assertTrue(MathUtils.equals(nUp1, nnUp1, 1)); assertFalse(MathUtils.equals(1.0, nnUp1, 1)); assertTrue(MathUtils.equals(0.0, FastMath.ulp(0d), 1)); assertTrue(MathUtils.equals(0.0, -FastMath.ulp(0d), 1)); assertTrue(MathUtils.equals(153.0, 153.0, 1)); assertTrue(MathUtils.equals(153.0, 153.00000000000003, 1)); assertFalse(MathUtils.equals(153.0, 153.00000000000006, 1)); assertTrue(MathUtils.equals(153.0, 152.99999999999997, 1)); assertFalse(MathUtils.equals(153, 152.99999999999994, 1)); assertTrue(MathUtils.equals(-128.0, -127.99999999999999, 1)); assertFalse(MathUtils.equals(-128.0, -127.99999999999997, 1)); assertTrue(MathUtils.equals(-128.0, -128.00000000000003, 1)); assertFalse(MathUtils.equals(-128.0, -128.00000000000006, 1)); assertTrue(MathUtils.equals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equals(Double.MAX_VALUE, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); assertTrue(MathUtils.equals(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY, 1)); assertFalse(MathUtils.equals(Double.NaN, Double.NaN, 1)); assertFalse(MathUtils.equals(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 100000)); } public void testEqualsIncludingNaNWithAllowedUlps() { assertTrue(MathUtils.equalsIncludingNaN(0.0, -0.0, 1)); assertTrue(MathUtils.equalsIncludingNaN(1.0, 1 + FastMath.ulp(1d), 1)); assertFalse(MathUtils.equalsIncludingNaN(1.0, 1 + 2 * FastMath.ulp(1d), 1)); final double nUp1 = FastMath.nextAfter(1d, Double.POSITIVE_INFINITY); final double nnUp1 = FastMath.nextAfter(nUp1, Double.POSITIVE_INFINITY); assertTrue(MathUtils.equalsIncludingNaN(1.0, nUp1, 1)); assertTrue(MathUtils.equalsIncludingNaN(nUp1, nnUp1, 1)); assertFalse(MathUtils.equalsIncludingNaN(1.0, nnUp1, 1)); assertTrue(MathUtils.equalsIncludingNaN(0.0, FastMath.ulp(0d), 1)); assertTrue(MathUtils.equalsIncludingNaN(0.0, -FastMath.ulp(0d), 1)); assertTrue(MathUtils.equalsIncludingNaN(153.0, 153.0, 1)); assertTrue(MathUtils.equalsIncludingNaN(153.0, 153.00000000000003, 1)); assertFalse(MathUtils.equalsIncludingNaN(153.0, 153.00000000000006, 1)); assertTrue(MathUtils.equalsIncludingNaN(153.0, 152.99999999999997, 1)); assertFalse(MathUtils.equalsIncludingNaN(153, 152.99999999999994, 1)); assertTrue(MathUtils.equalsIncludingNaN(-128.0, -127.99999999999999, 1)); assertFalse(MathUtils.equalsIncludingNaN(-128.0, -127.99999999999997, 1)); assertTrue(MathUtils.equalsIncludingNaN(-128.0, -128.00000000000003, 1)); assertFalse(MathUtils.equalsIncludingNaN(-128.0, -128.00000000000006, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.MAX_VALUE, Double.POSITIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY, 1)); assertTrue(MathUtils.equalsIncludingNaN(Double.NaN, Double.NaN, 1)); assertFalse(MathUtils.equalsIncludingNaN(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 100000)); } /** * @deprecated To be removed in release 3.0 (replaced by {@link * #testArrayEqualsIncludingNaN()}. */ public void testArrayEquals() { assertFalse(MathUtils.equals(new double[] { 1d }, null)); assertFalse(MathUtils.equals(null, new double[] { 1d })); assertTrue(MathUtils.equals((double[]) null, (double[]) null)); assertFalse(MathUtils.equals(new double[] { 1d }, new double[0])); assertTrue(MathUtils.equals(new double[] { 1d }, new double[] { 1d })); assertTrue(MathUtils.equals(new double[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }, new double[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d })); assertFalse(MathUtils.equals(new double[] { Double.NaN }, new double[] { Double.NaN })); assertFalse(MathUtils.equals(new double[] { Double.POSITIVE_INFINITY }, new double[] { Double.NEGATIVE_INFINITY })); assertFalse(MathUtils.equals(new double[] { 1d }, new double[] { FastMath.nextAfter(FastMath.nextAfter(1d, 2d), 2d) })); } public void testArrayEqualsIncludingNaN() { assertFalse(MathUtils.equalsIncludingNaN(new double[] { 1d }, null)); assertFalse(MathUtils.equalsIncludingNaN(null, new double[] { 1d })); assertTrue(MathUtils.equalsIncludingNaN((double[]) null, (double[]) null)); assertFalse(MathUtils.equalsIncludingNaN(new double[] { 1d }, new double[0])); assertTrue(MathUtils.equalsIncludingNaN(new double[] { 1d }, new double[] { 1d })); assertTrue(MathUtils.equalsIncludingNaN(new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }, new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d })); assertFalse(MathUtils.equalsIncludingNaN(new double[] { Double.POSITIVE_INFINITY }, new double[] { Double.NEGATIVE_INFINITY })); assertFalse(MathUtils.equalsIncludingNaN(new double[] { 1d }, new double[] { FastMath.nextAfter(FastMath.nextAfter(1d, 2d), 2d) })); } public void testFactorial() { for (int i = 1; i < 21; i++) { assertEquals(i + "! ", factorial(i), MathUtils.factorial(i)); assertEquals(i + "! ", factorial(i), MathUtils.factorialDouble(i), Double.MIN_VALUE); assertEquals(i + "! ", FastMath.log(factorial(i)), MathUtils.factorialLog(i), 10E-12); } assertEquals("0", 1, MathUtils.factorial(0)); assertEquals("0", 1.0d, MathUtils.factorialDouble(0), 1E-14); assertEquals("0", 0.0d, MathUtils.factorialLog(0), 1E-14); } public void testFactorialFail() { try { MathUtils.factorial(-1); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.factorialDouble(-1); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.factorialLog(-1); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // ignored } try { MathUtils.factorial(21); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) { // ignored } assertTrue("expecting infinite factorial value", Double.isInfinite(MathUtils.factorialDouble(171))); } public void testGcd() { int a = 30; int b = 50; int c = 77; assertEquals(0, MathUtils.gcd(0, 0)); assertEquals(b, MathUtils.gcd(0, b)); assertEquals(a, MathUtils.gcd(a, 0)); assertEquals(b, MathUtils.gcd(0, -b)); assertEquals(a, MathUtils.gcd(-a, 0)); assertEquals(10, MathUtils.gcd(a, b)); assertEquals(10, MathUtils.gcd(-a, b)); assertEquals(10, MathUtils.gcd(a, -b)); assertEquals(10, MathUtils.gcd(-a, -b)); assertEquals(1, MathUtils.gcd(a, c)); assertEquals(1, MathUtils.gcd(-a, c)); assertEquals(1, MathUtils.gcd(a, -c)); assertEquals(1, MathUtils.gcd(-a, -c)); assertEquals(3 * (1<<15), MathUtils.gcd(3 * (1<<20), 9 * (1<<15))); assertEquals(Integer.MAX_VALUE, MathUtils.gcd(Integer.MAX_VALUE, 0)); assertEquals(Integer.MAX_VALUE, MathUtils.gcd(-Integer.MAX_VALUE, 0)); assertEquals(1<<30, MathUtils.gcd(1<<30, -Integer.MIN_VALUE)); try { // gcd(Integer.MIN_VALUE, 0) > Integer.MAX_VALUE MathUtils.gcd(Integer.MIN_VALUE, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(0, Integer.MIN_VALUE) > Integer.MAX_VALUE MathUtils.gcd(0, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(Integer.MIN_VALUE, Integer.MIN_VALUE) > Integer.MAX_VALUE MathUtils.gcd(Integer.MIN_VALUE, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testGcdLong(){ long a = 30; long b = 50; long c = 77; assertEquals(0, MathUtils.gcd(0L, 0)); assertEquals(b, MathUtils.gcd(0, b)); assertEquals(a, MathUtils.gcd(a, 0)); assertEquals(b, MathUtils.gcd(0, -b)); assertEquals(a, MathUtils.gcd(-a, 0)); assertEquals(10, MathUtils.gcd(a, b)); assertEquals(10, MathUtils.gcd(-a, b)); assertEquals(10, MathUtils.gcd(a, -b)); assertEquals(10, MathUtils.gcd(-a, -b)); assertEquals(1, MathUtils.gcd(a, c)); assertEquals(1, MathUtils.gcd(-a, c)); assertEquals(1, MathUtils.gcd(a, -c)); assertEquals(1, MathUtils.gcd(-a, -c)); assertEquals(3L * (1L<<45), MathUtils.gcd(3L * (1L<<50), 9L * (1L<<45))); assertEquals(1L<<45, MathUtils.gcd(1L<<45, Long.MIN_VALUE)); assertEquals(Long.MAX_VALUE, MathUtils.gcd(Long.MAX_VALUE, 0L)); assertEquals(Long.MAX_VALUE, MathUtils.gcd(-Long.MAX_VALUE, 0L)); assertEquals(1, MathUtils.gcd(60247241209L, 153092023L)); try { // gcd(Long.MIN_VALUE, 0) > Long.MAX_VALUE MathUtils.gcd(Long.MIN_VALUE, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(0, Long.MIN_VALUE) > Long.MAX_VALUE MathUtils.gcd(0, Long.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // gcd(Long.MIN_VALUE, Long.MIN_VALUE) > Long.MAX_VALUE MathUtils.gcd(Long.MIN_VALUE, Long.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testGcdConsistency() { int[] primeList = {19, 23, 53, 67, 73, 79, 101, 103, 111, 131}; ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 0; i < primeList.length; i++) { primes.add(Integer.valueOf(primeList[i])); } RandomDataImpl randomData = new RandomDataImpl(); for (int i = 0; i < 20; i++) { Object[] sample = randomData.nextSample(primes, 4); int p1 = ((Integer) sample[0]).intValue(); int p2 = ((Integer) sample[1]).intValue(); int p3 = ((Integer) sample[2]).intValue(); int p4 = ((Integer) sample[3]).intValue(); int i1 = p1 * p2 * p3; int i2 = p1 * p2 * p4; int gcd = p1 * p2; assertEquals(gcd, MathUtils.gcd(i1, i2)); long l1 = i1; long l2 = i2; assertEquals(gcd, MathUtils.gcd(l1, l2)); } } public void testHash() { double[] testArray = { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d, 1E-14, (1 + 1E-14), Double.MIN_VALUE, Double.MAX_VALUE }; for (int i = 0; i < testArray.length; i++) { for (int j = 0; j < testArray.length; j++) { if (i == j) { assertEquals(MathUtils.hash(testArray[i]), MathUtils.hash(testArray[j])); assertEquals(MathUtils.hash(testArray[j]), MathUtils.hash(testArray[i])); } else { assertTrue(MathUtils.hash(testArray[i]) != MathUtils.hash(testArray[j])); assertTrue(MathUtils.hash(testArray[j]) != MathUtils.hash(testArray[i])); } } } } public void testArrayHash() { assertEquals(0, MathUtils.hash((double[]) null)); assertEquals(MathUtils.hash(new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d }), MathUtils.hash(new double[] { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1d, 0d })); assertFalse(MathUtils.hash(new double[] { 1d }) == MathUtils.hash(new double[] { FastMath.nextAfter(1d, 2d) })); assertFalse(MathUtils.hash(new double[] { 1d }) == MathUtils.hash(new double[] { 1d, 1d })); } /** * Make sure that permuted arrays do not hash to the same value. */ public void testPermutedArrayHash() { double[] original = new double[10]; double[] permuted = new double[10]; RandomDataImpl random = new RandomDataImpl(); // Generate 10 distinct random values for (int i = 0; i < 10; i++) { original[i] = random.nextUniform(i + 0.5, i + 0.75); } // Generate a random permutation, making sure it is not the identity boolean isIdentity = true; do { int[] permutation = random.nextPermutation(10, 10); for (int i = 0; i < 10; i++) { if (i != permutation[i]) { isIdentity = false; } permuted[i] = original[permutation[i]]; } } while (isIdentity); // Verify that permuted array has different hash assertFalse(MathUtils.hash(original) == MathUtils.hash(permuted)); } public void testIndicatorByte() { assertEquals((byte)1, MathUtils.indicator((byte)2)); assertEquals((byte)1, MathUtils.indicator((byte)0)); assertEquals((byte)(-1), MathUtils.indicator((byte)(-2))); } public void testIndicatorDouble() { double delta = 0.0; assertEquals(1.0, MathUtils.indicator(2.0), delta); assertEquals(1.0, MathUtils.indicator(0.0), delta); assertEquals(-1.0, MathUtils.indicator(-2.0), delta); assertEquals(Double.NaN, MathUtils.indicator(Double.NaN)); } public void testIndicatorFloat() { float delta = 0.0F; assertEquals(1.0F, MathUtils.indicator(2.0F), delta); assertEquals(1.0F, MathUtils.indicator(0.0F), delta); assertEquals(-1.0F, MathUtils.indicator(-2.0F), delta); } public void testIndicatorInt() { assertEquals(1, MathUtils.indicator((2))); assertEquals(1, MathUtils.indicator((0))); assertEquals((-1), MathUtils.indicator((-2))); } public void testIndicatorLong() { assertEquals(1L, MathUtils.indicator(2L)); assertEquals(1L, MathUtils.indicator(0L)); assertEquals(-1L, MathUtils.indicator(-2L)); } public void testIndicatorShort() { assertEquals((short)1, MathUtils.indicator((short)2)); assertEquals((short)1, MathUtils.indicator((short)0)); assertEquals((short)(-1), MathUtils.indicator((short)(-2))); } public void testLcm() { int a = 30; int b = 50; int c = 77; assertEquals(0, MathUtils.lcm(0, b)); assertEquals(0, MathUtils.lcm(a, 0)); assertEquals(b, MathUtils.lcm(1, b)); assertEquals(a, MathUtils.lcm(a, 1)); assertEquals(150, MathUtils.lcm(a, b)); assertEquals(150, MathUtils.lcm(-a, b)); assertEquals(150, MathUtils.lcm(a, -b)); assertEquals(150, MathUtils.lcm(-a, -b)); assertEquals(2310, MathUtils.lcm(a, c)); // Assert that no intermediate value overflows: // The naive implementation of lcm(a,b) would be (a*b)/gcd(a,b) assertEquals((1<<20)*15, MathUtils.lcm((1<<20)*3, (1<<20)*5)); // Special case assertEquals(0, MathUtils.lcm(0, 0)); try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Integer.MIN_VALUE, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Integer.MIN_VALUE, 1<<20); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { MathUtils.lcm(Integer.MAX_VALUE, Integer.MAX_VALUE - 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testLcmLong() { long a = 30; long b = 50; long c = 77; assertEquals(0, MathUtils.lcm(0, b)); assertEquals(0, MathUtils.lcm(a, 0)); assertEquals(b, MathUtils.lcm(1, b)); assertEquals(a, MathUtils.lcm(a, 1)); assertEquals(150, MathUtils.lcm(a, b)); assertEquals(150, MathUtils.lcm(-a, b)); assertEquals(150, MathUtils.lcm(a, -b)); assertEquals(150, MathUtils.lcm(-a, -b)); assertEquals(2310, MathUtils.lcm(a, c)); assertEquals(Long.MAX_VALUE, MathUtils.lcm(60247241209L, 153092023L)); // Assert that no intermediate value overflows: // The naive implementation of lcm(a,b) would be (a*b)/gcd(a,b) assertEquals((1L<<50)*15, MathUtils.lcm((1L<<45)*3, (1L<<50)*5)); // Special case assertEquals(0L, MathUtils.lcm(0L, 0L)); try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Long.MIN_VALUE, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } try { // lcm == abs(MIN_VALUE) cannot be represented as a nonnegative int MathUtils.lcm(Long.MIN_VALUE, 1<<20); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } assertEquals((long) Integer.MAX_VALUE * (Integer.MAX_VALUE - 1), MathUtils.lcm((long)Integer.MAX_VALUE, Integer.MAX_VALUE - 1)); try { MathUtils.lcm(Long.MAX_VALUE, Long.MAX_VALUE - 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException expected) { // expected } } public void testLog() { assertEquals(2.0, MathUtils.log(2, 4), 0); assertEquals(3.0, MathUtils.log(2, 8), 0); assertTrue(Double.isNaN(MathUtils.log(-1, 1))); assertTrue(Double.isNaN(MathUtils.log(1, -1))); assertTrue(Double.isNaN(MathUtils.log(0, 0))); assertEquals(0, MathUtils.log(0, 10), 0); assertEquals(Double.NEGATIVE_INFINITY, MathUtils.log(10, 0), 0); } public void testMulAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; assertEquals(big, MathUtils.mulAndCheck(big, 1)); try { MathUtils.mulAndCheck(big, 2); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } try { MathUtils.mulAndCheck(bigNeg, 2); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } } public void testMulAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; assertEquals(max, MathUtils.mulAndCheck(max, 1L)); assertEquals(min, MathUtils.mulAndCheck(min, 1L)); assertEquals(0L, MathUtils.mulAndCheck(max, 0L)); assertEquals(0L, MathUtils.mulAndCheck(min, 0L)); assertEquals(max, MathUtils.mulAndCheck(1L, max)); assertEquals(min, MathUtils.mulAndCheck(1L, min)); assertEquals(0L, MathUtils.mulAndCheck(0L, max)); assertEquals(0L, MathUtils.mulAndCheck(0L, min)); assertEquals(1L, MathUtils.mulAndCheck(-1L, -1L)); assertEquals(min, MathUtils.mulAndCheck(min / 2, 2)); testMulAndCheckLongFailure(max, 2L); testMulAndCheckLongFailure(2L, max); testMulAndCheckLongFailure(min, 2L); testMulAndCheckLongFailure(2L, min); testMulAndCheckLongFailure(min, -1L); testMulAndCheckLongFailure(-1L, min); } private void testMulAndCheckLongFailure(long a, long b) { try { MathUtils.mulAndCheck(a, b); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // success } } public void testNextAfter() { // 0x402fffffffffffff 0x404123456789abcd -> 4030000000000000 assertEquals(16.0, FastMath.nextAfter(15.999999999999998, 34.27555555555555), 0.0); // 0xc02fffffffffffff 0x404123456789abcd -> c02ffffffffffffe assertEquals(-15.999999999999996, FastMath.nextAfter(-15.999999999999998, 34.27555555555555), 0.0); // 0x402fffffffffffff 0x400123456789abcd -> 402ffffffffffffe assertEquals(15.999999999999996, FastMath.nextAfter(15.999999999999998, 2.142222222222222), 0.0); // 0xc02fffffffffffff 0x400123456789abcd -> c02ffffffffffffe assertEquals(-15.999999999999996, FastMath.nextAfter(-15.999999999999998, 2.142222222222222), 0.0); // 0x4020000000000000 0x404123456789abcd -> 4020000000000001 assertEquals(8.000000000000002, FastMath.nextAfter(8.0, 34.27555555555555), 0.0); // 0xc020000000000000 0x404123456789abcd -> c01fffffffffffff assertEquals(-7.999999999999999, FastMath.nextAfter(-8.0, 34.27555555555555), 0.0); // 0x4020000000000000 0x400123456789abcd -> 401fffffffffffff assertEquals(7.999999999999999, FastMath.nextAfter(8.0, 2.142222222222222), 0.0); // 0xc020000000000000 0x400123456789abcd -> c01fffffffffffff assertEquals(-7.999999999999999, FastMath.nextAfter(-8.0, 2.142222222222222), 0.0); // 0x3f2e43753d36a223 0x3f2e43753d36a224 -> 3f2e43753d36a224 assertEquals(2.308922399667661E-4, FastMath.nextAfter(2.3089223996676606E-4, 2.308922399667661E-4), 0.0); // 0x3f2e43753d36a223 0x3f2e43753d36a223 -> 3f2e43753d36a224 assertEquals(2.308922399667661E-4, FastMath.nextAfter(2.3089223996676606E-4, 2.3089223996676606E-4), 0.0); // 0x3f2e43753d36a223 0x3f2e43753d36a222 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, 2.3089223996676603E-4), 0.0); // 0x3f2e43753d36a223 0xbf2e43753d36a224 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, -2.308922399667661E-4), 0.0); // 0x3f2e43753d36a223 0xbf2e43753d36a223 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, -2.3089223996676606E-4), 0.0); // 0x3f2e43753d36a223 0xbf2e43753d36a222 -> 3f2e43753d36a222 assertEquals(2.3089223996676603E-4, FastMath.nextAfter(2.3089223996676606E-4, -2.3089223996676603E-4), 0.0); // 0xbf2e43753d36a223 0x3f2e43753d36a224 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, 2.308922399667661E-4), 0.0); // 0xbf2e43753d36a223 0x3f2e43753d36a223 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, 2.3089223996676606E-4), 0.0); // 0xbf2e43753d36a223 0x3f2e43753d36a222 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, 2.3089223996676603E-4), 0.0); // 0xbf2e43753d36a223 0xbf2e43753d36a224 -> bf2e43753d36a224 assertEquals(-2.308922399667661E-4, FastMath.nextAfter(-2.3089223996676606E-4, -2.308922399667661E-4), 0.0); // 0xbf2e43753d36a223 0xbf2e43753d36a223 -> bf2e43753d36a224 assertEquals(-2.308922399667661E-4, FastMath.nextAfter(-2.3089223996676606E-4, -2.3089223996676606E-4), 0.0); // 0xbf2e43753d36a223 0xbf2e43753d36a222 -> bf2e43753d36a222 assertEquals(-2.3089223996676603E-4, FastMath.nextAfter(-2.3089223996676606E-4, -2.3089223996676603E-4), 0.0); } public void testNextAfterSpecialCases() { assertTrue(Double.isInfinite(FastMath.nextAfter(Double.NEGATIVE_INFINITY, 0))); assertTrue(Double.isInfinite(FastMath.nextAfter(Double.POSITIVE_INFINITY, 0))); assertTrue(Double.isNaN(FastMath.nextAfter(Double.NaN, 0))); assertTrue(Double.isInfinite(FastMath.nextAfter(Double.MAX_VALUE, Double.POSITIVE_INFINITY))); assertTrue(Double.isInfinite(FastMath.nextAfter(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY))); assertEquals(Double.MIN_VALUE, FastMath.nextAfter(0, 1), 0); assertEquals(-Double.MIN_VALUE, FastMath.nextAfter(0, -1), 0); assertEquals(0, FastMath.nextAfter(Double.MIN_VALUE, -1), 0); assertEquals(0, FastMath.nextAfter(-Double.MIN_VALUE, 1), 0); } public void testScalb() { assertEquals( 0.0, MathUtils.scalb(0.0, 5), 1.0e-15); assertEquals(32.0, MathUtils.scalb(1.0, 5), 1.0e-15); assertEquals(1.0 / 32.0, MathUtils.scalb(1.0, -5), 1.0e-15); assertEquals(FastMath.PI, MathUtils.scalb(FastMath.PI, 0), 1.0e-15); assertTrue(Double.isInfinite(MathUtils.scalb(Double.POSITIVE_INFINITY, 1))); assertTrue(Double.isInfinite(MathUtils.scalb(Double.NEGATIVE_INFINITY, 1))); assertTrue(Double.isNaN(MathUtils.scalb(Double.NaN, 1))); } public void testNormalizeAngle() { for (double a = -15.0; a <= 15.0; a += 0.1) { for (double b = -15.0; b <= 15.0; b += 0.2) { double c = MathUtils.normalizeAngle(a, b); assertTrue((b - FastMath.PI) <= c); assertTrue(c <= (b + FastMath.PI)); double twoK = FastMath.rint((a - c) / FastMath.PI); assertEquals(c, a - twoK * FastMath.PI, 1.0e-14); } } } public void testNormalizeArray() { double[] testValues1 = new double[] {1, 1, 2}; TestUtils.assertEquals( new double[] {.25, .25, .5}, MathUtils.normalizeArray(testValues1, 1), Double.MIN_VALUE); double[] testValues2 = new double[] {-1, -1, 1}; TestUtils.assertEquals( new double[] {1, 1, -1}, MathUtils.normalizeArray(testValues2, 1), Double.MIN_VALUE); // Ignore NaNs double[] testValues3 = new double[] {-1, -1, Double.NaN, 1, Double.NaN}; TestUtils.assertEquals( new double[] {1, 1,Double.NaN, -1, Double.NaN}, MathUtils.normalizeArray(testValues3, 1), Double.MIN_VALUE); // Zero sum -> ArithmeticException double[] zeroSum = new double[] {-1, 1}; try { MathUtils.normalizeArray(zeroSum, 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // Infinite elements -> ArithmeticException double[] hasInf = new double[] {1, 2, 1, Double.NEGATIVE_INFINITY}; try { MathUtils.normalizeArray(hasInf, 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // Infinite target -> IllegalArgumentException try { MathUtils.normalizeArray(testValues1, Double.POSITIVE_INFINITY); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // NaN target -> IllegalArgumentException try { MathUtils.normalizeArray(testValues1, Double.NaN); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testRoundDouble() { double x = 1.234567890; assertEquals(1.23, MathUtils.round(x, 2), 0.0); assertEquals(1.235, MathUtils.round(x, 3), 0.0); assertEquals(1.2346, MathUtils.round(x, 4), 0.0); // JIRA MATH-151 assertEquals(39.25, MathUtils.round(39.245, 2), 0.0); assertEquals(39.24, MathUtils.round(39.245, 2, BigDecimal.ROUND_DOWN), 0.0); double xx = 39.0; xx = xx + 245d / 1000d; assertEquals(39.25, MathUtils.round(xx, 2), 0.0); // BZ 35904 assertEquals(30.1d, MathUtils.round(30.095d, 2), 0.0d); assertEquals(30.1d, MathUtils.round(30.095d, 1), 0.0d); assertEquals(33.1d, MathUtils.round(33.095d, 1), 0.0d); assertEquals(33.1d, MathUtils.round(33.095d, 2), 0.0d); assertEquals(50.09d, MathUtils.round(50.085d, 2), 0.0d); assertEquals(50.19d, MathUtils.round(50.185d, 2), 0.0d); assertEquals(50.01d, MathUtils.round(50.005d, 2), 0.0d); assertEquals(30.01d, MathUtils.round(30.005d, 2), 0.0d); assertEquals(30.65d, MathUtils.round(30.645d, 2), 0.0d); assertEquals(1.24, MathUtils.round(x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.234, MathUtils.round(-x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.2345, MathUtils.round(-x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.234, MathUtils.round(x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.2345, MathUtils.round(x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.234, MathUtils.round(-x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.2345, MathUtils.round(-x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.234, MathUtils.round(x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.2345, MathUtils.round(x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.24, MathUtils.round(-x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.234, MathUtils.round(1.2345, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.234, MathUtils.round(-1.2345, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.234, MathUtils.round(1.2345, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.234, MathUtils.round(-1.2345, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.236, MathUtils.round(1.2355, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.236, MathUtils.round(-1.2355, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.23, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235, MathUtils.round(1.2345, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235, MathUtils.round(-1.2345, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23, MathUtils.round(-1.23, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); assertEquals(1.23, MathUtils.round(1.23, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); try { MathUtils.round(1.234, 2, BigDecimal.ROUND_UNNECESSARY); fail(); } catch (ArithmeticException ex) { // success } assertEquals(1.24, MathUtils.round(x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(1.235, MathUtils.round(x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(1.2346, MathUtils.round(x, 4, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.24, MathUtils.round(-x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.235, MathUtils.round(-x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.2346, MathUtils.round(-x, 4, BigDecimal.ROUND_UP), 0.0); try { MathUtils.round(1.234, 2, 1923); fail(); } catch (IllegalArgumentException ex) { // success } // MATH-151 assertEquals(39.25, MathUtils.round(39.245, 2, BigDecimal.ROUND_HALF_UP), 0.0); // special values TestUtils.assertEquals(Double.NaN, MathUtils.round(Double.NaN, 2), 0.0); assertEquals(0.0, MathUtils.round(0.0, 2), 0.0); assertEquals(Double.POSITIVE_INFINITY, MathUtils.round(Double.POSITIVE_INFINITY, 2), 0.0); assertEquals(Double.NEGATIVE_INFINITY, MathUtils.round(Double.NEGATIVE_INFINITY, 2), 0.0); } public void testRoundFloat() { float x = 1.234567890f; assertEquals(1.23f, MathUtils.round(x, 2), 0.0); assertEquals(1.235f, MathUtils.round(x, 3), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4), 0.0); // BZ 35904 assertEquals(30.1f, MathUtils.round(30.095f, 2), 0.0f); assertEquals(30.1f, MathUtils.round(30.095f, 1), 0.0f); assertEquals(50.09f, MathUtils.round(50.085f, 2), 0.0f); assertEquals(50.19f, MathUtils.round(50.185f, 2), 0.0f); assertEquals(50.01f, MathUtils.round(50.005f, 2), 0.0f); assertEquals(30.01f, MathUtils.round(30.005f, 2), 0.0f); assertEquals(30.65f, MathUtils.round(30.645f, 2), 0.0f); assertEquals(1.24f, MathUtils.round(x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.234f, MathUtils.round(-x, 3, BigDecimal.ROUND_CEILING), 0.0); assertEquals(-1.2345f, MathUtils.round(-x, 4, BigDecimal.ROUND_CEILING), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.234f, MathUtils.round(x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.2345f, MathUtils.round(x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.234f, MathUtils.round(-x, 3, BigDecimal.ROUND_DOWN), 0.0); assertEquals(-1.2345f, MathUtils.round(-x, 4, BigDecimal.ROUND_DOWN), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.234f, MathUtils.round(x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.2345f, MathUtils.round(x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.24f, MathUtils.round(-x, 2, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_FLOOR), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.234f, MathUtils.round(1.2345f, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(-1.234f, MathUtils.round(-1.2345f, 3, BigDecimal.ROUND_HALF_DOWN), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.234f, MathUtils.round(1.2345f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.234f, MathUtils.round(-1.2345f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.236f, MathUtils.round(1.2355f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(-1.236f, MathUtils.round(-1.2355f, 3, BigDecimal.ROUND_HALF_EVEN), 0.0); assertEquals(1.23f, MathUtils.round(x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23f, MathUtils.round(-x, 2, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(1.235f, MathUtils.round(1.2345f, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.235f, MathUtils.round(-1.2345f, 3, BigDecimal.ROUND_HALF_UP), 0.0); assertEquals(-1.23f, MathUtils.round(-1.23f, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); assertEquals(1.23f, MathUtils.round(1.23f, 2, BigDecimal.ROUND_UNNECESSARY), 0.0); try { MathUtils.round(1.234f, 2, BigDecimal.ROUND_UNNECESSARY); fail(); } catch (ArithmeticException ex) { // success } assertEquals(1.24f, MathUtils.round(x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(1.235f, MathUtils.round(x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(1.2346f, MathUtils.round(x, 4, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.24f, MathUtils.round(-x, 2, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.235f, MathUtils.round(-x, 3, BigDecimal.ROUND_UP), 0.0); assertEquals(-1.2346f, MathUtils.round(-x, 4, BigDecimal.ROUND_UP), 0.0); try { MathUtils.round(1.234f, 2, 1923); fail(); } catch (IllegalArgumentException ex) { // success } // special values TestUtils.assertEquals(Float.NaN, MathUtils.round(Float.NaN, 2), 0.0f); assertEquals(0.0f, MathUtils.round(0.0f, 2), 0.0f); assertEquals(Float.POSITIVE_INFINITY, MathUtils.round(Float.POSITIVE_INFINITY, 2), 0.0f); assertEquals(Float.NEGATIVE_INFINITY, MathUtils.round(Float.NEGATIVE_INFINITY, 2), 0.0f); } public void testSignByte() { assertEquals((byte) 1, MathUtils.sign((byte) 2)); assertEquals((byte) 0, MathUtils.sign((byte) 0)); assertEquals((byte) (-1), MathUtils.sign((byte) (-2))); } public void testSignDouble() { double delta = 0.0; assertEquals(1.0, MathUtils.sign(2.0), delta); assertEquals(0.0, MathUtils.sign(0.0), delta); assertEquals(-1.0, MathUtils.sign(-2.0), delta); TestUtils.assertSame(-0. / 0., MathUtils.sign(Double.NaN)); } public void testSignFloat() { float delta = 0.0F; assertEquals(1.0F, MathUtils.sign(2.0F), delta); assertEquals(0.0F, MathUtils.sign(0.0F), delta); assertEquals(-1.0F, MathUtils.sign(-2.0F), delta); TestUtils.assertSame(Float.NaN, MathUtils.sign(Float.NaN)); } public void testSignInt() { assertEquals(1, MathUtils.sign(2)); assertEquals(0, MathUtils.sign(0)); assertEquals((-1), MathUtils.sign((-2))); } public void testSignLong() { assertEquals(1L, MathUtils.sign(2L)); assertEquals(0L, MathUtils.sign(0L)); assertEquals(-1L, MathUtils.sign(-2L)); } public void testSignShort() { assertEquals((short) 1, MathUtils.sign((short) 2)); assertEquals((short) 0, MathUtils.sign((short) 0)); assertEquals((short) (-1), MathUtils.sign((short) (-2))); } public void testSinh() { double x = 3.0; double expected = 10.01787; assertEquals(expected, MathUtils.sinh(x), 1.0e-5); } public void testSinhNaN() { assertTrue(Double.isNaN(MathUtils.sinh(Double.NaN))); } public void testSubAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; assertEquals(big, MathUtils.subAndCheck(big, 0)); assertEquals(bigNeg + 1, MathUtils.subAndCheck(bigNeg, -1)); assertEquals(-1, MathUtils.subAndCheck(bigNeg, -big)); try { MathUtils.subAndCheck(big, -1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } try { MathUtils.subAndCheck(bigNeg, 1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { } } public void testSubAndCheckErrorMessage() { int big = Integer.MAX_VALUE; try { MathUtils.subAndCheck(big, -1); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { assertTrue(ex.getMessage().length() > 1); } } public void testSubAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; assertEquals(max, MathUtils.subAndCheck(max, 0)); assertEquals(min, MathUtils.subAndCheck(min, 0)); assertEquals(-max, MathUtils.subAndCheck(0, max)); assertEquals(min + 1, MathUtils.subAndCheck(min, -1)); // min == -1-max assertEquals(-1, MathUtils.subAndCheck(-max - 1, -max)); assertEquals(max, MathUtils.subAndCheck(-1, -1 - max)); testSubAndCheckLongFailure(0L, min); testSubAndCheckLongFailure(max, -1L); testSubAndCheckLongFailure(min, 1L); } private void testSubAndCheckLongFailure(long a, long b) { try { MathUtils.subAndCheck(a, b); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) { // success } } public void testPow() { assertEquals(1801088541, MathUtils.pow(21, 7)); assertEquals(1, MathUtils.pow(21, 0)); try { MathUtils.pow(21, -7); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(1801088541, MathUtils.pow(21, 7l)); assertEquals(1, MathUtils.pow(21, 0l)); try { MathUtils.pow(21, -7l); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(1801088541l, MathUtils.pow(21l, 7)); assertEquals(1l, MathUtils.pow(21l, 0)); try { MathUtils.pow(21l, -7); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(1801088541l, MathUtils.pow(21l, 7l)); assertEquals(1l, MathUtils.pow(21l, 0l)); try { MathUtils.pow(21l, -7l); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } BigInteger twentyOne = BigInteger.valueOf(21l); assertEquals(BigInteger.valueOf(1801088541l), MathUtils.pow(twentyOne, 7)); assertEquals(BigInteger.ONE, MathUtils.pow(twentyOne, 0)); try { MathUtils.pow(twentyOne, -7); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(BigInteger.valueOf(1801088541l), MathUtils.pow(twentyOne, 7l)); assertEquals(BigInteger.ONE, MathUtils.pow(twentyOne, 0l)); try { MathUtils.pow(twentyOne, -7l); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } assertEquals(BigInteger.valueOf(1801088541l), MathUtils.pow(twentyOne, BigInteger.valueOf(7l))); assertEquals(BigInteger.ONE, MathUtils.pow(twentyOne, BigInteger.ZERO)); try { MathUtils.pow(twentyOne, BigInteger.valueOf(-7l)); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected behavior } BigInteger bigOne = new BigInteger("1543786922199448028351389769265814882661837148" + "4763915343722775611762713982220306372888519211" + "560905579993523402015636025177602059044911261"); assertEquals(bigOne, MathUtils.pow(twentyOne, 103)); assertEquals(bigOne, MathUtils.pow(twentyOne, 103l)); assertEquals(bigOne, MathUtils.pow(twentyOne, BigInteger.valueOf(103l))); } public void testL1DistanceDouble() { double[] p1 = { 2.5, 0.0 }; double[] p2 = { -0.5, 4.0 }; assertEquals(7.0, MathUtils.distance1(p1, p2)); } public void testL1DistanceInt() { int[] p1 = { 3, 0 }; int[] p2 = { 0, 4 }; assertEquals(7, MathUtils.distance1(p1, p2)); } public void testL2DistanceDouble() { double[] p1 = { 2.5, 0.0 }; double[] p2 = { -0.5, 4.0 }; assertEquals(5.0, MathUtils.distance(p1, p2)); } public void testL2DistanceInt() { int[] p1 = { 3, 0 }; int[] p2 = { 0, 4 }; assertEquals(5.0, MathUtils.distance(p1, p2)); } public void testLInfDistanceDouble() { double[] p1 = { 2.5, 0.0 }; double[] p2 = { -0.5, 4.0 }; assertEquals(4.0, MathUtils.distanceInf(p1, p2)); } public void testLInfDistanceInt() { int[] p1 = { 3, 0 }; int[] p2 = { 0, 4 }; assertEquals(4, MathUtils.distanceInf(p1, p2)); } public void testCheckOrder() { MathUtils.checkOrder(new double[] {-15, -5.5, -1, 2, 15}, MathUtils.OrderDirection.INCREASING, true); MathUtils.checkOrder(new double[] {-15, -5.5, -1, 2, 2}, MathUtils.OrderDirection.INCREASING, false); MathUtils.checkOrder(new double[] {3, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, true); MathUtils.checkOrder(new double[] {3, 0, 0, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, false); try { MathUtils.checkOrder(new double[] {-15, -5.5, -1, -1, 2, 15}, MathUtils.OrderDirection.INCREASING, true); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } try { MathUtils.checkOrder(new double[] {-15, -5.5, -1, -2, 2}, MathUtils.OrderDirection.INCREASING, false); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } try { MathUtils.checkOrder(new double[] {3, 3, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, true); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } try { MathUtils.checkOrder(new double[] {3, -1, 0, -5.5, -11, -27.5}, MathUtils.OrderDirection.DECREASING, false); fail("an exception should have been thrown"); } catch (NonMonotonousSequenceException e) { // Expected } } }
public void testUnfinishedEntity() { NumericEntityUnescaper neu = new NumericEntityUnescaper(); String input = "Test &#x30 not test"; String expected = "Test \u0030 not test"; String result = neu.translate(input); assertEquals("Failed to support unfinished entities (i.e. missing semi-colon", expected, result); }
org.apache.commons.lang3.text.translate.NumericEntityUnescaperTest::testUnfinishedEntity
src/test/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaperTest.java
52
src/test/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaperTest.java
testUnfinishedEntity
/* * 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.text.translate; import junit.framework.TestCase; /** * Unit tests for {@link org.apache.commons.lang3.text.translate.NumericEntityUnescaper}. * @version $Id$ */ public class NumericEntityUnescaperTest extends TestCase { public void testSupplementaryUnescaping() { NumericEntityUnescaper neu = new NumericEntityUnescaper(); String input = "&#68642;"; String expected = "\uD803\uDC22"; String result = neu.translate(input); assertEquals("Failed to unescape numeric entities supplementary characters", expected, result); } public void testOutOfBounds() { NumericEntityUnescaper neu = new NumericEntityUnescaper(); assertEquals("Failed to ignore when last character is &", "Test &", neu.translate("Test &")); assertEquals("Failed to ignore when last character is &", "Test &#", neu.translate("Test &#")); assertEquals("Failed to ignore when last character is &", "Test &#x", neu.translate("Test &#x")); assertEquals("Failed to ignore when last character is &", "Test &#X", neu.translate("Test &#X")); } public void testUnfinishedEntity() { NumericEntityUnescaper neu = new NumericEntityUnescaper(); String input = "Test &#x30 not test"; String expected = "Test \u0030 not test"; String result = neu.translate(input); assertEquals("Failed to support unfinished entities (i.e. missing semi-colon", expected, result); } }
// You are a professional Java test case writer, please create a test case named `testUnfinishedEntity` for the issue `Lang-LANG-710`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-710 // // ## Issue-Title: // StringIndexOutOfBoundsException when calling unescapeHtml4("&#03") // // ## Issue-Description: // // When calling unescapeHtml4() on the String "&#03" (or any String that contains these characters) an Exception is thrown: // // // Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4 // // at java.lang.String.charAt(String.java:686) // // at org.apache.commons.lang3.text.translate.NumericEntityUnescaper.translate(NumericEntityUnescaper.java:49) // // at org.apache.commons.lang3.text.translate.AggregateTranslator.translate(AggregateTranslator.java:53) // // at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:88) // // at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:60) // // at org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(StringEscapeUtils.java:351) // // // // // public void testUnfinishedEntity() {
52
19
45
src/test/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaperTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-710 ## Issue-Title: StringIndexOutOfBoundsException when calling unescapeHtml4("&#03") ## Issue-Description: When calling unescapeHtml4() on the String "&#03" (or any String that contains these characters) an Exception is thrown: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4 at java.lang.String.charAt(String.java:686) at org.apache.commons.lang3.text.translate.NumericEntityUnescaper.translate(NumericEntityUnescaper.java:49) at org.apache.commons.lang3.text.translate.AggregateTranslator.translate(AggregateTranslator.java:53) at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:88) at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:60) at org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(StringEscapeUtils.java:351) ``` You are a professional Java test case writer, please create a test case named `testUnfinishedEntity` for the issue `Lang-LANG-710`, utilizing the provided issue report information and the following function signature. ```java public void testUnfinishedEntity() { ```
45
[ "org.apache.commons.lang3.text.translate.NumericEntityUnescaper" ]
b8b415f4986b4fe3f5e39b6a0877dcffe3799435c3bdf4691ad02995cb233ba5
public void testUnfinishedEntity()
// You are a professional Java test case writer, please create a test case named `testUnfinishedEntity` for the issue `Lang-LANG-710`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-710 // // ## Issue-Title: // StringIndexOutOfBoundsException when calling unescapeHtml4("&#03") // // ## Issue-Description: // // When calling unescapeHtml4() on the String "&#03" (or any String that contains these characters) an Exception is thrown: // // // Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4 // // at java.lang.String.charAt(String.java:686) // // at org.apache.commons.lang3.text.translate.NumericEntityUnescaper.translate(NumericEntityUnescaper.java:49) // // at org.apache.commons.lang3.text.translate.AggregateTranslator.translate(AggregateTranslator.java:53) // // at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:88) // // at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:60) // // at org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(StringEscapeUtils.java:351) // // // // //
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.text.translate; import junit.framework.TestCase; /** * Unit tests for {@link org.apache.commons.lang3.text.translate.NumericEntityUnescaper}. * @version $Id$ */ public class NumericEntityUnescaperTest extends TestCase { public void testSupplementaryUnescaping() { NumericEntityUnescaper neu = new NumericEntityUnescaper(); String input = "&#68642;"; String expected = "\uD803\uDC22"; String result = neu.translate(input); assertEquals("Failed to unescape numeric entities supplementary characters", expected, result); } public void testOutOfBounds() { NumericEntityUnescaper neu = new NumericEntityUnescaper(); assertEquals("Failed to ignore when last character is &", "Test &", neu.translate("Test &")); assertEquals("Failed to ignore when last character is &", "Test &#", neu.translate("Test &#")); assertEquals("Failed to ignore when last character is &", "Test &#x", neu.translate("Test &#x")); assertEquals("Failed to ignore when last character is &", "Test &#X", neu.translate("Test &#X")); } public void testUnfinishedEntity() { NumericEntityUnescaper neu = new NumericEntityUnescaper(); String input = "Test &#x30 not test"; String expected = "Test \u0030 not test"; String result = neu.translate(input); assertEquals("Failed to support unfinished entities (i.e. missing semi-colon", expected, result); } }
@Test public void TestLang747() { assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000")); assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000")); assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000")); assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000")); assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF")); assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000")); assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF")); // Leading zero tests assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000")); assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF")); assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000")); assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF")); assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000")); assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000")); assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000")); assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000")); assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000")); assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000")); assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000")); assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF")); // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000")); assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF")); // Leading zero tests assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000")); assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000")); assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF")); // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000")); assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF")); }
org.apache.commons.lang3.math.NumberUtilsTest::TestLang747
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
283
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
TestLang747
/* * 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.math; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import org.junit.Test; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @version $Id$ */ public class NumberUtilsTest { //----------------------------------------------------------------------- @Test public void testConstructor() { assertNotNull(new NumberUtils()); final Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(NumberUtils.class.getModifiers())); assertFalse(Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ @Test public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ @Test public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ @Test public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ @Test public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ @Test public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ @Test public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {(@link NumberUtils#createNumber(String)} */ @Test public void testStringCreateNumberEnsureNoPrecisionLoss(){ String shouldBeFloat = "1.23"; String shouldBeDouble = "3.40282354e+38"; String shouldBeBigDecimal = "1.797693134862315759e+308"; assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float); assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double); assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal); } /** * Test for {@link NumberUtils#toDouble(String)}. */ @Test public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ @Test public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ @Test public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ @Test public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ @Test public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ @Test public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } @Test public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", Integer.valueOf("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", Float.valueOf("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", Integer.valueOf("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9a failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 9b failed", 0xFADE == NumberUtils.createNumber("0Xfade").intValue()); assertTrue("createNumber(String) 10a failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertTrue("createNumber(String) 10b failed", -0xFADE == NumberUtils.createNumber("-0Xfade").intValue()); assertEquals("createNumber(String) 11 failed", Double.valueOf("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", Float.valueOf("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); assertEquals("createNumber(String) 16 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", Float.valueOf("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); // LANG-693 assertEquals("createNumber(String) LANG-693 failed", Double.valueOf(Double.MAX_VALUE), NumberUtils .createNumber("" + Double.MAX_VALUE)); // LANG-822 // ensure that the underlying negative number would create a BigDecimal final Number bigNum = NumberUtils.createNumber("-1.1E-700F"); assertNotNull(bigNum); assertEquals(BigDecimal.class, bigNum.getClass()); } @Test public void TestLang747() { assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000")); assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000")); assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000")); assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000")); assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF")); assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000")); assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF")); // Leading zero tests assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000")); assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF")); assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000")); assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF")); assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000")); assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000")); assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000")); assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000")); assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000")); assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000")); assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000")); assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF")); // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000")); assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF")); // Leading zero tests assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000")); assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000")); assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF")); // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000")); assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF")); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when preceeded by -- rather than - public void testCreateNumberFailure_1() { NumberUtils.createNumber("--1.1E-700F"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (with decimal) public void testCreateNumberFailure_2() { NumberUtils.createNumber("-1.1E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_3() { NumberUtils.createNumber("-11E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_4() { NumberUtils.createNumber("1eE+00001"); } // Tests to show when magnitude causes switch to next Number type // Will probably need to be adjusted if code is changed to check precision (LANG-693) @Test public void testCreateNumberMagnitude() { // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38")); assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38")); // Test Double.MAX_VALUE assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308")); // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal) assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308")); assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678")); assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff")); // Does not appear to be a way to create a literal BigInteger of this magnitude assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("0x7fffffffffffffff0")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff")); assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("#7fffffffffffffff0")); assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); // 63 bits assertEquals(new BigInteger("1777777777777777777777",8), NumberUtils.createNumber("01777777777777777777777"));// 64 bits } @Test public void testCreateFloat() { assertEquals("createFloat(String) failed", Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(final String str) { try { final Float value = NumberUtils.createFloat(str); fail("createFloat(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateDouble() { assertEquals("createDouble(String) failed", Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(final String str) { try { final Double value = NumberUtils.createDouble(str); fail("createDouble(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateInteger() { assertEquals("createInteger(String) failed", Integer.valueOf("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(final String str) { try { final Integer value = NumberUtils.createInteger(str); fail("createInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateLong() { assertEquals("createLong(String) failed", Long.valueOf("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(final String str) { try { final Long value = NumberUtils.createLong(str); fail("createLong(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("#ff")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-0"), NumberUtils.createBigInteger("-0")); assertEquals("createBigInteger(String) failed", new BigInteger("0"), NumberUtils.createBigInteger("0")); testCreateBigIntegerFailure("#"); testCreateBigIntegerFailure("-#"); testCreateBigIntegerFailure("0x"); testCreateBigIntegerFailure("-0x"); } protected void testCreateBigIntegerFailure(final String str) { try { final BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); this.testCreateBigDecimalFailure("-"); // sign alone not valid this.testCreateBigDecimalFailure("--"); // comment in NumberUtils suggests some implementations may incorrectly allow this this.testCreateBigDecimalFailure("--0"); this.testCreateBigDecimalFailure("+"); // sign alone not valid this.testCreateBigDecimalFailure("++"); // in case this was also allowed by some JVMs this.testCreateBigDecimalFailure("++0"); } protected void testCreateBigDecimalFailure(final String str) { try { final BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- @Test(expected = IllegalArgumentException.class) public void testMinLong_nullArray() { NumberUtils.min((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinLong_emptyArray() { NumberUtils.min(new long[0]); } @Test public void testMinLong() { assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinInt_nullArray() { NumberUtils.min((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinInt_emptyArray() { NumberUtils.min(new int[0]); } @Test public void testMinInt() { assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinShort_nullArray() { NumberUtils.min((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinShort_emptyArray() { NumberUtils.min(new short[0]); } @Test public void testMinShort() { assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinByte_nullArray() { NumberUtils.min((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinByte_emptyArray() { NumberUtils.min(new byte[0]); } @Test public void testMinByte() { assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_nullArray() { NumberUtils.min((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_emptyArray() { NumberUtils.min(new double[0]); } @Test public void testMinDouble() { assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_nullArray() { NumberUtils.min((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_emptyArray() { NumberUtils.min(new float[0]); } @Test public void testMinFloat() { assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_nullArray() { NumberUtils.max((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_emptyArray() { NumberUtils.max(new long[0]); } @Test public void testMaxLong() { assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_nullArray() { NumberUtils.max((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_emptyArray() { NumberUtils.max(new int[0]); } @Test public void testMaxInt() { assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_nullArray() { NumberUtils.max((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_emptyArray() { NumberUtils.max(new short[0]); } @Test public void testMaxShort() { assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_nullArray() { NumberUtils.max((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_emptyArray() { NumberUtils.max(new byte[0]); } @Test public void testMaxByte() { assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_nullArray() { NumberUtils.max((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_emptyArray() { NumberUtils.max(new double[0]); } @Test public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (final IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (final IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_nullArray() { NumberUtils.max((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_emptyArray() { NumberUtils.max(new float[0]); } @Test public void testMaxFloat() { assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } @Test public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } @Test public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } @Test public void testMinimumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } @Test public void testMinimumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } @Test public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } @Test public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } @Test public void testMaximumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } @Test public void testMaximumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality @Test public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } @Test public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } @Test public void testIsDigits() { assertFalse("isDigits(null) failed", NumberUtils.isDigits(null)); assertFalse("isDigits('') failed", NumberUtils.isDigits("")); assertTrue("isDigits(String) failed", NumberUtils.isDigits("12345")); assertFalse("isDigits(String) neg 1 failed", NumberUtils.isDigits("1234.5")); assertFalse("isDigits(String) neg 3 failed", NumberUtils.isDigits("1ab")); assertFalse("isDigits(String) neg 4 failed", NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ @Test public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); // LANG-664 val = "1.1L"; assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(final String val) { try { final Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (final NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check @Test public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } @Test public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } @Test public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
// You are a professional Java test case writer, please create a test case named `TestLang747` for the issue `Lang-LANG-747`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-747 // // ## Issue-Title: // NumberUtils does not handle Long Hex numbers // // ## Issue-Description: // // NumberUtils.createLong() does not handle hex numbers, but createInteger() handles hex and octal. // // This seems odd. // // // NumberUtils.createNumber() assumes that hex numbers can only be Integer. // // Again, why not handle bigger Hex numbers? // // // == // // // It is trivial to fix createLong() - just use Long.decode() instead of valueOf(). // // It's not clear why this was not done originally - the decode() method was added to both Integer and Long in Java 1.2. // // // Fixing createNumber() is also fairly easy - if the hex string has more than 8 digits, use Long. // // // Should we allow for leading zeros in an Integer? // // If not, the length check is trivial. // // // // // @Test public void TestLang747() {
283
1
248
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-747 ## Issue-Title: NumberUtils does not handle Long Hex numbers ## Issue-Description: NumberUtils.createLong() does not handle hex numbers, but createInteger() handles hex and octal. This seems odd. NumberUtils.createNumber() assumes that hex numbers can only be Integer. Again, why not handle bigger Hex numbers? == It is trivial to fix createLong() - just use Long.decode() instead of valueOf(). It's not clear why this was not done originally - the decode() method was added to both Integer and Long in Java 1.2. Fixing createNumber() is also fairly easy - if the hex string has more than 8 digits, use Long. Should we allow for leading zeros in an Integer? If not, the length check is trivial. ``` You are a professional Java test case writer, please create a test case named `TestLang747` for the issue `Lang-LANG-747`, utilizing the provided issue report information and the following function signature. ```java @Test public void TestLang747() { ```
248
[ "org.apache.commons.lang3.math.NumberUtils" ]
b8dcad25f49707ad1b320847f699f2853b233291eddec5793615df39006587aa
@Test public void TestLang747()
// You are a professional Java test case writer, please create a test case named `TestLang747` for the issue `Lang-LANG-747`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-747 // // ## Issue-Title: // NumberUtils does not handle Long Hex numbers // // ## Issue-Description: // // NumberUtils.createLong() does not handle hex numbers, but createInteger() handles hex and octal. // // This seems odd. // // // NumberUtils.createNumber() assumes that hex numbers can only be Integer. // // Again, why not handle bigger Hex numbers? // // // == // // // It is trivial to fix createLong() - just use Long.decode() instead of valueOf(). // // It's not clear why this was not done originally - the decode() method was added to both Integer and Long in Java 1.2. // // // Fixing createNumber() is also fairly easy - if the hex string has more than 8 digits, use Long. // // // Should we allow for leading zeros in an Integer? // // If not, the length check is trivial. // // // // //
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.math; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import org.junit.Test; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @version $Id$ */ public class NumberUtilsTest { //----------------------------------------------------------------------- @Test public void testConstructor() { assertNotNull(new NumberUtils()); final Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(NumberUtils.class.getModifiers())); assertFalse(Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ @Test public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ @Test public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ @Test public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ @Test public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ @Test public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ @Test public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {(@link NumberUtils#createNumber(String)} */ @Test public void testStringCreateNumberEnsureNoPrecisionLoss(){ String shouldBeFloat = "1.23"; String shouldBeDouble = "3.40282354e+38"; String shouldBeBigDecimal = "1.797693134862315759e+308"; assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float); assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double); assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal); } /** * Test for {@link NumberUtils#toDouble(String)}. */ @Test public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ @Test public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ @Test public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ @Test public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ @Test public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ @Test public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } @Test public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", Integer.valueOf("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", Long.valueOf(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", Float.valueOf("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", Integer.valueOf("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9a failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 9b failed", 0xFADE == NumberUtils.createNumber("0Xfade").intValue()); assertTrue("createNumber(String) 10a failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertTrue("createNumber(String) 10b failed", -0xFADE == NumberUtils.createNumber("-0Xfade").intValue()); assertEquals("createNumber(String) 11 failed", Double.valueOf("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", Float.valueOf("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); assertEquals("createNumber(String) 16 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", Float.valueOf("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); // LANG-693 assertEquals("createNumber(String) LANG-693 failed", Double.valueOf(Double.MAX_VALUE), NumberUtils .createNumber("" + Double.MAX_VALUE)); // LANG-822 // ensure that the underlying negative number would create a BigDecimal final Number bigNum = NumberUtils.createNumber("-1.1E-700F"); assertNotNull(bigNum); assertEquals(BigDecimal.class, bigNum.getClass()); } @Test public void TestLang747() { assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000")); assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000")); assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000")); assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000")); assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF")); assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000")); assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF")); // Leading zero tests assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000")); assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF")); assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000")); assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF")); assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000")); assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000")); assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000")); assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000")); assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000")); assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000")); assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000")); assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF")); // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000")); assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF")); // Leading zero tests assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000")); assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000")); assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF")); // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000")); assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF")); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when preceeded by -- rather than - public void testCreateNumberFailure_1() { NumberUtils.createNumber("--1.1E-700F"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (with decimal) public void testCreateNumberFailure_2() { NumberUtils.createNumber("-1.1E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_3() { NumberUtils.createNumber("-11E+0-7e00"); } @Test(expected=NumberFormatException.class) // Check that the code fails to create a valid number when both e and E are present (no decimal) public void testCreateNumberFailure_4() { NumberUtils.createNumber("1eE+00001"); } // Tests to show when magnitude causes switch to next Number type // Will probably need to be adjusted if code is changed to check precision (LANG-693) @Test public void testCreateNumberMagnitude() { // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38")); assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38")); // Test Double.MAX_VALUE assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308")); // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal) assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308")); assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678")); assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff")); // Does not appear to be a way to create a literal BigInteger of this magnitude assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("0x7fffffffffffffff0")); assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff")); assertEquals(new BigInteger("7fffffffffffffff0",16), NumberUtils.createNumber("#7fffffffffffffff0")); assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); // 63 bits assertEquals(new BigInteger("1777777777777777777777",8), NumberUtils.createNumber("01777777777777777777777"));// 64 bits } @Test public void testCreateFloat() { assertEquals("createFloat(String) failed", Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(final String str) { try { final Float value = NumberUtils.createFloat(str); fail("createFloat(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateDouble() { assertEquals("createDouble(String) failed", Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(final String str) { try { final Double value = NumberUtils.createDouble(str); fail("createDouble(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateInteger() { assertEquals("createInteger(String) failed", Integer.valueOf("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(final String str) { try { final Integer value = NumberUtils.createInteger(str); fail("createInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateLong() { assertEquals("createLong(String) failed", Long.valueOf("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(final String str) { try { final Long value = NumberUtils.createLong(str); fail("createLong(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("#ff")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0xff")); assertEquals("createBigInteger(String) failed", new BigInteger("255"), NumberUtils.createBigInteger("0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-255"), NumberUtils.createBigInteger("-0377")); assertEquals("createBigInteger(String) failed", new BigInteger("-0"), NumberUtils.createBigInteger("-0")); assertEquals("createBigInteger(String) failed", new BigInteger("0"), NumberUtils.createBigInteger("0")); testCreateBigIntegerFailure("#"); testCreateBigIntegerFailure("-#"); testCreateBigIntegerFailure("0x"); testCreateBigIntegerFailure("-0x"); } protected void testCreateBigIntegerFailure(final String str) { try { final BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } @Test public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); this.testCreateBigDecimalFailure("-"); // sign alone not valid this.testCreateBigDecimalFailure("--"); // comment in NumberUtils suggests some implementations may incorrectly allow this this.testCreateBigDecimalFailure("--0"); this.testCreateBigDecimalFailure("+"); // sign alone not valid this.testCreateBigDecimalFailure("++"); // in case this was also allowed by some JVMs this.testCreateBigDecimalFailure("++0"); } protected void testCreateBigDecimalFailure(final String str) { try { final BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(\"" + str + "\") should have failed: " + value); } catch (final NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- @Test(expected = IllegalArgumentException.class) public void testMinLong_nullArray() { NumberUtils.min((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinLong_emptyArray() { NumberUtils.min(new long[0]); } @Test public void testMinLong() { assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinInt_nullArray() { NumberUtils.min((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinInt_emptyArray() { NumberUtils.min(new int[0]); } @Test public void testMinInt() { assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinShort_nullArray() { NumberUtils.min((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinShort_emptyArray() { NumberUtils.min(new short[0]); } @Test public void testMinShort() { assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinByte_nullArray() { NumberUtils.min((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinByte_emptyArray() { NumberUtils.min(new byte[0]); } @Test public void testMinByte() { assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_nullArray() { NumberUtils.min((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinDouble_emptyArray() { NumberUtils.min(new double[0]); } @Test public void testMinDouble() { assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_nullArray() { NumberUtils.min((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMinFloat_emptyArray() { NumberUtils.min(new float[0]); } @Test public void testMinFloat() { assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_nullArray() { NumberUtils.max((long[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxLong_emptyArray() { NumberUtils.max(new long[0]); } @Test public void testMaxLong() { assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_nullArray() { NumberUtils.max((int[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxInt_emptyArray() { NumberUtils.max(new int[0]); } @Test public void testMaxInt() { assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_nullArray() { NumberUtils.max((short[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxShort_emptyArray() { NumberUtils.max(new short[0]); } @Test public void testMaxShort() { assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_nullArray() { NumberUtils.max((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxByte_emptyArray() { NumberUtils.max(new byte[0]); } @Test public void testMaxByte() { assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_nullArray() { NumberUtils.max((double[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxDouble_emptyArray() { NumberUtils.max(new double[0]); } @Test public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (final IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (final IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_nullArray() { NumberUtils.max((float[]) null); } @Test(expected = IllegalArgumentException.class) public void testMaxFloat_emptyArray() { NumberUtils.max(new float[0]); } @Test public void testMaxFloat() { assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } @Test public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } @Test public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } @Test public void testMinimumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } @Test public void testMinimumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } @Test public void testMinimumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } @Test public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } @Test public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } @Test public void testMaximumShort() { final short low = 1234; final short mid = 1234 + 1; final short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumByte() { final byte low = 123; final byte mid = 123 + 1; final byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } @Test public void testMaximumDouble() { final double low = 12.3; final double mid = 12.3 + 1; final double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } @Test public void testMaximumFloat() { final float low = 12.3f; final float mid = 12.3f + 1; final float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality @Test public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } @Test public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } @Test public void testIsDigits() { assertFalse("isDigits(null) failed", NumberUtils.isDigits(null)); assertFalse("isDigits('') failed", NumberUtils.isDigits("")); assertTrue("isDigits(String) failed", NumberUtils.isDigits("12345")); assertFalse("isDigits(String) neg 1 failed", NumberUtils.isDigits("1234.5")); assertFalse("isDigits(String) neg 3 failed", NumberUtils.isDigits("1ab")); assertFalse("isDigits(String) neg 4 failed", NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ @Test public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); // LANG-664 val = "1.1L"; assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(final String val) { try { final Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (final NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check @Test public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } @Test public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } @Test public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
public void testLendsAnnotation3() { testSame("/** @constructor */ function F() {}" + "dojo.declare(F, /** @lends {F.prototype} */ (" + " {foo: function() { return this.foo; }}));"); }
com.google.javascript.jscomp.CheckGlobalThisTest::testLendsAnnotation3
test/com/google/javascript/jscomp/CheckGlobalThisTest.java
238
test/com/google/javascript/jscomp/CheckGlobalThisTest.java
testLendsAnnotation3
/* * 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 testIssue182a() { testFailure("var NS = {read: function() { return this.foo; }};"); } public void testIssue182b() { testFailure("var NS = {write: function() { this.foo = 3; }};"); } public void testIssue182c() { testFailure("var NS = {}; NS.write2 = function() { this.foo = 3; };"); } public void testIssue182d() { testSame("function Foo() {} " + "Foo.prototype = {write: function() { this.foo = 3; }};"); } public void testLendsAnnotation1() { testFailure("/** @constructor */ function F() {}" + "dojo.declare(F, {foo: function() { return this.foo; }});"); } public void testLendsAnnotation2() { testFailure("/** @constructor */ function F() {}" + "dojo.declare(F, /** @lends {F.bar} */ (" + " {foo: function() { return this.foo; }}));"); } public void testLendsAnnotation3() { testSame("/** @constructor */ function F() {}" + "dojo.declare(F, /** @lends {F.prototype} */ (" + " {foo: function() { return this.foo; }}));"); } }
// You are a professional Java test case writer, please create a test case named `testLendsAnnotation3` for the issue `Closure-248`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-248 // // ## Issue-Title: // support @lends annotation // // ## Issue-Description: // Some javascript toolkits (dojo, base, etc.) have a special way of declaring (what java calls) classes, for example in dojo: // // dojo.declare("MyClass", [superClass1, superClass2], { // foo: function(){ ... } // bar: function(){ ... } // }); // // JSDoc (or at least JSDoc toolkit) supports this via annotations: // // /\*\* // \* @name MyClass // \* @class // \* @extends superClass1 // \* @extends superClass2 // \*/ // dojo.declare("MyClass", [superClass1, superClass2], /\*\* @lends // MyClass.prototype \*/ { // foo: function(){ ... } // bar: function(){ ... } // }); // // The @lends keyword in particular is useful since it tells JSDoc that foo and bar are part of MyClass's prototype. But closure compiler isn't picking up on that, thus I get a bunch of errors about "dangerous use of this" inside of foo() and bar(). // // So, can @lends support be added to the closure compiler? // // The workaround is to use @this on every method, but not sure if that is sufficient to make advanced mode compilation work correctly. // // public void testLendsAnnotation3() {
238
91
234
test/com/google/javascript/jscomp/CheckGlobalThisTest.java
test
```markdown ## Issue-ID: Closure-248 ## Issue-Title: support @lends annotation ## Issue-Description: Some javascript toolkits (dojo, base, etc.) have a special way of declaring (what java calls) classes, for example in dojo: dojo.declare("MyClass", [superClass1, superClass2], { foo: function(){ ... } bar: function(){ ... } }); JSDoc (or at least JSDoc toolkit) supports this via annotations: /\*\* \* @name MyClass \* @class \* @extends superClass1 \* @extends superClass2 \*/ dojo.declare("MyClass", [superClass1, superClass2], /\*\* @lends MyClass.prototype \*/ { foo: function(){ ... } bar: function(){ ... } }); The @lends keyword in particular is useful since it tells JSDoc that foo and bar are part of MyClass's prototype. But closure compiler isn't picking up on that, thus I get a bunch of errors about "dangerous use of this" inside of foo() and bar(). So, can @lends support be added to the closure compiler? The workaround is to use @this on every method, but not sure if that is sufficient to make advanced mode compilation work correctly. ``` You are a professional Java test case writer, please create a test case named `testLendsAnnotation3` for the issue `Closure-248`, utilizing the provided issue report information and the following function signature. ```java public void testLendsAnnotation3() { ```
234
[ "com.google.javascript.jscomp.CheckGlobalThis" ]
b950b4be3c4afb59ea7f08ab3996ed594b7facbecec94f8c2483bc0b05ff466d
public void testLendsAnnotation3()
// You are a professional Java test case writer, please create a test case named `testLendsAnnotation3` for the issue `Closure-248`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-248 // // ## Issue-Title: // support @lends annotation // // ## Issue-Description: // Some javascript toolkits (dojo, base, etc.) have a special way of declaring (what java calls) classes, for example in dojo: // // dojo.declare("MyClass", [superClass1, superClass2], { // foo: function(){ ... } // bar: function(){ ... } // }); // // JSDoc (or at least JSDoc toolkit) supports this via annotations: // // /\*\* // \* @name MyClass // \* @class // \* @extends superClass1 // \* @extends superClass2 // \*/ // dojo.declare("MyClass", [superClass1, superClass2], /\*\* @lends // MyClass.prototype \*/ { // foo: function(){ ... } // bar: function(){ ... } // }); // // The @lends keyword in particular is useful since it tells JSDoc that foo and bar are part of MyClass's prototype. But closure compiler isn't picking up on that, thus I get a bunch of errors about "dangerous use of this" inside of foo() and bar(). // // So, can @lends support be added to the closure compiler? // // The workaround is to use @this on every method, but not sure if that is sufficient to make advanced mode compilation work correctly. // //
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 testIssue182a() { testFailure("var NS = {read: function() { return this.foo; }};"); } public void testIssue182b() { testFailure("var NS = {write: function() { this.foo = 3; }};"); } public void testIssue182c() { testFailure("var NS = {}; NS.write2 = function() { this.foo = 3; };"); } public void testIssue182d() { testSame("function Foo() {} " + "Foo.prototype = {write: function() { this.foo = 3; }};"); } public void testLendsAnnotation1() { testFailure("/** @constructor */ function F() {}" + "dojo.declare(F, {foo: function() { return this.foo; }});"); } public void testLendsAnnotation2() { testFailure("/** @constructor */ function F() {}" + "dojo.declare(F, /** @lends {F.bar} */ (" + " {foo: function() { return this.foo; }}));"); } public void testLendsAnnotation3() { testSame("/** @constructor */ function F() {}" + "dojo.declare(F, /** @lends {F.prototype} */ (" + " {foo: function() { return this.foo; }}));"); } }
public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); }
com.google.javascript.jscomp.PeepholeFoldConstantsTest::testFoldBitShifts
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
287
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
testFoldBitShifts
/* * Copyright 2004 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; /** * Tests for PeepholeFoldConstants in isolation. Tests for the interaction of * multiple peephole passes are in PeepholeIntegrationTest. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUnaryOps() { fold("!foo()", "foo()"); fold("~foo()", "foo()"); fold("-foo()", "foo()"); fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // surprisingly unfoldable fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // foldable, analogous to if(). fold("a = x || false ? b : c", "a=x?b:c"); fold("a = x && true ? b : c", "a=x?b:c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1&1.1"); fold("x = 1.1 & 1", "x = 1.1&1"); fold("x = 1 & 3000000000", "x = 1&3000000000"); fold("x = 3000000000 & 1", "x = 3000000000&1"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1|1.1"); fold("x = 1 | 3000000000", "x = 1|3000000000"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = \"\"+[]"); // cannot fold (but nice if we can) } public void testStringIndexOf() { fold("x = 'abcdef'.indexOf('b')", "x = 1"); fold("x = 'abcdefbe'.indexOf('b', 2)", "x = 6"); fold("x = 'abcdef'.indexOf('bcd')", "x = 1"); fold("x = 'abcdefsdfasdfbcdassd'.indexOf('bcd', 4)", "x = 13"); fold("x = 'abcdef'.lastIndexOf('b')", "x = 1"); fold("x = 'abcdefbe'.lastIndexOf('b')", "x = 6"); fold("x = 'abcdefbe'.lastIndexOf('b', 5)", "x = 1"); // Both elements must be string. Dont do anything if either one is not // string. fold("x = 'abc1def'.indexOf(1)", "x = 3"); fold("x = 'abcNaNdef'.indexOf(NaN)", "x = 3"); fold("x = 'abcundefineddef'.indexOf(undefined)", "x = 3"); fold("x = 'abcnulldef'.indexOf(null)", "x = 3"); fold("x = 'abctruedef'.indexOf(true)", "x = 3"); // The following testcase fails with JSC_PARSE_ERROR. Hence omitted. // foldSame("x = 1.indexOf('bcd');"); foldSame("x = NaN.indexOf('bcd')"); foldSame("x = undefined.indexOf('bcd')"); foldSame("x = null.indexOf('bcd')"); foldSame("x = true.indexOf('bcd')"); foldSame("x = false.indexOf('bcd')"); // Avoid dealing with regex or other types. foldSame("x = 'abcdef'.indexOf(/b./)"); foldSame("x = 'abcdef'.indexOf({a:2})"); foldSame("x = 'abcdef'.indexOf([1,2])"); } public void testStringJoinAdd() { fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\""); fold("x = [].join(',')", "x = \"\""); fold("x = ['a'].join(',')", "x = \"a\""); fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\""); fold("x = ['a', foo, 'b', 'c'].join(',')", "x = [\"a\",foo,\"b,c\"].join(\",\")"); fold("x = [foo, 'a', 'b', 'c'].join(',')", "x = [foo,\"a,b,c\"].join(\",\")"); fold("x = ['a', 'b', 'c', foo].join(',')", "x = [\"a,b,c\",foo].join(\",\")"); // Works with numbers fold("x = ['a=', 5].join('')", "x = \"a=5\""); fold("x = ['a', '5'].join(7)", "x = \"a75\""); // Works on boolean fold("x = ['a=', false].join('')", "x = \"a=false\""); fold("x = ['a', '5'].join(true)", "x = \"atrue5\""); fold("x = ['a', '5'].join(false)", "x = \"afalse5\""); // Only optimize if it's a size win. fold("x = ['a', '5', 'c'].join('a very very very long chain')", "x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")"); // TODO(user): Its possible to fold this better. foldSame("x = ['', foo].join(',')"); foldSame("x = ['', foo, ''].join(',')"); fold("x = ['', '', foo, ''].join(',')", "x = [',', foo, ''].join(',')"); fold("x = ['', '', foo, '', ''].join(',')", "x = [',', foo, ','].join(',')"); fold("x = ['', '', foo, '', '', bar].join(',')", "x = [',', foo, ',', bar].join(',')"); fold("x = [1,2,3].join('abcdef')", "x = '1abcdef2abcdef3'"); } public void testStringJoinAdd_b1992789() { fold("x = ['a'].join('')", "x = \"a\""); fold("x = [foo()].join('')", "x = '' + foo()"); fold("[foo()].join('')", "'' + foo()"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "", PeepholeFoldConstants.DIVIDE_BY_0_ERROR); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = true == true", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = true === true", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldGetElem() { fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOps() { fold("x=x+y", "x+=y"); fold("x=x*y", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); } }
// You are a professional Java test case writer, please create a test case named `testFoldBitShifts` for the issue `Closure-200`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-200 // // ## Issue-Title: // Unsigned Shift Right (>>>) bug operating on negative numbers // // ## Issue-Description: // **What steps will reproduce the problem?** // i = -1 >>> 0 ; // // **What is the expected output? What do you see instead?** // Expected: i = -1 >>> 0 ; // or // i = 4294967295 ; // Instead: i = -1 ; // // **What version of the product are you using? On what operating system?** // The UI version as of 7/18/2001 (http://closure-compiler.appspot.com/home) // // **Please provide any additional information below.** // -1 >>> 0 == 4294967295 == Math.pow( 2, 32 ) - 1 // Test in any browser and/or See ECMA-262-5 11.7.3 // // public void testFoldBitShifts() {
287
97
239
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
test
```markdown ## Issue-ID: Closure-200 ## Issue-Title: Unsigned Shift Right (>>>) bug operating on negative numbers ## Issue-Description: **What steps will reproduce the problem?** i = -1 >>> 0 ; **What is the expected output? What do you see instead?** Expected: i = -1 >>> 0 ; // or // i = 4294967295 ; Instead: i = -1 ; **What version of the product are you using? On what operating system?** The UI version as of 7/18/2001 (http://closure-compiler.appspot.com/home) **Please provide any additional information below.** -1 >>> 0 == 4294967295 == Math.pow( 2, 32 ) - 1 Test in any browser and/or See ECMA-262-5 11.7.3 ``` You are a professional Java test case writer, please create a test case named `testFoldBitShifts` for the issue `Closure-200`, utilizing the provided issue report information and the following function signature. ```java public void testFoldBitShifts() { ```
239
[ "com.google.javascript.jscomp.PeepholeFoldConstants" ]
ba57a90e4e9b07697922e19e1de6d6e31eadd98d906d54a46f6cf5a0e8531f41
public void testFoldBitShifts()
// You are a professional Java test case writer, please create a test case named `testFoldBitShifts` for the issue `Closure-200`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-200 // // ## Issue-Title: // Unsigned Shift Right (>>>) bug operating on negative numbers // // ## Issue-Description: // **What steps will reproduce the problem?** // i = -1 >>> 0 ; // // **What is the expected output? What do you see instead?** // Expected: i = -1 >>> 0 ; // or // i = 4294967295 ; // Instead: i = -1 ; // // **What version of the product are you using? On what operating system?** // The UI version as of 7/18/2001 (http://closure-compiler.appspot.com/home) // // **Please provide any additional information below.** // -1 >>> 0 == 4294967295 == Math.pow( 2, 32 ) - 1 // Test in any browser and/or See ECMA-262-5 11.7.3 // //
Closure
/* * Copyright 2004 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; /** * Tests for PeepholeFoldConstants in isolation. Tests for the interaction of * multiple peephole passes are in PeepholeIntegrationTest. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUnaryOps() { fold("!foo()", "foo()"); fold("~foo()", "foo()"); fold("-foo()", "foo()"); fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // surprisingly unfoldable fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // foldable, analogous to if(). fold("a = x || false ? b : c", "a=x?b:c"); fold("a = x && true ? b : c", "a=x?b:c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1&1.1"); fold("x = 1.1 & 1", "x = 1.1&1"); fold("x = 1 & 3000000000", "x = 1&3000000000"); fold("x = 3000000000 & 1", "x = 3000000000&1"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1|1.1"); fold("x = 1 | 3000000000", "x = 1|3000000000"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = \"\"+[]"); // cannot fold (but nice if we can) } public void testStringIndexOf() { fold("x = 'abcdef'.indexOf('b')", "x = 1"); fold("x = 'abcdefbe'.indexOf('b', 2)", "x = 6"); fold("x = 'abcdef'.indexOf('bcd')", "x = 1"); fold("x = 'abcdefsdfasdfbcdassd'.indexOf('bcd', 4)", "x = 13"); fold("x = 'abcdef'.lastIndexOf('b')", "x = 1"); fold("x = 'abcdefbe'.lastIndexOf('b')", "x = 6"); fold("x = 'abcdefbe'.lastIndexOf('b', 5)", "x = 1"); // Both elements must be string. Dont do anything if either one is not // string. fold("x = 'abc1def'.indexOf(1)", "x = 3"); fold("x = 'abcNaNdef'.indexOf(NaN)", "x = 3"); fold("x = 'abcundefineddef'.indexOf(undefined)", "x = 3"); fold("x = 'abcnulldef'.indexOf(null)", "x = 3"); fold("x = 'abctruedef'.indexOf(true)", "x = 3"); // The following testcase fails with JSC_PARSE_ERROR. Hence omitted. // foldSame("x = 1.indexOf('bcd');"); foldSame("x = NaN.indexOf('bcd')"); foldSame("x = undefined.indexOf('bcd')"); foldSame("x = null.indexOf('bcd')"); foldSame("x = true.indexOf('bcd')"); foldSame("x = false.indexOf('bcd')"); // Avoid dealing with regex or other types. foldSame("x = 'abcdef'.indexOf(/b./)"); foldSame("x = 'abcdef'.indexOf({a:2})"); foldSame("x = 'abcdef'.indexOf([1,2])"); } public void testStringJoinAdd() { fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\""); fold("x = [].join(',')", "x = \"\""); fold("x = ['a'].join(',')", "x = \"a\""); fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\""); fold("x = ['a', foo, 'b', 'c'].join(',')", "x = [\"a\",foo,\"b,c\"].join(\",\")"); fold("x = [foo, 'a', 'b', 'c'].join(',')", "x = [foo,\"a,b,c\"].join(\",\")"); fold("x = ['a', 'b', 'c', foo].join(',')", "x = [\"a,b,c\",foo].join(\",\")"); // Works with numbers fold("x = ['a=', 5].join('')", "x = \"a=5\""); fold("x = ['a', '5'].join(7)", "x = \"a75\""); // Works on boolean fold("x = ['a=', false].join('')", "x = \"a=false\""); fold("x = ['a', '5'].join(true)", "x = \"atrue5\""); fold("x = ['a', '5'].join(false)", "x = \"afalse5\""); // Only optimize if it's a size win. fold("x = ['a', '5', 'c'].join('a very very very long chain')", "x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")"); // TODO(user): Its possible to fold this better. foldSame("x = ['', foo].join(',')"); foldSame("x = ['', foo, ''].join(',')"); fold("x = ['', '', foo, ''].join(',')", "x = [',', foo, ''].join(',')"); fold("x = ['', '', foo, '', ''].join(',')", "x = [',', foo, ','].join(',')"); fold("x = ['', '', foo, '', '', bar].join(',')", "x = [',', foo, ',', bar].join(',')"); fold("x = [1,2,3].join('abcdef')", "x = '1abcdef2abcdef3'"); } public void testStringJoinAdd_b1992789() { fold("x = ['a'].join('')", "x = \"a\""); fold("x = [foo()].join('')", "x = '' + foo()"); fold("[foo()].join('')", "'' + foo()"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "", PeepholeFoldConstants.DIVIDE_BY_0_ERROR); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = true == true", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = true === true", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldGetElem() { fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOps() { fold("x=x+y", "x+=y"); fold("x=x*y", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); } }
@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())); }
org.jsoup.parser.HtmlParserTest::handlesKnownEmptyBlocks
src/test/java/org/jsoup/parser/HtmlParserTest.java
331
src/test/java/org/jsoup/parser/HtmlParserTest.java
handlesKnownEmptyBlocks
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.*; import org.jsoup.select.Elements; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** Tests for the Parser @author Jonathan Hedley, [email protected] */ 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 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 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></noscript></head><body><img src=\"foo\" /><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 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); // modifies output only to clarify test assertEquals(StringUtil.normaliseWhitespace("&amp; &quot; &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())); } }
// You are a professional Java test case writer, please create a test case named `handlesKnownEmptyBlocks` for the issue `Jsoup-305`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-305 // // ## Issue-Title: // Self-closing script tag causes remainder of document to be html-escaped. // // ## Issue-Description: // When a self-closing script block is encountered it appears that the state transitions do not account for the closing tag, so the rest of the document is considered to be in the body of the script tag, and so is escaped. // // // The unit test HtmlParserTest.handlesKnownEmptyBlocks() will fail if a self-closing script tag is included in the String h. // // // // @Test public void handlesKnownEmptyBlocks() {
331
33
326
src/test/java/org/jsoup/parser/HtmlParserTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-305 ## Issue-Title: Self-closing script tag causes remainder of document to be html-escaped. ## Issue-Description: When a self-closing script block is encountered it appears that the state transitions do not account for the closing tag, so the rest of the document is considered to be in the body of the script tag, and so is escaped. The unit test HtmlParserTest.handlesKnownEmptyBlocks() will fail if a self-closing script tag is included in the String h. ``` You are a professional Java test case writer, please create a test case named `handlesKnownEmptyBlocks` for the issue `Jsoup-305`, utilizing the provided issue report information and the following function signature. ```java @Test public void handlesKnownEmptyBlocks() { ```
326
[ "org.jsoup.parser.HtmlTreeBuilder" ]
baa973bc8cf2d383b6320f2caf89e7b7a4f5954ed1f395b4f013bfd75b4e8395
@Test public void handlesKnownEmptyBlocks()
// You are a professional Java test case writer, please create a test case named `handlesKnownEmptyBlocks` for the issue `Jsoup-305`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-305 // // ## Issue-Title: // Self-closing script tag causes remainder of document to be html-escaped. // // ## Issue-Description: // When a self-closing script block is encountered it appears that the state transitions do not account for the closing tag, so the rest of the document is considered to be in the body of the script tag, and so is escaped. // // // The unit test HtmlParserTest.handlesKnownEmptyBlocks() will fail if a self-closing script tag is included in the String h. // // // //
Jsoup
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.*; import org.jsoup.select.Elements; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** Tests for the Parser @author Jonathan Hedley, [email protected] */ 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 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 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></noscript></head><body><img src=\"foo\" /><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 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); // modifies output only to clarify test assertEquals(StringUtil.normaliseWhitespace("&amp; &quot; &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 testMath864() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { @Override public double value(double[] parameters) { final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; final double[] lower = { -1e6 }; final double[] upper = { 0.5 }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); Assert.assertTrue("Out of bounds (" + result[0] + " > " + upper[0] + ")", result[0] <= upper[0]); }
org.apache.commons.math3.optimization.direct.CMAESOptimizerTest::testMath864
src/test/java/org/apache/commons/math3/optimization/direct/CMAESOptimizerTest.java
401
src/test/java/org/apache/commons/math3/optimization/direct/CMAESOptimizerTest.java
testMath864
/* * 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.direct; import java.util.Arrays; import java.util.Random; import org.apache.commons.math3.Retry; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.optimization.PointValuePair; import org.apache.commons.math3.random.MersenneTwister; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test for {@link CMAESOptimizer}. */ @RunWith(RetryRunner.class) public class CMAESOptimizerTest { static final int DIM = 13; static final int LAMBDA = 4 + (int)(3.*Math.log(DIM)); @Test(expected = NumberIsTooLargeException.class) public void testInitOutofbounds1() { double[] startPoint = point(DIM,3); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NumberIsTooSmallException.class) public void testInitOutofbounds2() { double[] startPoint = point(DIM, -2); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testBoundariesDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM+1,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries1() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1, Double.POSITIVE_INFINITY); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries2() { double[] startPoint = point(DIM, 0.5); double[] insigma = null; final double[] lB = new double[] { -1, -1, -1, -1, -1, Double.NEGATIVE_INFINITY, -1, -1, -1, -1, -1, -1, -1 }; final double[] uB = new double[] { 2, 2, 2, Double.POSITIVE_INFINITY, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; double[][] boundaries = new double[2][]; boundaries[0] = lB; boundaries[1] = uB; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NotPositiveException.class) public void testInputSigmaNegative() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = OutOfRangeException.class) public void testInputSigmaOutOfRange() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM, 1.1); double[][] boundaries = boundaries(DIM,-0.5,0.5); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testInputSigmaDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM+1,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testMaximize() {} // Defects4J: flaky method // public void testMaximize() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),1.0); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, false, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // boundaries = boundaries(DIM,-0.3,0.3); // startPoint = point(DIM,0.1); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // } @Test public void testEllipse() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testElliRotated() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testCigar() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTwoAxes() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-8, 1e-3, 200000, expected); } @Test public void testCigTab() {} // Defects4J: flaky method // @Test // public void testCigTab() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.3); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),0.0); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // } @Test public void testSphere() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTablet() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-8, 1e-1, 100000, expected); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-8, 2e-1, 100000, expected); } @Test public void testSsDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-4, 1e-1, 200000, expected); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-4, 1e-1, 200000, expected); } @Test public void testAckley() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,1.0); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-9, 1e-5, 100000, expected); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-9, 1e-5, 100000, expected); } @Test public void testRastrigin() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), false, 0, 1e-13, 1e-13, 1e-6, 200000, expected); } @Test public void testConstrainedRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiagonalRosen() {} // Defects4J: flaky method // @Test // public void testDiagonalRosen() { // double[] startPoint = point(DIM,0.1); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,1.0),0.0); // doTest(new Rosen(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 1, 1e-13, // 1e-10, 1e-4, 1000000, expected); // } @Test public void testMath864() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { @Override public double value(double[] parameters) { final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; final double[] lower = { -1e6 }; final double[] upper = { 0.5 }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); Assert.assertTrue("Out of bounds (" + result[0] + " > " + upper[0] + ")", result[0] <= upper[0]); } /** * @param func Function to optimize. * @param startPoint Starting point. * @param inSigma Individual input sigma. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param lambda Population size used for offspring. * @param isActive Covariance update mechanism. * @param diagonalOnly Simplified covariance update. * @param stopValue Termination criteria for optimization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[] inSigma, double[][] boundaries, GoalType goal, int lambda, boolean isActive, int diagonalOnly, double stopValue, double fTol, double pointTol, int maxEvaluations, PointValuePair expected) { int dim = startPoint.length; // test diagonalOnly = 0 - slow but normally fewer feval# CMAESOptimizer optim = new CMAESOptimizer( lambda, inSigma, 30000, stopValue, isActive, diagonalOnly, 0, new MersenneTwister(), false); final double[] lB = boundaries == null ? null : boundaries[0]; final double[] uB = boundaries == null ? null : boundaries[1]; PointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); Assert.assertEquals(expected.getValue(), result.getValue(), fTol); for (int i = 0; i < dim; i++) { Assert.assertEquals(expected.getPoint()[i], result.getPoint()[i], pointTol); } } private static double[] point(int n, double value) { double[] ds = new double[n]; Arrays.fill(ds, value); return ds; } private static double[][] boundaries(int dim, double lower, double upper) { double[][] boundaries = new double[2][dim]; for (int i = 0; i < dim; i++) boundaries[0][i] = lower; for (int i = 0; i < dim; i++) boundaries[1][i] = upper; return boundaries; } private static class Sphere implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class Cigar implements MultivariateFunction { private double factor; Cigar() { this(1e3); } Cigar(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += factor * x[i] * x[i]; return f; } } private static class Tablet implements MultivariateFunction { private double factor; Tablet() { this(1e3); } Tablet(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = factor * x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class CigTab implements MultivariateFunction { private double factor; CigTab() { this(1e4); } CigTab(double axisratio) { factor = axisratio; } public double value(double[] x) { int end = x.length - 1; double f = x[0] * x[0] / factor + factor * x[end] * x[end]; for (int i = 1; i < end; ++i) f += x[i] * x[i]; return f; } } private static class TwoAxes implements MultivariateFunction { private double factor; TwoAxes() { this(1e6); } TwoAxes(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += (i < x.length / 2 ? factor : 1) * x[i] * x[i]; return f; } } private static class ElliRotated implements MultivariateFunction { private Basis B = new Basis(); private double factor; ElliRotated() { this(1e3); } ElliRotated(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; x = B.Rotate(x); for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class Elli implements MultivariateFunction { private double factor; Elli() { this(1e3); } Elli(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class MinusElli implements MultivariateFunction { public double value(double[] x) { return 1.0-(new Elli().value(x)); } } private static class DiffPow implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(Math.abs(x[i]), 2. + 10 * (double) i / (x.length - 1.)); return f; } } private static class SsDiffPow implements MultivariateFunction { public double value(double[] x) { double f = Math.pow(new DiffPow().value(x), 0.25); return f; } } private static class Rosen implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length - 1; ++i) f += 1e2 * (x[i] * x[i] - x[i + 1]) * (x[i] * x[i] - x[i + 1]) + (x[i] - 1.) * (x[i] - 1.); return f; } } private static class Ackley implements MultivariateFunction { private double axisratio; Ackley(double axra) { axisratio = axra; } public Ackley() { this(1); } public double value(double[] x) { double f = 0; double res2 = 0; double fac = 0; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); f += fac * fac * x[i] * x[i]; res2 += Math.cos(2. * Math.PI * fac * x[i]); } f = (20. - 20. * Math.exp(-0.2 * Math.sqrt(f / x.length)) + Math.exp(1.) - Math.exp(res2 / x.length)); return f; } } private static class Rastrigin implements MultivariateFunction { private double axisratio; private double amplitude; Rastrigin() { this(1, 10); } Rastrigin(double axisratio, double amplitude) { this.axisratio = axisratio; this.amplitude = amplitude; } public double value(double[] x) { double f = 0; double fac; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); if (i == 0 && x[i] < 0) fac *= 1.; f += fac * fac * x[i] * x[i] + amplitude * (1. - Math.cos(2. * Math.PI * fac * x[i])); } return f; } } private static class Basis { double[][] basis; Random rand = new Random(2); // use not always the same basis double[] Rotate(double[] x) { GenBasis(x.length); double[] y = new double[x.length]; for (int i = 0; i < x.length; ++i) { y[i] = 0; for (int j = 0; j < x.length; ++j) y[i] += basis[i][j] * x[j]; } return y; } void GenBasis(int DIM) { if (basis != null ? basis.length == DIM : false) return; double sp; int i, j, k; /* generate orthogonal basis */ basis = new double[DIM][DIM]; for (i = 0; i < DIM; ++i) { /* sample components gaussian */ for (j = 0; j < DIM; ++j) basis[i][j] = rand.nextGaussian(); /* substract projection of previous vectors */ for (j = i - 1; j >= 0; --j) { for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[j][k]; /* scalar product */ for (k = 0; k < DIM; ++k) basis[i][k] -= sp * basis[j][k]; /* substract */ } /* normalize */ for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[i][k]; /* squared norm */ for (k = 0; k < DIM; ++k) basis[i][k] /= Math.sqrt(sp); } } } }
// You are a professional Java test case writer, please create a test case named `testMath864` for the issue `Math-MATH-864`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-864 // // ## Issue-Title: // CMAESOptimizer does not enforce bounds // // ## Issue-Description: // // The CMAESOptimizer can exceed the bounds passed to optimize. Looking at the generationLoop in doOptimize(), it does a bounds check by calling isFeasible() but if checkFeasableCount is zero (the default) then isFeasible() is never even called. Also, even with non-zero checkFeasableCount it may give up before finding an in-bounds offspring and go forward with an out-of-bounds offspring. This is against svn revision 1387637. I can provide an example program where the optimizer ends up with a fit outside the prescribed bounds if that would help. // // // // // @Test public void testMath864() {
401
// } // 1e-10, 1e-4, 1000000, expected); // GoalType.MINIMIZE, LAMBDA, false, 1, 1e-13, // doTest(new Rosen(), startPoint, insigma, boundaries, // new PointValuePair(point(DIM,1.0),0.0); // PointValuePair expected = // double[][] boundaries = null; // double[] insigma = point(DIM,0.1); // double[] startPoint = point(DIM,0.1); // public void testDiagonalRosen() { // @Test // Defects4J: flaky method
20
382
src/test/java/org/apache/commons/math3/optimization/direct/CMAESOptimizerTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-864 ## Issue-Title: CMAESOptimizer does not enforce bounds ## Issue-Description: The CMAESOptimizer can exceed the bounds passed to optimize. Looking at the generationLoop in doOptimize(), it does a bounds check by calling isFeasible() but if checkFeasableCount is zero (the default) then isFeasible() is never even called. Also, even with non-zero checkFeasableCount it may give up before finding an in-bounds offspring and go forward with an out-of-bounds offspring. This is against svn revision 1387637. I can provide an example program where the optimizer ends up with a fit outside the prescribed bounds if that would help. ``` You are a professional Java test case writer, please create a test case named `testMath864` for the issue `Math-MATH-864`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMath864() { ```
382
[ "org.apache.commons.math3.optimization.direct.CMAESOptimizer" ]
bcc3bde3a6903cad91ecda2023d882ad73e6195695655bdd38398de5dd48056a
@Test public void testMath864()
// You are a professional Java test case writer, please create a test case named `testMath864` for the issue `Math-MATH-864`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-864 // // ## Issue-Title: // CMAESOptimizer does not enforce bounds // // ## Issue-Description: // // The CMAESOptimizer can exceed the bounds passed to optimize. Looking at the generationLoop in doOptimize(), it does a bounds check by calling isFeasible() but if checkFeasableCount is zero (the default) then isFeasible() is never even called. Also, even with non-zero checkFeasableCount it may give up before finding an in-bounds offspring and go forward with an out-of-bounds offspring. This is against svn revision 1387637. I can provide an example program where the optimizer ends up with a fit outside the prescribed bounds if that would help. // // // // //
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.direct; import java.util.Arrays; import java.util.Random; import org.apache.commons.math3.Retry; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.optimization.PointValuePair; import org.apache.commons.math3.random.MersenneTwister; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test for {@link CMAESOptimizer}. */ @RunWith(RetryRunner.class) public class CMAESOptimizerTest { static final int DIM = 13; static final int LAMBDA = 4 + (int)(3.*Math.log(DIM)); @Test(expected = NumberIsTooLargeException.class) public void testInitOutofbounds1() { double[] startPoint = point(DIM,3); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NumberIsTooSmallException.class) public void testInitOutofbounds2() { double[] startPoint = point(DIM, -2); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testBoundariesDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM+1,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries1() { double[] startPoint = point(DIM,0.5); double[] insigma = null; double[][] boundaries = boundaries(DIM,-1, Double.POSITIVE_INFINITY); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = MathUnsupportedOperationException.class) public void testUnsupportedBoundaries2() { double[] startPoint = point(DIM, 0.5); double[] insigma = null; final double[] lB = new double[] { -1, -1, -1, -1, -1, Double.NEGATIVE_INFINITY, -1, -1, -1, -1, -1, -1, -1 }; final double[] uB = new double[] { 2, 2, 2, Double.POSITIVE_INFINITY, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; double[][] boundaries = new double[2][]; boundaries[0] = lB; boundaries[1] = uB; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = NotPositiveException.class) public void testInputSigmaNegative() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = OutOfRangeException.class) public void testInputSigmaOutOfRange() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM, 1.1); double[][] boundaries = boundaries(DIM,-0.5,0.5); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test(expected = DimensionMismatchException.class) public void testInputSigmaDimensionMismatch() { double[] startPoint = point(DIM,0.5); double[] insigma = point(DIM+1,-0.5); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test @Retry(3) public void testMaximize() {} // Defects4J: flaky method // public void testMaximize() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),1.0); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, false, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // boundaries = boundaries(DIM,-0.3,0.3); // startPoint = point(DIM,0.1); // doTest(new MinusElli(), startPoint, insigma, boundaries, // GoalType.MAXIMIZE, LAMBDA, true, 0, 1.0-1e-13, // 2e-10, 5e-6, 100000, expected); // } @Test public void testEllipse() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Elli(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testElliRotated() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new ElliRotated(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testCigar() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Cigar(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTwoAxes() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new TwoAxes(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-8, 1e-3, 200000, expected); } @Test public void testCigTab() {} // Defects4J: flaky method // @Test // public void testCigTab() { // double[] startPoint = point(DIM,1.0); // double[] insigma = point(DIM,0.3); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,0.0),0.0); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // doTest(new CigTab(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, // 1e-13, 5e-5, 100000, expected); // } @Test public void testSphere() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Sphere(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testTablet() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Tablet(), startPoint, insigma, boundaries, GoalType.MINIMIZE, LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-8, 1e-1, 100000, expected); doTest(new DiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-8, 2e-1, 100000, expected); } @Test public void testSsDiffPow() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, true, 0, 1e-13, 1e-4, 1e-1, 200000, expected); doTest(new SsDiffPow(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 10, false, 0, 1e-13, 1e-4, 1e-1, 200000, expected); } @Test public void testAckley() { double[] startPoint = point(DIM,1.0); double[] insigma = point(DIM,1.0); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-9, 1e-5, 100000, expected); doTest(new Ackley(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-9, 1e-5, 100000, expected); } @Test public void testRastrigin() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = null; PointValuePair expected = new PointValuePair(point(DIM,0.0),0.0); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), true, 0, 1e-13, 1e-13, 1e-6, 200000, expected); doTest(new Rastrigin(), startPoint, insigma, boundaries, GoalType.MINIMIZE, (int)(200*Math.sqrt(DIM)), false, 0, 1e-13, 1e-13, 1e-6, 200000, expected); } @Test public void testConstrainedRosen() { double[] startPoint = point(DIM,0.1); double[] insigma = point(DIM,0.1); double[][] boundaries = boundaries(DIM,-1,2); PointValuePair expected = new PointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, true, 0, 1e-13, 1e-13, 1e-6, 100000, expected); doTest(new Rosen(), startPoint, insigma, boundaries, GoalType.MINIMIZE, 2*LAMBDA, false, 0, 1e-13, 1e-13, 1e-6, 100000, expected); } @Test public void testDiagonalRosen() {} // Defects4J: flaky method // @Test // public void testDiagonalRosen() { // double[] startPoint = point(DIM,0.1); // double[] insigma = point(DIM,0.1); // double[][] boundaries = null; // PointValuePair expected = // new PointValuePair(point(DIM,1.0),0.0); // doTest(new Rosen(), startPoint, insigma, boundaries, // GoalType.MINIMIZE, LAMBDA, false, 1, 1e-13, // 1e-10, 1e-4, 1000000, expected); // } @Test public void testMath864() { final CMAESOptimizer optimizer = new CMAESOptimizer(); final MultivariateFunction fitnessFunction = new MultivariateFunction() { @Override public double value(double[] parameters) { final double target = 1; final double error = target - parameters[0]; return error * error; } }; final double[] start = { 0 }; final double[] lower = { -1e6 }; final double[] upper = { 0.5 }; final double[] result = optimizer.optimize(10000, fitnessFunction, GoalType.MINIMIZE, start, lower, upper).getPoint(); Assert.assertTrue("Out of bounds (" + result[0] + " > " + upper[0] + ")", result[0] <= upper[0]); } /** * @param func Function to optimize. * @param startPoint Starting point. * @param inSigma Individual input sigma. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param lambda Population size used for offspring. * @param isActive Covariance update mechanism. * @param diagonalOnly Simplified covariance update. * @param stopValue Termination criteria for optimization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[] inSigma, double[][] boundaries, GoalType goal, int lambda, boolean isActive, int diagonalOnly, double stopValue, double fTol, double pointTol, int maxEvaluations, PointValuePair expected) { int dim = startPoint.length; // test diagonalOnly = 0 - slow but normally fewer feval# CMAESOptimizer optim = new CMAESOptimizer( lambda, inSigma, 30000, stopValue, isActive, diagonalOnly, 0, new MersenneTwister(), false); final double[] lB = boundaries == null ? null : boundaries[0]; final double[] uB = boundaries == null ? null : boundaries[1]; PointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); Assert.assertEquals(expected.getValue(), result.getValue(), fTol); for (int i = 0; i < dim; i++) { Assert.assertEquals(expected.getPoint()[i], result.getPoint()[i], pointTol); } } private static double[] point(int n, double value) { double[] ds = new double[n]; Arrays.fill(ds, value); return ds; } private static double[][] boundaries(int dim, double lower, double upper) { double[][] boundaries = new double[2][dim]; for (int i = 0; i < dim; i++) boundaries[0][i] = lower; for (int i = 0; i < dim; i++) boundaries[1][i] = upper; return boundaries; } private static class Sphere implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class Cigar implements MultivariateFunction { private double factor; Cigar() { this(1e3); } Cigar(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += factor * x[i] * x[i]; return f; } } private static class Tablet implements MultivariateFunction { private double factor; Tablet() { this(1e3); } Tablet(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = factor * x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class CigTab implements MultivariateFunction { private double factor; CigTab() { this(1e4); } CigTab(double axisratio) { factor = axisratio; } public double value(double[] x) { int end = x.length - 1; double f = x[0] * x[0] / factor + factor * x[end] * x[end]; for (int i = 1; i < end; ++i) f += x[i] * x[i]; return f; } } private static class TwoAxes implements MultivariateFunction { private double factor; TwoAxes() { this(1e6); } TwoAxes(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += (i < x.length / 2 ? factor : 1) * x[i] * x[i]; return f; } } private static class ElliRotated implements MultivariateFunction { private Basis B = new Basis(); private double factor; ElliRotated() { this(1e3); } ElliRotated(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; x = B.Rotate(x); for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class Elli implements MultivariateFunction { private double factor; Elli() { this(1e3); } Elli(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class MinusElli implements MultivariateFunction { public double value(double[] x) { return 1.0-(new Elli().value(x)); } } private static class DiffPow implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(Math.abs(x[i]), 2. + 10 * (double) i / (x.length - 1.)); return f; } } private static class SsDiffPow implements MultivariateFunction { public double value(double[] x) { double f = Math.pow(new DiffPow().value(x), 0.25); return f; } } private static class Rosen implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length - 1; ++i) f += 1e2 * (x[i] * x[i] - x[i + 1]) * (x[i] * x[i] - x[i + 1]) + (x[i] - 1.) * (x[i] - 1.); return f; } } private static class Ackley implements MultivariateFunction { private double axisratio; Ackley(double axra) { axisratio = axra; } public Ackley() { this(1); } public double value(double[] x) { double f = 0; double res2 = 0; double fac = 0; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); f += fac * fac * x[i] * x[i]; res2 += Math.cos(2. * Math.PI * fac * x[i]); } f = (20. - 20. * Math.exp(-0.2 * Math.sqrt(f / x.length)) + Math.exp(1.) - Math.exp(res2 / x.length)); return f; } } private static class Rastrigin implements MultivariateFunction { private double axisratio; private double amplitude; Rastrigin() { this(1, 10); } Rastrigin(double axisratio, double amplitude) { this.axisratio = axisratio; this.amplitude = amplitude; } public double value(double[] x) { double f = 0; double fac; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); if (i == 0 && x[i] < 0) fac *= 1.; f += fac * fac * x[i] * x[i] + amplitude * (1. - Math.cos(2. * Math.PI * fac * x[i])); } return f; } } private static class Basis { double[][] basis; Random rand = new Random(2); // use not always the same basis double[] Rotate(double[] x) { GenBasis(x.length); double[] y = new double[x.length]; for (int i = 0; i < x.length; ++i) { y[i] = 0; for (int j = 0; j < x.length; ++j) y[i] += basis[i][j] * x[j]; } return y; } void GenBasis(int DIM) { if (basis != null ? basis.length == DIM : false) return; double sp; int i, j, k; /* generate orthogonal basis */ basis = new double[DIM][DIM]; for (i = 0; i < DIM; ++i) { /* sample components gaussian */ for (j = 0; j < DIM; ++j) basis[i][j] = rand.nextGaussian(); /* substract projection of previous vectors */ for (j = i - 1; j >= 0; --j) { for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[j][k]; /* scalar product */ for (k = 0; k < DIM; ++k) basis[i][k] -= sp * basis[j][k]; /* substract */ } /* normalize */ for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[i][k]; /* squared norm */ for (k = 0; k < DIM; ++k) basis[i][k] /= Math.sqrt(sp); } } } }
@Test public void testIssue631() { final UnivariateRealFunction f = new UnivariateRealFunction() { @Override public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; final UnivariateRealSolver solver = new RegulaFalsiSolver(); final double root = solver.solve(3624, f, 1, 10); Assert.assertEquals(3.4341896575482003, root, 1e-15); }
org.apache.commons.math.analysis.solvers.RegulaFalsiSolverTest::testIssue631
src/test/java/org/apache/commons/math/analysis/solvers/RegulaFalsiSolverTest.java
54
src/test/java/org/apache/commons/math/analysis/solvers/RegulaFalsiSolverTest.java
testIssue631
/* * 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.UnivariateRealFunction; import org.junit.Test; import org.junit.Assert; /** * Test case for {@link RegulaFalsiSolver Regula Falsi} solver. * * @version $Id$ */ public final class RegulaFalsiSolverTest extends BaseSecantSolverAbstractTest { /** {@inheritDoc} */ protected UnivariateRealSolver getSolver() { return new RegulaFalsiSolver(); } /** {@inheritDoc} */ protected int[] getQuinticEvalCounts() { // While the Regula Falsi method guarantees convergence, convergence // may be extremely slow. The last test case does not converge within // even a million iterations. As such, it was disabled. return new int[] {3, 7, 8, 19, 18, 11, 67, 55, 288, 151, -1}; } @Test public void testIssue631() { final UnivariateRealFunction f = new UnivariateRealFunction() { @Override public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; final UnivariateRealSolver solver = new RegulaFalsiSolver(); final double root = solver.solve(3624, f, 1, 10); Assert.assertEquals(3.4341896575482003, root, 1e-15); } }
// You are a professional Java test case writer, please create a test case named `testIssue631` for the issue `Math-MATH-631`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-631 // // ## Issue-Title: // "RegulaFalsiSolver" failure // // ## Issue-Description: // // The following unit test: // // // // // ``` // @Test // public void testBug() { // final UnivariateRealFunction f = new UnivariateRealFunction() { // @Override // public double value(double x) { // return Math.exp(x) - Math.pow(Math.PI, 3.0); // } // }; // // UnivariateRealSolver solver = new RegulaFalsiSolver(); // double root = solver.solve(100, f, 1, 10); // } // // ``` // // // fails with // // // // // ``` // illegal state: maximal count (100) exceeded: evaluations // // ``` // // // Using "PegasusSolver", the answer is found after 17 evaluations. // // // // // @Test public void testIssue631() {
54
51
42
src/test/java/org/apache/commons/math/analysis/solvers/RegulaFalsiSolverTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-631 ## Issue-Title: "RegulaFalsiSolver" failure ## Issue-Description: The following unit test: ``` @Test public void testBug() { final UnivariateRealFunction f = new UnivariateRealFunction() { @Override public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; UnivariateRealSolver solver = new RegulaFalsiSolver(); double root = solver.solve(100, f, 1, 10); } ``` fails with ``` illegal state: maximal count (100) exceeded: evaluations ``` Using "PegasusSolver", the answer is found after 17 evaluations. ``` You are a professional Java test case writer, please create a test case named `testIssue631` for the issue `Math-MATH-631`, utilizing the provided issue report information and the following function signature. ```java @Test public void testIssue631() { ```
42
[ "org.apache.commons.math.analysis.solvers.BaseSecantSolver" ]
bcdfc6d99123654a690cb2e2a55d42b1d948338ce720150f75ec7709951eed87
@Test public void testIssue631()
// You are a professional Java test case writer, please create a test case named `testIssue631` for the issue `Math-MATH-631`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-631 // // ## Issue-Title: // "RegulaFalsiSolver" failure // // ## Issue-Description: // // The following unit test: // // // // // ``` // @Test // public void testBug() { // final UnivariateRealFunction f = new UnivariateRealFunction() { // @Override // public double value(double x) { // return Math.exp(x) - Math.pow(Math.PI, 3.0); // } // }; // // UnivariateRealSolver solver = new RegulaFalsiSolver(); // double root = solver.solve(100, f, 1, 10); // } // // ``` // // // fails with // // // // // ``` // illegal state: maximal count (100) exceeded: evaluations // // ``` // // // Using "PegasusSolver", the answer is found after 17 evaluations. // // // // //
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.UnivariateRealFunction; import org.junit.Test; import org.junit.Assert; /** * Test case for {@link RegulaFalsiSolver Regula Falsi} solver. * * @version $Id$ */ public final class RegulaFalsiSolverTest extends BaseSecantSolverAbstractTest { /** {@inheritDoc} */ protected UnivariateRealSolver getSolver() { return new RegulaFalsiSolver(); } /** {@inheritDoc} */ protected int[] getQuinticEvalCounts() { // While the Regula Falsi method guarantees convergence, convergence // may be extremely slow. The last test case does not converge within // even a million iterations. As such, it was disabled. return new int[] {3, 7, 8, 19, 18, 11, 67, 55, 288, 151, -1}; } @Test public void testIssue631() { final UnivariateRealFunction f = new UnivariateRealFunction() { @Override public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; final UnivariateRealSolver solver = new RegulaFalsiSolver(); final double root = solver.solve(3624, f, 1, 10); Assert.assertEquals(3.4341896575482003, root, 1e-15); } }
public void testReducedFactory_int_int() { Fraction f = null; // zero f = Fraction.getReducedFraction(0, 1); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // normal f = Fraction.getReducedFraction(1, 1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 1); assertEquals(2, f.getNumerator()); assertEquals(1, f.getDenominator()); // improper f = Fraction.getReducedFraction(22, 7); assertEquals(22, f.getNumerator()); assertEquals(7, f.getDenominator()); // negatives f = Fraction.getReducedFraction(-6, 10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(6, -10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(-6, -10); assertEquals(3, f.getNumerator()); assertEquals(5, f.getDenominator()); // zero denominator try { f = Fraction.getReducedFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(-3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // reduced f = Fraction.getReducedFraction(0, 2); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 4); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(15, 10); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(121, 22); assertEquals(11, f.getNumerator()); assertEquals(2, f.getDenominator()); // Extreme values // OK, can reduce before negating f = Fraction.getReducedFraction(-2, Integer.MIN_VALUE); assertEquals(1, f.getNumerator()); assertEquals(-(Integer.MIN_VALUE / 2), f.getDenominator()); // Can't reduce, negation will throw try { f = Fraction.getReducedFraction(-7, Integer.MIN_VALUE); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) {} // LANG-662 f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2); assertEquals(Integer.MIN_VALUE / 2, f.getNumerator()); assertEquals(1, f.getDenominator()); }
org.apache.commons.lang3.math.FractionTest::testReducedFactory_int_int
src/test/java/org/apache/commons/lang3/math/FractionTest.java
337
src/test/java/org/apache/commons/lang3/math/FractionTest.java
testReducedFactory_int_int
/* * 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.math; import junit.framework.TestCase; /** * Test cases for the {@link Fraction} class * * @author Apache Software Foundation * @author C. Scott Ananian * @version $Id$ */ public class FractionTest extends TestCase { private static final int SKIP = 500; //53 public FractionTest(String name) { super(name); } //-------------------------------------------------------------------------- public void testConstants() { assertEquals(0, Fraction.ZERO.getNumerator()); assertEquals(1, Fraction.ZERO.getDenominator()); assertEquals(1, Fraction.ONE.getNumerator()); assertEquals(1, Fraction.ONE.getDenominator()); assertEquals(1, Fraction.ONE_HALF.getNumerator()); assertEquals(2, Fraction.ONE_HALF.getDenominator()); assertEquals(1, Fraction.ONE_THIRD.getNumerator()); assertEquals(3, Fraction.ONE_THIRD.getDenominator()); assertEquals(2, Fraction.TWO_THIRDS.getNumerator()); assertEquals(3, Fraction.TWO_THIRDS.getDenominator()); assertEquals(1, Fraction.ONE_QUARTER.getNumerator()); assertEquals(4, Fraction.ONE_QUARTER.getDenominator()); assertEquals(2, Fraction.TWO_QUARTERS.getNumerator()); assertEquals(4, Fraction.TWO_QUARTERS.getDenominator()); assertEquals(3, Fraction.THREE_QUARTERS.getNumerator()); assertEquals(4, Fraction.THREE_QUARTERS.getDenominator()); assertEquals(1, Fraction.ONE_FIFTH.getNumerator()); assertEquals(5, Fraction.ONE_FIFTH.getDenominator()); assertEquals(2, Fraction.TWO_FIFTHS.getNumerator()); assertEquals(5, Fraction.TWO_FIFTHS.getDenominator()); assertEquals(3, Fraction.THREE_FIFTHS.getNumerator()); assertEquals(5, Fraction.THREE_FIFTHS.getDenominator()); assertEquals(4, Fraction.FOUR_FIFTHS.getNumerator()); assertEquals(5, Fraction.FOUR_FIFTHS.getDenominator()); } public void testFactory_int_int() { Fraction f = null; // zero f = Fraction.getFraction(0, 1); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(0, 2); assertEquals(0, f.getNumerator()); assertEquals(2, f.getDenominator()); // normal f = Fraction.getFraction(1, 1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(2, 1); assertEquals(2, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(23, 345); assertEquals(23, f.getNumerator()); assertEquals(345, f.getDenominator()); // improper f = Fraction.getFraction(22, 7); assertEquals(22, f.getNumerator()); assertEquals(7, f.getDenominator()); // negatives f = Fraction.getFraction(-6, 10); assertEquals(-6, f.getNumerator()); assertEquals(10, f.getDenominator()); f = Fraction.getFraction(6, -10); assertEquals(-6, f.getNumerator()); assertEquals(10, f.getDenominator()); f = Fraction.getFraction(-6, -10); assertEquals(6, f.getNumerator()); assertEquals(10, f.getDenominator()); // zero denominator try { f = Fraction.getFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // very large: can't represent as unsimplified fraction, although try { f = Fraction.getFraction(4, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testFactory_int_int_int() { Fraction f = null; // zero f = Fraction.getFraction(0, 0, 2); assertEquals(0, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction(2, 0, 2); assertEquals(4, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction(0, 1, 2); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); // normal f = Fraction.getFraction(1, 1, 2); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); // negatives try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // negative whole f = Fraction.getFraction(-1, 6, 10); assertEquals(-16, f.getNumerator()); assertEquals(10, f.getDenominator()); try { f = Fraction.getFraction(-1, -6, 10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, 6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // zero denominator try { f = Fraction.getFraction(0, 1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, 2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, -3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Integer.MAX_VALUE, 1, 2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-Integer.MAX_VALUE, 1, 2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // very large f = Fraction.getFraction(-1, 0, Integer.MAX_VALUE); assertEquals(-Integer.MAX_VALUE, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); try { // negative denominators not allowed in this constructor. f = Fraction.getFraction(0, 4, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, 1, Integer.MAX_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, 2, Integer.MAX_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testReducedFactory_int_int() { Fraction f = null; // zero f = Fraction.getReducedFraction(0, 1); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // normal f = Fraction.getReducedFraction(1, 1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 1); assertEquals(2, f.getNumerator()); assertEquals(1, f.getDenominator()); // improper f = Fraction.getReducedFraction(22, 7); assertEquals(22, f.getNumerator()); assertEquals(7, f.getDenominator()); // negatives f = Fraction.getReducedFraction(-6, 10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(6, -10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(-6, -10); assertEquals(3, f.getNumerator()); assertEquals(5, f.getDenominator()); // zero denominator try { f = Fraction.getReducedFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(-3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // reduced f = Fraction.getReducedFraction(0, 2); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 4); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(15, 10); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(121, 22); assertEquals(11, f.getNumerator()); assertEquals(2, f.getDenominator()); // Extreme values // OK, can reduce before negating f = Fraction.getReducedFraction(-2, Integer.MIN_VALUE); assertEquals(1, f.getNumerator()); assertEquals(-(Integer.MIN_VALUE / 2), f.getDenominator()); // Can't reduce, negation will throw try { f = Fraction.getReducedFraction(-7, Integer.MIN_VALUE); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) {} // LANG-662 f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2); assertEquals(Integer.MIN_VALUE / 2, f.getNumerator()); assertEquals(1, f.getDenominator()); } public void testFactory_double() { Fraction f = null; try { f = Fraction.getFraction(Double.NaN); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Double.POSITIVE_INFINITY); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Double.NEGATIVE_INFINITY); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction((double) Integer.MAX_VALUE + 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // zero f = Fraction.getFraction(0.0d); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // one f = Fraction.getFraction(1.0d); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); // one half f = Fraction.getFraction(0.5d); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); // negative f = Fraction.getFraction(-0.875d); assertEquals(-7, f.getNumerator()); assertEquals(8, f.getDenominator()); // over 1 f = Fraction.getFraction(1.25d); assertEquals(5, f.getNumerator()); assertEquals(4, f.getDenominator()); // two thirds f = Fraction.getFraction(0.66666d); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); // small f = Fraction.getFraction(1.0d/10001d); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // normal Fraction f2 = null; for (int i = 1; i <= 100; i++) { // denominator for (int j = 1; j <= i; j++) { // numerator try { f = Fraction.getFraction((double) j / (double) i); } catch (ArithmeticException ex) { System.err.println(j + " " + i); throw ex; } f2 = Fraction.getReducedFraction(j, i); assertEquals(f2.getNumerator(), f.getNumerator()); assertEquals(f2.getDenominator(), f.getDenominator()); } } // save time by skipping some tests! ( for (int i = 1001; i <= 10000; i+=SKIP) { // denominator for (int j = 1; j <= i; j++) { // numerator try { f = Fraction.getFraction((double) j / (double) i); } catch (ArithmeticException ex) { System.err.println(j + " " + i); throw ex; } f2 = Fraction.getReducedFraction(j, i); assertEquals(f2.getNumerator(), f.getNumerator()); assertEquals(f2.getDenominator(), f.getDenominator()); } } } public void testFactory_String() { try { Fraction.getFraction(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testFactory_String_double() { Fraction f = null; f = Fraction.getFraction("0.0"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("0.2"); assertEquals(1, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("0.5"); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("0.66666"); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); try { f = Fraction.getFraction("2.3R"); fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2147483648"); // too big fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("."); fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testFactory_String_proper() { Fraction f = null; f = Fraction.getFraction("0 0/1"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("1 1/5"); assertEquals(6, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("7 1/2"); assertEquals(15, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("1 2/4"); assertEquals(6, f.getNumerator()); assertEquals(4, f.getDenominator()); f = Fraction.getFraction("-7 1/2"); assertEquals(-15, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("-1 2/4"); assertEquals(-6, f.getNumerator()); assertEquals(4, f.getDenominator()); try { f = Fraction.getFraction("2 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("a 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2 b/4"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2 "); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction(" 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction(" "); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testFactory_String_improper() { Fraction f = null; f = Fraction.getFraction("0/1"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("1/5"); assertEquals(1, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("1/2"); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("2/3"); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction("7/3"); assertEquals(7, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction("2/4"); assertEquals(2, f.getNumerator()); assertEquals(4, f.getDenominator()); try { f = Fraction.getFraction("2/d"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2e/3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2/"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("/"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testGets() { Fraction f = null; f = Fraction.getFraction(3, 5, 6); assertEquals(23, f.getNumerator()); assertEquals(3, f.getProperWhole()); assertEquals(5, f.getProperNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(-3, 5, 6); assertEquals(-23, f.getNumerator()); assertEquals(-3, f.getProperWhole()); assertEquals(5, f.getProperNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(Integer.MIN_VALUE, f.getProperWhole()); assertEquals(0, f.getProperNumerator()); assertEquals(1, f.getDenominator()); } public void testConversions() { Fraction f = null; f = Fraction.getFraction(3, 7, 8); assertEquals(3, f.intValue()); assertEquals(3L, f.longValue()); assertEquals(3.875f, f.floatValue(), 0.00001f); assertEquals(3.875d, f.doubleValue(), 0.00001d); } public void testReduce() { Fraction f = null; f = Fraction.getFraction(50, 75); Fraction result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(-2, -3); result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(2, -3); result = f.reduce(); assertEquals(-2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(-2, 3); result = f.reduce(); assertEquals(-2, result.getNumerator()); assertEquals(3, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(2, 3); result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(0, 1); result = f.reduce(); assertEquals(0, result.getNumerator()); assertEquals(1, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(0, 100); result = f.reduce(); assertEquals(0, result.getNumerator()); assertEquals(1, result.getDenominator()); assertSame(result, Fraction.ZERO); f = Fraction.getFraction(Integer.MIN_VALUE, 2); result = f.reduce(); assertEquals(Integer.MIN_VALUE / 2, result.getNumerator()); assertEquals(1, result.getDenominator()); } public void testInvert() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.invert(); assertEquals(75, f.getNumerator()); assertEquals(50, f.getDenominator()); f = Fraction.getFraction(4, 3); f = f.invert(); assertEquals(3, f.getNumerator()); assertEquals(4, f.getDenominator()); f = Fraction.getFraction(-15, 47); f = f.invert(); assertEquals(-47, f.getNumerator()); assertEquals(15, f.getDenominator()); f = Fraction.getFraction(0, 3); try { f = f.invert(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // large values f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.invert(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f = Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.invert(); assertEquals(1, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); } public void testNegate() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.negate(); assertEquals(-50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(-50, 75); f = f.negate(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); // large values f = Fraction.getFraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = f.negate(); assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.negate(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAbs() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.abs(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(-50, 75); f = f.abs(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.abs(); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(Integer.MAX_VALUE, -1); f = f.abs(); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.abs(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testPow() { Fraction f = null; f = Fraction.getFraction(3, 5); assertEquals(Fraction.ONE, f.pow(0)); f = Fraction.getFraction(3, 5); assertSame(f, f.pow(1)); assertEquals(f, f.pow(1)); f = Fraction.getFraction(3, 5); f = f.pow(2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(3); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(-1); assertEquals(5, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(-2); assertEquals(25, f.getNumerator()); assertEquals(9, f.getDenominator()); // check unreduced fractions stay that way. f = Fraction.getFraction(6, 10); assertEquals(Fraction.ONE, f.pow(0)); f = Fraction.getFraction(6, 10); assertEquals(f, f.pow(1)); assertFalse(f.pow(1).equals(Fraction.getFraction(3,5))); f = Fraction.getFraction(6, 10); f = f.pow(2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(3); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(-1); assertEquals(10, f.getNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(-2); assertEquals(25, f.getNumerator()); assertEquals(9, f.getDenominator()); // zero to any positive power is still zero. f = Fraction.getFraction(0, 1231); f = f.pow(1); assertTrue(0==f.compareTo(Fraction.ZERO)); assertEquals(0, f.getNumerator()); assertEquals(1231, f.getDenominator()); f = f.pow(2); assertTrue(0==f.compareTo(Fraction.ZERO)); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // zero to negative powers should throw an exception try { f = f.pow(-1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = f.pow(Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // one to any power is still one. f = Fraction.getFraction(1, 1); f = f.pow(0); assertEquals(f, Fraction.ONE); f = f.pow(1); assertEquals(f, Fraction.ONE); f = f.pow(-1); assertEquals(f, Fraction.ONE); f = f.pow(Integer.MAX_VALUE); assertEquals(f, Fraction.ONE); f = f.pow(Integer.MIN_VALUE); assertEquals(f, Fraction.ONE); f = Fraction.getFraction(Integer.MAX_VALUE, 1); try { f = f.pow(2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // Numerator growing too negative during the pow operation. f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.pow(3); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f = Fraction.getFraction(65536, 1); try { f = f.pow(2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAdd() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 5); f = f1.add(f2); assertEquals(4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.add(f2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(3, 5); f = f1.add(f2); assertEquals(6, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-4, 5); f = f1.add(f2); assertEquals(-1, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 2); f = f1.add(f2); assertEquals(11, f.getNumerator()); assertEquals(10, f.getDenominator()); f1 = Fraction.getFraction(3, 8); f2 = Fraction.getFraction(1, 6); f = f1.add(f2); assertEquals(13, f.getNumerator()); assertEquals(24, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(1, 5); f = f1.add(f2); assertSame(f2, f); f = f2.add(f1); assertSame(f2, f); f1 = Fraction.getFraction(-1, 13*13*2*2); f2 = Fraction.getFraction(-2, 13*17*2); f = f1.add(f2); assertEquals(13*13*17*2*2, f.getDenominator()); assertEquals(-17 - 2*13*2, f.getNumerator()); try { f.add(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = Fraction.getFraction(1,32768*3); f2 = Fraction.getFraction(1,59049); f = f1.add(f2); assertEquals(52451, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f2 = Fraction.ONE_THIRD; f = f1.add(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f = f.add(Fraction.ONE); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = Fraction.getFraction(Integer.MIN_VALUE, 5); f2 = Fraction.getFraction(-1,5); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(3,327680); f2 = Fraction.getFraction(2,59049); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testSubtract() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 5); f = f1.subtract(f2); assertEquals(2, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(7, 5); f2 = Fraction.getFraction(2, 5); f = f1.subtract(f2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(3, 5); f = f1.subtract(f2); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-4, 5); f = f1.subtract(f2); assertEquals(7, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(4, 5); f = f1.subtract(f2); assertEquals(-4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(-4, 5); f = f1.subtract(f2); assertEquals(4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 2); f = f1.subtract(f2); assertEquals(1, f.getNumerator()); assertEquals(10, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(1, 5); f = f2.subtract(f1); assertSame(f2, f); try { f.subtract(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is subtracted naively, it will overflow. // check that it doesn't. f1 = Fraction.getFraction(1,32768*3); f2 = Fraction.getFraction(1,59049); f = f1.subtract(f2); assertEquals(-13085, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f2 = Fraction.ONE_THIRD.negate(); f = f1.subtract(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f2 = Fraction.getFraction(1, Integer.MAX_VALUE - 1); f = f1.subtract(f2); fail("expecting ArithmeticException"); //should overflow } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = Fraction.getFraction(Integer.MIN_VALUE, 5); f2 = Fraction.getFraction(1,5); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(3,327680); f2 = Fraction.getFraction(2,59049); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testMultiply() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.multiplyBy(f2); assertEquals(6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(6, 10); f2 = Fraction.getFraction(6, 10); f = f1.multiplyBy(f2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = f.multiplyBy(f2); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-2, 5); f = f1.multiplyBy(f2); assertEquals(-6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(-3, 5); f2 = Fraction.getFraction(-2, 5); f = f1.multiplyBy(f2); assertEquals(6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(2, 7); f = f1.multiplyBy(f2); assertSame(Fraction.ZERO, f); f1 = Fraction.getFraction(2, 7); f2 = Fraction.ONE; f = f1.multiplyBy(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE, 1); f2 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f = f1.multiplyBy(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.multiplyBy(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.multiplyBy(f1); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = Fraction.getFraction(1, -Integer.MAX_VALUE); f = f1.multiplyBy(f1); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testDivide() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.divideBy(f2); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.ZERO; try { f = f1.divideBy(f2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(2, 7); f = f1.divideBy(f2); assertSame(Fraction.ZERO, f); f1 = Fraction.getFraction(2, 7); f2 = Fraction.ONE; f = f1.divideBy(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.divideBy(null); fail("IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f1.invert()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = Fraction.getFraction(1, -Integer.MAX_VALUE); f = f1.divideBy(f1.invert()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testEquals() { Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); assertEquals(false, f1.equals(null)); assertEquals(false, f1.equals(new Object())); assertEquals(false, f1.equals(new Integer(6))); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); assertEquals(false, f1.equals(f2)); assertEquals(true, f1.equals(f1)); assertEquals(true, f2.equals(f2)); f2 = Fraction.getFraction(3, 5); assertEquals(true, f1.equals(f2)); f2 = Fraction.getFraction(6, 10); assertEquals(false, f1.equals(f2)); } public void testHashCode() { Fraction f1 = Fraction.getFraction(3, 5); Fraction f2 = Fraction.getFraction(3, 5); assertTrue(f1.hashCode() == f2.hashCode()); f2 = Fraction.getFraction(2, 5); assertTrue(f1.hashCode() != f2.hashCode()); f2 = Fraction.getFraction(6, 10); assertTrue(f1.hashCode() != f2.hashCode()); } public void testCompareTo() { Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); assertTrue(f1.compareTo(f1) == 0); try { f1.compareTo(null); fail("expecting NullPointerException"); } catch (NullPointerException ex) {} f2 = Fraction.getFraction(2, 5); assertTrue(f1.compareTo(f2) > 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(4, 5); assertTrue(f1.compareTo(f2) < 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(3, 5); assertTrue(f1.compareTo(f2) == 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(6, 10); assertTrue(f1.compareTo(f2) == 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertTrue(f1.compareTo(f2) > 0); assertTrue(f2.compareTo(f2) == 0); } public void testToString() { Fraction f = null; f = Fraction.getFraction(3, 5); String str = f.toString(); assertEquals("3/5", str); assertSame(str, f.toString()); f = Fraction.getFraction(7, 5); assertEquals("7/5", f.toString()); f = Fraction.getFraction(4, 2); assertEquals("4/2", f.toString()); f = Fraction.getFraction(0, 2); assertEquals("0/2", f.toString()); f = Fraction.getFraction(2, 2); assertEquals("2/2", f.toString()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals("-2147483648/1", f.toString()); f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertEquals("-2147483648/2147483647", f.toString()); } public void testToProperString() { Fraction f = null; f = Fraction.getFraction(3, 5); String str = f.toProperString(); assertEquals("3/5", str); assertSame(str, f.toProperString()); f = Fraction.getFraction(7, 5); assertEquals("1 2/5", f.toProperString()); f = Fraction.getFraction(14, 10); assertEquals("1 4/10", f.toProperString()); f = Fraction.getFraction(4, 2); assertEquals("2", f.toProperString()); f = Fraction.getFraction(0, 2); assertEquals("0", f.toProperString()); f = Fraction.getFraction(2, 2); assertEquals("1", f.toProperString()); f = Fraction.getFraction(-7, 5); assertEquals("-1 2/5", f.toProperString()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals("-2147483648", f.toProperString()); f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertEquals("-1 1/2147483647", f.toProperString()); assertEquals("-1", Fraction.getFraction(-1).toProperString()); } }
// You are a professional Java test case writer, please create a test case named `testReducedFactory_int_int` for the issue `Lang-LANG-662`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-662 // // ## Issue-Title: // org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k) // // ## Issue-Description: // // The greatestCommonDivisor method in class Fraction does not find the gcd of Integer.MIN\_VALUE and 2^k, and this case can be triggered by taking Integer.MIN\_VALUE as the numerator. Note that the case of taking Integer.MIN\_VALUE as the denominator is handled explicitly in the getReducedFraction factory method. // // // **FractionTest.java** // // ``` // // additional test cases // public void testReducedFactory_int_int() { // // ... // f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2); // assertEquals(Integer.MIN_VALUE / 2, f.getNumerator()); // assertEquals(1, f.getDenominator()); // // public void testReduce() { // // ... // f = Fraction.getFraction(Integer.MIN_VALUE, 2); // result = f.reduce(); // assertEquals(Integer.MIN_VALUE / 2, result.getNumerator()); // assertEquals(1, result.getDenominator()); // // ``` // // // // // public void testReducedFactory_int_int() {
337
22
249
src/test/java/org/apache/commons/lang3/math/FractionTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-662 ## Issue-Title: org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k) ## Issue-Description: The greatestCommonDivisor method in class Fraction does not find the gcd of Integer.MIN\_VALUE and 2^k, and this case can be triggered by taking Integer.MIN\_VALUE as the numerator. Note that the case of taking Integer.MIN\_VALUE as the denominator is handled explicitly in the getReducedFraction factory method. **FractionTest.java** ``` // additional test cases public void testReducedFactory_int_int() { // ... f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2); assertEquals(Integer.MIN_VALUE / 2, f.getNumerator()); assertEquals(1, f.getDenominator()); public void testReduce() { // ... f = Fraction.getFraction(Integer.MIN_VALUE, 2); result = f.reduce(); assertEquals(Integer.MIN_VALUE / 2, result.getNumerator()); assertEquals(1, result.getDenominator()); ``` ``` You are a professional Java test case writer, please create a test case named `testReducedFactory_int_int` for the issue `Lang-LANG-662`, utilizing the provided issue report information and the following function signature. ```java public void testReducedFactory_int_int() { ```
249
[ "org.apache.commons.lang3.math.Fraction" ]
bdb7d5eed32a3133919fdeebbaa0e393fb3787de236c722b69fd7cb21dcf2f5d
public void testReducedFactory_int_int()
// You are a professional Java test case writer, please create a test case named `testReducedFactory_int_int` for the issue `Lang-LANG-662`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-662 // // ## Issue-Title: // org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k) // // ## Issue-Description: // // The greatestCommonDivisor method in class Fraction does not find the gcd of Integer.MIN\_VALUE and 2^k, and this case can be triggered by taking Integer.MIN\_VALUE as the numerator. Note that the case of taking Integer.MIN\_VALUE as the denominator is handled explicitly in the getReducedFraction factory method. // // // **FractionTest.java** // // ``` // // additional test cases // public void testReducedFactory_int_int() { // // ... // f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2); // assertEquals(Integer.MIN_VALUE / 2, f.getNumerator()); // assertEquals(1, f.getDenominator()); // // public void testReduce() { // // ... // f = Fraction.getFraction(Integer.MIN_VALUE, 2); // result = f.reduce(); // assertEquals(Integer.MIN_VALUE / 2, result.getNumerator()); // assertEquals(1, result.getDenominator()); // // ``` // // // // //
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.math; import junit.framework.TestCase; /** * Test cases for the {@link Fraction} class * * @author Apache Software Foundation * @author C. Scott Ananian * @version $Id$ */ public class FractionTest extends TestCase { private static final int SKIP = 500; //53 public FractionTest(String name) { super(name); } //-------------------------------------------------------------------------- public void testConstants() { assertEquals(0, Fraction.ZERO.getNumerator()); assertEquals(1, Fraction.ZERO.getDenominator()); assertEquals(1, Fraction.ONE.getNumerator()); assertEquals(1, Fraction.ONE.getDenominator()); assertEquals(1, Fraction.ONE_HALF.getNumerator()); assertEquals(2, Fraction.ONE_HALF.getDenominator()); assertEquals(1, Fraction.ONE_THIRD.getNumerator()); assertEquals(3, Fraction.ONE_THIRD.getDenominator()); assertEquals(2, Fraction.TWO_THIRDS.getNumerator()); assertEquals(3, Fraction.TWO_THIRDS.getDenominator()); assertEquals(1, Fraction.ONE_QUARTER.getNumerator()); assertEquals(4, Fraction.ONE_QUARTER.getDenominator()); assertEquals(2, Fraction.TWO_QUARTERS.getNumerator()); assertEquals(4, Fraction.TWO_QUARTERS.getDenominator()); assertEquals(3, Fraction.THREE_QUARTERS.getNumerator()); assertEquals(4, Fraction.THREE_QUARTERS.getDenominator()); assertEquals(1, Fraction.ONE_FIFTH.getNumerator()); assertEquals(5, Fraction.ONE_FIFTH.getDenominator()); assertEquals(2, Fraction.TWO_FIFTHS.getNumerator()); assertEquals(5, Fraction.TWO_FIFTHS.getDenominator()); assertEquals(3, Fraction.THREE_FIFTHS.getNumerator()); assertEquals(5, Fraction.THREE_FIFTHS.getDenominator()); assertEquals(4, Fraction.FOUR_FIFTHS.getNumerator()); assertEquals(5, Fraction.FOUR_FIFTHS.getDenominator()); } public void testFactory_int_int() { Fraction f = null; // zero f = Fraction.getFraction(0, 1); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(0, 2); assertEquals(0, f.getNumerator()); assertEquals(2, f.getDenominator()); // normal f = Fraction.getFraction(1, 1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(2, 1); assertEquals(2, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(23, 345); assertEquals(23, f.getNumerator()); assertEquals(345, f.getDenominator()); // improper f = Fraction.getFraction(22, 7); assertEquals(22, f.getNumerator()); assertEquals(7, f.getDenominator()); // negatives f = Fraction.getFraction(-6, 10); assertEquals(-6, f.getNumerator()); assertEquals(10, f.getDenominator()); f = Fraction.getFraction(6, -10); assertEquals(-6, f.getNumerator()); assertEquals(10, f.getDenominator()); f = Fraction.getFraction(-6, -10); assertEquals(6, f.getNumerator()); assertEquals(10, f.getDenominator()); // zero denominator try { f = Fraction.getFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // very large: can't represent as unsimplified fraction, although try { f = Fraction.getFraction(4, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testFactory_int_int_int() { Fraction f = null; // zero f = Fraction.getFraction(0, 0, 2); assertEquals(0, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction(2, 0, 2); assertEquals(4, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction(0, 1, 2); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); // normal f = Fraction.getFraction(1, 1, 2); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); // negatives try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // negative whole f = Fraction.getFraction(-1, 6, 10); assertEquals(-16, f.getNumerator()); assertEquals(10, f.getDenominator()); try { f = Fraction.getFraction(-1, -6, 10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, 6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // zero denominator try { f = Fraction.getFraction(0, 1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, 2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, -3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Integer.MAX_VALUE, 1, 2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-Integer.MAX_VALUE, 1, 2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // very large f = Fraction.getFraction(-1, 0, Integer.MAX_VALUE); assertEquals(-Integer.MAX_VALUE, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); try { // negative denominators not allowed in this constructor. f = Fraction.getFraction(0, 4, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, 1, Integer.MAX_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, 2, Integer.MAX_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testReducedFactory_int_int() { Fraction f = null; // zero f = Fraction.getReducedFraction(0, 1); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // normal f = Fraction.getReducedFraction(1, 1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 1); assertEquals(2, f.getNumerator()); assertEquals(1, f.getDenominator()); // improper f = Fraction.getReducedFraction(22, 7); assertEquals(22, f.getNumerator()); assertEquals(7, f.getDenominator()); // negatives f = Fraction.getReducedFraction(-6, 10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(6, -10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(-6, -10); assertEquals(3, f.getNumerator()); assertEquals(5, f.getDenominator()); // zero denominator try { f = Fraction.getReducedFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(-3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // reduced f = Fraction.getReducedFraction(0, 2); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 4); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(15, 10); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(121, 22); assertEquals(11, f.getNumerator()); assertEquals(2, f.getDenominator()); // Extreme values // OK, can reduce before negating f = Fraction.getReducedFraction(-2, Integer.MIN_VALUE); assertEquals(1, f.getNumerator()); assertEquals(-(Integer.MIN_VALUE / 2), f.getDenominator()); // Can't reduce, negation will throw try { f = Fraction.getReducedFraction(-7, Integer.MIN_VALUE); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) {} // LANG-662 f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2); assertEquals(Integer.MIN_VALUE / 2, f.getNumerator()); assertEquals(1, f.getDenominator()); } public void testFactory_double() { Fraction f = null; try { f = Fraction.getFraction(Double.NaN); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Double.POSITIVE_INFINITY); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Double.NEGATIVE_INFINITY); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction((double) Integer.MAX_VALUE + 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // zero f = Fraction.getFraction(0.0d); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // one f = Fraction.getFraction(1.0d); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); // one half f = Fraction.getFraction(0.5d); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); // negative f = Fraction.getFraction(-0.875d); assertEquals(-7, f.getNumerator()); assertEquals(8, f.getDenominator()); // over 1 f = Fraction.getFraction(1.25d); assertEquals(5, f.getNumerator()); assertEquals(4, f.getDenominator()); // two thirds f = Fraction.getFraction(0.66666d); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); // small f = Fraction.getFraction(1.0d/10001d); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // normal Fraction f2 = null; for (int i = 1; i <= 100; i++) { // denominator for (int j = 1; j <= i; j++) { // numerator try { f = Fraction.getFraction((double) j / (double) i); } catch (ArithmeticException ex) { System.err.println(j + " " + i); throw ex; } f2 = Fraction.getReducedFraction(j, i); assertEquals(f2.getNumerator(), f.getNumerator()); assertEquals(f2.getDenominator(), f.getDenominator()); } } // save time by skipping some tests! ( for (int i = 1001; i <= 10000; i+=SKIP) { // denominator for (int j = 1; j <= i; j++) { // numerator try { f = Fraction.getFraction((double) j / (double) i); } catch (ArithmeticException ex) { System.err.println(j + " " + i); throw ex; } f2 = Fraction.getReducedFraction(j, i); assertEquals(f2.getNumerator(), f.getNumerator()); assertEquals(f2.getDenominator(), f.getDenominator()); } } } public void testFactory_String() { try { Fraction.getFraction(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testFactory_String_double() { Fraction f = null; f = Fraction.getFraction("0.0"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("0.2"); assertEquals(1, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("0.5"); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("0.66666"); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); try { f = Fraction.getFraction("2.3R"); fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2147483648"); // too big fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("."); fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testFactory_String_proper() { Fraction f = null; f = Fraction.getFraction("0 0/1"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("1 1/5"); assertEquals(6, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("7 1/2"); assertEquals(15, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("1 2/4"); assertEquals(6, f.getNumerator()); assertEquals(4, f.getDenominator()); f = Fraction.getFraction("-7 1/2"); assertEquals(-15, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("-1 2/4"); assertEquals(-6, f.getNumerator()); assertEquals(4, f.getDenominator()); try { f = Fraction.getFraction("2 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("a 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2 b/4"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2 "); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction(" 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction(" "); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testFactory_String_improper() { Fraction f = null; f = Fraction.getFraction("0/1"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("1/5"); assertEquals(1, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("1/2"); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("2/3"); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction("7/3"); assertEquals(7, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction("2/4"); assertEquals(2, f.getNumerator()); assertEquals(4, f.getDenominator()); try { f = Fraction.getFraction("2/d"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2e/3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2/"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("/"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testGets() { Fraction f = null; f = Fraction.getFraction(3, 5, 6); assertEquals(23, f.getNumerator()); assertEquals(3, f.getProperWhole()); assertEquals(5, f.getProperNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(-3, 5, 6); assertEquals(-23, f.getNumerator()); assertEquals(-3, f.getProperWhole()); assertEquals(5, f.getProperNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(Integer.MIN_VALUE, f.getProperWhole()); assertEquals(0, f.getProperNumerator()); assertEquals(1, f.getDenominator()); } public void testConversions() { Fraction f = null; f = Fraction.getFraction(3, 7, 8); assertEquals(3, f.intValue()); assertEquals(3L, f.longValue()); assertEquals(3.875f, f.floatValue(), 0.00001f); assertEquals(3.875d, f.doubleValue(), 0.00001d); } public void testReduce() { Fraction f = null; f = Fraction.getFraction(50, 75); Fraction result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(-2, -3); result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(2, -3); result = f.reduce(); assertEquals(-2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(-2, 3); result = f.reduce(); assertEquals(-2, result.getNumerator()); assertEquals(3, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(2, 3); result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(0, 1); result = f.reduce(); assertEquals(0, result.getNumerator()); assertEquals(1, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(0, 100); result = f.reduce(); assertEquals(0, result.getNumerator()); assertEquals(1, result.getDenominator()); assertSame(result, Fraction.ZERO); f = Fraction.getFraction(Integer.MIN_VALUE, 2); result = f.reduce(); assertEquals(Integer.MIN_VALUE / 2, result.getNumerator()); assertEquals(1, result.getDenominator()); } public void testInvert() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.invert(); assertEquals(75, f.getNumerator()); assertEquals(50, f.getDenominator()); f = Fraction.getFraction(4, 3); f = f.invert(); assertEquals(3, f.getNumerator()); assertEquals(4, f.getDenominator()); f = Fraction.getFraction(-15, 47); f = f.invert(); assertEquals(-47, f.getNumerator()); assertEquals(15, f.getDenominator()); f = Fraction.getFraction(0, 3); try { f = f.invert(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // large values f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.invert(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f = Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.invert(); assertEquals(1, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); } public void testNegate() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.negate(); assertEquals(-50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(-50, 75); f = f.negate(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); // large values f = Fraction.getFraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = f.negate(); assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.negate(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAbs() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.abs(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(-50, 75); f = f.abs(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.abs(); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(Integer.MAX_VALUE, -1); f = f.abs(); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.abs(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testPow() { Fraction f = null; f = Fraction.getFraction(3, 5); assertEquals(Fraction.ONE, f.pow(0)); f = Fraction.getFraction(3, 5); assertSame(f, f.pow(1)); assertEquals(f, f.pow(1)); f = Fraction.getFraction(3, 5); f = f.pow(2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(3); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(-1); assertEquals(5, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(-2); assertEquals(25, f.getNumerator()); assertEquals(9, f.getDenominator()); // check unreduced fractions stay that way. f = Fraction.getFraction(6, 10); assertEquals(Fraction.ONE, f.pow(0)); f = Fraction.getFraction(6, 10); assertEquals(f, f.pow(1)); assertFalse(f.pow(1).equals(Fraction.getFraction(3,5))); f = Fraction.getFraction(6, 10); f = f.pow(2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(3); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(-1); assertEquals(10, f.getNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(-2); assertEquals(25, f.getNumerator()); assertEquals(9, f.getDenominator()); // zero to any positive power is still zero. f = Fraction.getFraction(0, 1231); f = f.pow(1); assertTrue(0==f.compareTo(Fraction.ZERO)); assertEquals(0, f.getNumerator()); assertEquals(1231, f.getDenominator()); f = f.pow(2); assertTrue(0==f.compareTo(Fraction.ZERO)); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // zero to negative powers should throw an exception try { f = f.pow(-1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = f.pow(Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // one to any power is still one. f = Fraction.getFraction(1, 1); f = f.pow(0); assertEquals(f, Fraction.ONE); f = f.pow(1); assertEquals(f, Fraction.ONE); f = f.pow(-1); assertEquals(f, Fraction.ONE); f = f.pow(Integer.MAX_VALUE); assertEquals(f, Fraction.ONE); f = f.pow(Integer.MIN_VALUE); assertEquals(f, Fraction.ONE); f = Fraction.getFraction(Integer.MAX_VALUE, 1); try { f = f.pow(2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // Numerator growing too negative during the pow operation. f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.pow(3); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f = Fraction.getFraction(65536, 1); try { f = f.pow(2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAdd() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 5); f = f1.add(f2); assertEquals(4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.add(f2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(3, 5); f = f1.add(f2); assertEquals(6, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-4, 5); f = f1.add(f2); assertEquals(-1, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 2); f = f1.add(f2); assertEquals(11, f.getNumerator()); assertEquals(10, f.getDenominator()); f1 = Fraction.getFraction(3, 8); f2 = Fraction.getFraction(1, 6); f = f1.add(f2); assertEquals(13, f.getNumerator()); assertEquals(24, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(1, 5); f = f1.add(f2); assertSame(f2, f); f = f2.add(f1); assertSame(f2, f); f1 = Fraction.getFraction(-1, 13*13*2*2); f2 = Fraction.getFraction(-2, 13*17*2); f = f1.add(f2); assertEquals(13*13*17*2*2, f.getDenominator()); assertEquals(-17 - 2*13*2, f.getNumerator()); try { f.add(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = Fraction.getFraction(1,32768*3); f2 = Fraction.getFraction(1,59049); f = f1.add(f2); assertEquals(52451, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f2 = Fraction.ONE_THIRD; f = f1.add(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f = f.add(Fraction.ONE); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = Fraction.getFraction(Integer.MIN_VALUE, 5); f2 = Fraction.getFraction(-1,5); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(3,327680); f2 = Fraction.getFraction(2,59049); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testSubtract() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 5); f = f1.subtract(f2); assertEquals(2, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(7, 5); f2 = Fraction.getFraction(2, 5); f = f1.subtract(f2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(3, 5); f = f1.subtract(f2); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-4, 5); f = f1.subtract(f2); assertEquals(7, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(4, 5); f = f1.subtract(f2); assertEquals(-4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(-4, 5); f = f1.subtract(f2); assertEquals(4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 2); f = f1.subtract(f2); assertEquals(1, f.getNumerator()); assertEquals(10, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(1, 5); f = f2.subtract(f1); assertSame(f2, f); try { f.subtract(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is subtracted naively, it will overflow. // check that it doesn't. f1 = Fraction.getFraction(1,32768*3); f2 = Fraction.getFraction(1,59049); f = f1.subtract(f2); assertEquals(-13085, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f2 = Fraction.ONE_THIRD.negate(); f = f1.subtract(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f2 = Fraction.getFraction(1, Integer.MAX_VALUE - 1); f = f1.subtract(f2); fail("expecting ArithmeticException"); //should overflow } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = Fraction.getFraction(Integer.MIN_VALUE, 5); f2 = Fraction.getFraction(1,5); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(3,327680); f2 = Fraction.getFraction(2,59049); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testMultiply() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.multiplyBy(f2); assertEquals(6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(6, 10); f2 = Fraction.getFraction(6, 10); f = f1.multiplyBy(f2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = f.multiplyBy(f2); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-2, 5); f = f1.multiplyBy(f2); assertEquals(-6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(-3, 5); f2 = Fraction.getFraction(-2, 5); f = f1.multiplyBy(f2); assertEquals(6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(2, 7); f = f1.multiplyBy(f2); assertSame(Fraction.ZERO, f); f1 = Fraction.getFraction(2, 7); f2 = Fraction.ONE; f = f1.multiplyBy(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE, 1); f2 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f = f1.multiplyBy(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.multiplyBy(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.multiplyBy(f1); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = Fraction.getFraction(1, -Integer.MAX_VALUE); f = f1.multiplyBy(f1); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testDivide() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.divideBy(f2); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.ZERO; try { f = f1.divideBy(f2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(2, 7); f = f1.divideBy(f2); assertSame(Fraction.ZERO, f); f1 = Fraction.getFraction(2, 7); f2 = Fraction.ONE; f = f1.divideBy(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.divideBy(null); fail("IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f1.invert()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = Fraction.getFraction(1, -Integer.MAX_VALUE); f = f1.divideBy(f1.invert()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testEquals() { Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); assertEquals(false, f1.equals(null)); assertEquals(false, f1.equals(new Object())); assertEquals(false, f1.equals(new Integer(6))); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); assertEquals(false, f1.equals(f2)); assertEquals(true, f1.equals(f1)); assertEquals(true, f2.equals(f2)); f2 = Fraction.getFraction(3, 5); assertEquals(true, f1.equals(f2)); f2 = Fraction.getFraction(6, 10); assertEquals(false, f1.equals(f2)); } public void testHashCode() { Fraction f1 = Fraction.getFraction(3, 5); Fraction f2 = Fraction.getFraction(3, 5); assertTrue(f1.hashCode() == f2.hashCode()); f2 = Fraction.getFraction(2, 5); assertTrue(f1.hashCode() != f2.hashCode()); f2 = Fraction.getFraction(6, 10); assertTrue(f1.hashCode() != f2.hashCode()); } public void testCompareTo() { Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); assertTrue(f1.compareTo(f1) == 0); try { f1.compareTo(null); fail("expecting NullPointerException"); } catch (NullPointerException ex) {} f2 = Fraction.getFraction(2, 5); assertTrue(f1.compareTo(f2) > 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(4, 5); assertTrue(f1.compareTo(f2) < 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(3, 5); assertTrue(f1.compareTo(f2) == 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(6, 10); assertTrue(f1.compareTo(f2) == 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertTrue(f1.compareTo(f2) > 0); assertTrue(f2.compareTo(f2) == 0); } public void testToString() { Fraction f = null; f = Fraction.getFraction(3, 5); String str = f.toString(); assertEquals("3/5", str); assertSame(str, f.toString()); f = Fraction.getFraction(7, 5); assertEquals("7/5", f.toString()); f = Fraction.getFraction(4, 2); assertEquals("4/2", f.toString()); f = Fraction.getFraction(0, 2); assertEquals("0/2", f.toString()); f = Fraction.getFraction(2, 2); assertEquals("2/2", f.toString()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals("-2147483648/1", f.toString()); f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertEquals("-2147483648/2147483647", f.toString()); } public void testToProperString() { Fraction f = null; f = Fraction.getFraction(3, 5); String str = f.toProperString(); assertEquals("3/5", str); assertSame(str, f.toProperString()); f = Fraction.getFraction(7, 5); assertEquals("1 2/5", f.toProperString()); f = Fraction.getFraction(14, 10); assertEquals("1 4/10", f.toProperString()); f = Fraction.getFraction(4, 2); assertEquals("2", f.toProperString()); f = Fraction.getFraction(0, 2); assertEquals("0", f.toProperString()); f = Fraction.getFraction(2, 2); assertEquals("1", f.toProperString()); f = Fraction.getFraction(-7, 5); assertEquals("-1 2/5", f.toProperString()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals("-2147483648", f.toProperString()); f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertEquals("-1 1/2147483647", f.toProperString()); assertEquals("-1", Fraction.getFraction(-1).toProperString()); } }
public void testBug545() { testLocal("var a = {}", ""); testLocal("var a; a = {}", "true"); }
com.google.javascript.jscomp.InlineObjectLiteralsTest::testBug545
test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java
361
test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java
testBug545
/* * Copyright 2011 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; /** * Verifies that valid candidates for object literals are inlined as * expected, and invalid candidates are not touched. * */ public class InlineObjectLiteralsTest extends CompilerTestCase { public InlineObjectLiteralsTest() { enableNormalize(); } @Override public void setUp() { super.enableLineNumberCheck(true); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new InlineObjectLiterals( compiler, compiler.getUniqueNameIdSupplier()); } // Test object literal -> variable inlining public void testObject0() { // Don't mess with global variables, that is the job of CollapseProperties. testSame("var a = {x:1}; f(a.x);"); } public void testObject1() { testLocal("var a = {x:x(), y:y()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=x();" + "var JSCompiler_object_inline_y_1=y();" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject1a() { testLocal("var a; a = {x:x, y:y}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "(JSCompiler_object_inline_x_0=x," + "JSCompiler_object_inline_y_1=y, true);" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject2() { testLocal("var a = {y:y}; a.x = z; f(a.x, a.y);", "var JSCompiler_object_inline_y_0 = y;" + "var JSCompiler_object_inline_x_1;" + "JSCompiler_object_inline_x_1=z;" + "f(JSCompiler_object_inline_x_1, JSCompiler_object_inline_y_0);"); } public void testObject3() { // Inlining the 'y' would cause the 'this' to be different in the // target function. testSameLocal("var a = {y:y,x:x}; a.y(); f(a.x);"); testSameLocal("var a; a = {y:y,x:x}; a.y(); f(a.x);"); } public void testObject4() { // Object literal is escaped. testSameLocal("var a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); testSameLocal("var a; a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); } public void testObject5() { testLocal("var a = {x:x, y:y}; var b = {a:a}; f(b.a.x, b.a.y);", "var a = {x:x, y:y};" + "var JSCompiler_object_inline_a_0=a;" + "f(JSCompiler_object_inline_a_0.x, JSCompiler_object_inline_a_0.y);"); } public void testObject6() { testLocal("for (var i = 0; i < 5; i++) { var a = {i:i,x:x}; f(a.i, a.x); }", "for (var i = 0; i < 5; i++) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("if (c) { var a = {i:i,x:x}; f(a.i, a.x); }", "if (c) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); } public void testObject7() { testLocal("var a = {x:x, y:f()}; g(a.x);", "var JSCompiler_object_inline_x_0=x;" + "var JSCompiler_object_inline_y_1=f();" + "g(JSCompiler_object_inline_x_0)"); } public void testObject8() { testSameLocal("var a = {x:x,y:y}; var b = {x:y}; f((c?a:b).x);"); testLocal("var a; if(c) { a={x:x, y:y}; } else { a={x:y}; } f(a.x);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "if(c) JSCompiler_object_inline_x_0=x," + " JSCompiler_object_inline_y_1=y," + " true;" + "else JSCompiler_object_inline_x_0=y," + " JSCompiler_object_inline_y_1=void 0," + " true;" + "f(JSCompiler_object_inline_x_0)"); testLocal("var a = {x:x,y:y}; var b = {x:y}; c ? f(a.x) : f(b.x);", "var JSCompiler_object_inline_x_0 = x; " + "var JSCompiler_object_inline_y_1 = y; " + "var JSCompiler_object_inline_x_2 = y; " + "c ? f(JSCompiler_object_inline_x_0):f(JSCompiler_object_inline_x_2)"); } public void testObject9() { // There is a call, so no inlining testSameLocal("function f(a,b) {" + " var x = {a:a,b:b}; x.a(); return x.b;" + "}"); testLocal("function f(a,b) {" + " var x = {a:a,b:b}; g(x.a); x = {a:a,b:2}; return x.b;" + "}", "function f(a,b) {" + " var JSCompiler_object_inline_a_0 = a;" + " var JSCompiler_object_inline_b_1 = b;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_a_0 = a," + " JSCompiler_object_inline_b_1=2," + " true;" + " return JSCompiler_object_inline_b_1" + "}"); testLocal("function f(a,b) { " + " var x = {a:a,b:b}; g(x.a); x.b = x.c = 2; return x.b; " + "}", "function f(a,b) { " + " var JSCompiler_object_inline_a_0=a;" + " var JSCompiler_object_inline_b_1=b; " + " var JSCompiler_object_inline_c_2;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_b_1=JSCompiler_object_inline_c_2=2;" + " return JSCompiler_object_inline_b_1" + "}"); } public void testObject10() { testLocal("var x; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var b = f();" + "JSCompiler_object_inline_a_0=a,JSCompiler_object_inline_b_1=b,true;" + "if(JSCompiler_object_inline_a_0) g(JSCompiler_object_inline_b_1)"); testLocal("var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var b=f();" + "JSCompiler_object_inline_a_0=a,JSCompiler_object_inline_b_1=b," + " JSCompiler_object_inline_c_2=void 0,true;" + "if(JSCompiler_object_inline_a_0) " + " g(JSCompiler_object_inline_b_1) + JSCompiler_object_inline_c_2"); testLocal("var x; var b = f(); x = {a:a, b:b}; x.c = c; if(x.a) g(x.b) + x.c", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var b = f();" + "JSCompiler_object_inline_a_0 = a,JSCompiler_object_inline_b_1 = b, " + " JSCompiler_object_inline_c_2=void 0,true;" + "JSCompiler_object_inline_c_2 = c;" + "if (JSCompiler_object_inline_a_0)" + " g(JSCompiler_object_inline_b_1) + JSCompiler_object_inline_c_2;"); testLocal("var x = {a:a}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0 = a;" + "var JSCompiler_object_inline_b_1;" + "if(b) JSCompiler_object_inline_b_1 = b," + " JSCompiler_object_inline_a_0 = void 0," + " true;" + "f(JSCompiler_object_inline_a_0 || JSCompiler_object_inline_b_1)"); testLocal("var x; var y = 5; x = {a:a, b:b, c:c}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var y=5;" + "JSCompiler_object_inline_a_0=a," + "JSCompiler_object_inline_b_1=b," + "JSCompiler_object_inline_c_2=c," + "true;" + "if (b) JSCompiler_object_inline_b_1=b," + " JSCompiler_object_inline_a_0=void 0," + " JSCompiler_object_inline_c_2=void 0," + " true;" + "f(JSCompiler_object_inline_a_0||JSCompiler_object_inline_b_1)"); } public void testObject11() { testSameLocal("var x = {a:b}; (x = {a:a}).c = 5; f(x.a);"); testSameLocal("var x = {a:a}; f(x[a]); g(x[a]);"); } public void testObject12() { testLocal("var a; a = {x:1, y:2}; f(a.x, a.y2);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "var JSCompiler_object_inline_y2_2;" + "JSCompiler_object_inline_x_0=1," + "JSCompiler_object_inline_y_1=2," + "JSCompiler_object_inline_y2_2=void 0," + "true;" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y2_2);"); } public void testObject13() { testSameLocal("var x = {a:1, b:2}; x = {a:3, b:x.a};"); } public void testObject14() { testSameLocal("var x = {a:1}; if ('a' in x) { f(); }"); testSameLocal("var x = {a:1}; for (var y in x) { f(y); }"); } public void testObject15() { testSameLocal("x = x || {}; f(x.a);"); } public void testObject16() { testLocal("function f(e) { bar(); x = {a: foo()}; var x; print(x.a); }", "function f(e) { " + " var JSCompiler_object_inline_a_0;" + " bar();" + " JSCompiler_object_inline_a_0 = foo(), true;" + " print(JSCompiler_object_inline_a_0);" + "}"); } public void testObject17() { // Note: Some day, with careful analysis, these two uses could be // disambiguated, and the second assignment could be inlined. testSameLocal( "var a = {a: function(){}};" + "a.a();" + "a = {a1: 100};" + "print(a.a1);"); } public void testObject18() { testSameLocal("var a,b; b=a={x:x, y:y}; f(b.x);"); } public void testObject19() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(b.x);"); } public void testObject20() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(a.x);"); } public void testObject21() { testSameLocal("var a,b; b=a={x:x, y:y};"); testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; }" + "else { b=a={x:y}; } f(a.x); f(b.x)"); testSameLocal("var a, b; if(c) { if (a={x:x, y:y}) f(); } " + "else { b=a={x:y}; } f(a.x);"); testSameLocal("var a,b; b = (a = {x:x, y:x});"); testSameLocal("var a,b; a = {x:x, y:x}; b = a"); testSameLocal("var a,b; a = {x:x, y:x}; b = x || a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y && a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y ? a : a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y , a"); testSameLocal("b = x || (a = {x:1, y:2});"); } public void testObject22() { testLocal("while(1) { var a = {y:1}; if (b) a.x = 2; f(a.y, a.x);}", "for(;1;){" + " var JSCompiler_object_inline_y_0=1;" + " var JSCompiler_object_inline_x_1;" + " if(b) JSCompiler_object_inline_x_1=2;" + " f(JSCompiler_object_inline_y_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("var a; while (1) { f(a.x, a.y); a = {x:1, y:1};}", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "for(;1;) {" + " f(JSCompiler_object_inline_x_0,JSCompiler_object_inline_y_1);" + " JSCompiler_object_inline_x_0=1," + " JSCompiler_object_inline_y_1=1," + " true" + "}"); } public void testObject23() { testLocal("function f() {\n" + " var templateData = {\n" + " linkIds: {\n" + " CHROME: 'cl',\n" + " DISMISS: 'd'\n" + " }\n" + " };\n" + " var html = templateData.linkIds.CHROME \n" + " + \":\" + templateData.linkIds.DISMISS;\n" + "}", "function f(){" + "var JSCompiler_object_inline_CHROME_1='cl';" + "var JSCompiler_object_inline_DISMISS_2='d';" + "var html=JSCompiler_object_inline_CHROME_1 +" + " ':' +JSCompiler_object_inline_DISMISS_2}"); } public void testObject24() { testLocal("function f() {\n" + " var linkIds = {\n" + " CHROME: 1,\n" + " };\n" + " var g = function () {var o = {a: linkIds};}\n" + "}", "function f(){var linkIds={CHROME:1};" + "var g=function(){var JSCompiler_object_inline_a_0=linkIds}}"); } public void testObject25() { testLocal("var a = {x:f(), y:g()}; a = {y:g(), x:f()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=f();" + "var JSCompiler_object_inline_y_1=g();" + "JSCompiler_object_inline_y_1=g()," + " JSCompiler_object_inline_x_0=f()," + " true;" + "f(JSCompiler_object_inline_x_0,JSCompiler_object_inline_y_1)"); } public void testObject26() { testLocal("var a = {}; a.b = function() {}; new a.b.c", "var JSCompiler_object_inline_b_0;" + "JSCompiler_object_inline_b_0=function(){};" + "new JSCompiler_object_inline_b_0.c"); } public void testBug545() { testLocal("var a = {}", ""); testLocal("var a; a = {}", "true"); } private final String LOCAL_PREFIX = "function local(){"; private final String LOCAL_POSTFIX = "}"; private void testLocal(String code, String result) { test(LOCAL_PREFIX + code + LOCAL_POSTFIX, LOCAL_PREFIX + result + LOCAL_POSTFIX); } private void testSameLocal(String code) { testLocal(code, code); } }
// You are a professional Java test case writer, please create a test case named `testBug545` for the issue `Closure-545`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-545 // // ## Issue-Title: // compiler-20110811 crashes with index(1) must be less than size(1) // // ## Issue-Description: // **What steps will reproduce the problem?** // Run compiler on https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js // // You can copy this into the Appspot closure compiler to see the error: // // ==ClosureCompiler== // // @output\_file\_name default.js // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @code\_url https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js // // ==/ClosureCompiler== // // I've attached a dump of the error from appspot. // // (This is the popular SoundManager library for HTML5 audio) // // **What is the expected output? What do you see instead?** // Got crash... // // **What version of the product are you using? On what operating system?** // Latest (compiler-20110811). We were previously using the June build, and had no problems // // **Please provide any additional information below.** // // public void testBug545() {
361
53
358
test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java
test
```markdown ## Issue-ID: Closure-545 ## Issue-Title: compiler-20110811 crashes with index(1) must be less than size(1) ## Issue-Description: **What steps will reproduce the problem?** Run compiler on https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js You can copy this into the Appspot closure compiler to see the error: // ==ClosureCompiler== // @output\_file\_name default.js // @compilation\_level SIMPLE\_OPTIMIZATIONS // @code\_url https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js // ==/ClosureCompiler== I've attached a dump of the error from appspot. (This is the popular SoundManager library for HTML5 audio) **What is the expected output? What do you see instead?** Got crash... **What version of the product are you using? On what operating system?** Latest (compiler-20110811). We were previously using the June build, and had no problems **Please provide any additional information below.** ``` You are a professional Java test case writer, please create a test case named `testBug545` for the issue `Closure-545`, utilizing the provided issue report information and the following function signature. ```java public void testBug545() { ```
358
[ "com.google.javascript.jscomp.InlineObjectLiterals" ]
be1ae31ec9f9616b9c4924c6cd511324dc84c58b620a99f05e2494b61bca10a9
public void testBug545()
// You are a professional Java test case writer, please create a test case named `testBug545` for the issue `Closure-545`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-545 // // ## Issue-Title: // compiler-20110811 crashes with index(1) must be less than size(1) // // ## Issue-Description: // **What steps will reproduce the problem?** // Run compiler on https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js // // You can copy this into the Appspot closure compiler to see the error: // // ==ClosureCompiler== // // @output\_file\_name default.js // // @compilation\_level SIMPLE\_OPTIMIZATIONS // // @code\_url https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js // // ==/ClosureCompiler== // // I've attached a dump of the error from appspot. // // (This is the popular SoundManager library for HTML5 audio) // // **What is the expected output? What do you see instead?** // Got crash... // // **What version of the product are you using? On what operating system?** // Latest (compiler-20110811). We were previously using the June build, and had no problems // // **Please provide any additional information below.** // //
Closure
/* * Copyright 2011 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; /** * Verifies that valid candidates for object literals are inlined as * expected, and invalid candidates are not touched. * */ public class InlineObjectLiteralsTest extends CompilerTestCase { public InlineObjectLiteralsTest() { enableNormalize(); } @Override public void setUp() { super.enableLineNumberCheck(true); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new InlineObjectLiterals( compiler, compiler.getUniqueNameIdSupplier()); } // Test object literal -> variable inlining public void testObject0() { // Don't mess with global variables, that is the job of CollapseProperties. testSame("var a = {x:1}; f(a.x);"); } public void testObject1() { testLocal("var a = {x:x(), y:y()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=x();" + "var JSCompiler_object_inline_y_1=y();" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject1a() { testLocal("var a; a = {x:x, y:y}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "(JSCompiler_object_inline_x_0=x," + "JSCompiler_object_inline_y_1=y, true);" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y_1);"); } public void testObject2() { testLocal("var a = {y:y}; a.x = z; f(a.x, a.y);", "var JSCompiler_object_inline_y_0 = y;" + "var JSCompiler_object_inline_x_1;" + "JSCompiler_object_inline_x_1=z;" + "f(JSCompiler_object_inline_x_1, JSCompiler_object_inline_y_0);"); } public void testObject3() { // Inlining the 'y' would cause the 'this' to be different in the // target function. testSameLocal("var a = {y:y,x:x}; a.y(); f(a.x);"); testSameLocal("var a; a = {y:y,x:x}; a.y(); f(a.x);"); } public void testObject4() { // Object literal is escaped. testSameLocal("var a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); testSameLocal("var a; a = {y:y}; a.x = z; f(a.x, a.y); g(a);"); } public void testObject5() { testLocal("var a = {x:x, y:y}; var b = {a:a}; f(b.a.x, b.a.y);", "var a = {x:x, y:y};" + "var JSCompiler_object_inline_a_0=a;" + "f(JSCompiler_object_inline_a_0.x, JSCompiler_object_inline_a_0.y);"); } public void testObject6() { testLocal("for (var i = 0; i < 5; i++) { var a = {i:i,x:x}; f(a.i, a.x); }", "for (var i = 0; i < 5; i++) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("if (c) { var a = {i:i,x:x}; f(a.i, a.x); }", "if (c) {" + " var JSCompiler_object_inline_i_0=i;" + " var JSCompiler_object_inline_x_1=x;" + " f(JSCompiler_object_inline_i_0,JSCompiler_object_inline_x_1)" + "}"); } public void testObject7() { testLocal("var a = {x:x, y:f()}; g(a.x);", "var JSCompiler_object_inline_x_0=x;" + "var JSCompiler_object_inline_y_1=f();" + "g(JSCompiler_object_inline_x_0)"); } public void testObject8() { testSameLocal("var a = {x:x,y:y}; var b = {x:y}; f((c?a:b).x);"); testLocal("var a; if(c) { a={x:x, y:y}; } else { a={x:y}; } f(a.x);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "if(c) JSCompiler_object_inline_x_0=x," + " JSCompiler_object_inline_y_1=y," + " true;" + "else JSCompiler_object_inline_x_0=y," + " JSCompiler_object_inline_y_1=void 0," + " true;" + "f(JSCompiler_object_inline_x_0)"); testLocal("var a = {x:x,y:y}; var b = {x:y}; c ? f(a.x) : f(b.x);", "var JSCompiler_object_inline_x_0 = x; " + "var JSCompiler_object_inline_y_1 = y; " + "var JSCompiler_object_inline_x_2 = y; " + "c ? f(JSCompiler_object_inline_x_0):f(JSCompiler_object_inline_x_2)"); } public void testObject9() { // There is a call, so no inlining testSameLocal("function f(a,b) {" + " var x = {a:a,b:b}; x.a(); return x.b;" + "}"); testLocal("function f(a,b) {" + " var x = {a:a,b:b}; g(x.a); x = {a:a,b:2}; return x.b;" + "}", "function f(a,b) {" + " var JSCompiler_object_inline_a_0 = a;" + " var JSCompiler_object_inline_b_1 = b;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_a_0 = a," + " JSCompiler_object_inline_b_1=2," + " true;" + " return JSCompiler_object_inline_b_1" + "}"); testLocal("function f(a,b) { " + " var x = {a:a,b:b}; g(x.a); x.b = x.c = 2; return x.b; " + "}", "function f(a,b) { " + " var JSCompiler_object_inline_a_0=a;" + " var JSCompiler_object_inline_b_1=b; " + " var JSCompiler_object_inline_c_2;" + " g(JSCompiler_object_inline_a_0);" + " JSCompiler_object_inline_b_1=JSCompiler_object_inline_c_2=2;" + " return JSCompiler_object_inline_b_1" + "}"); } public void testObject10() { testLocal("var x; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var b = f();" + "JSCompiler_object_inline_a_0=a,JSCompiler_object_inline_b_1=b,true;" + "if(JSCompiler_object_inline_a_0) g(JSCompiler_object_inline_b_1)"); testLocal("var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var b=f();" + "JSCompiler_object_inline_a_0=a,JSCompiler_object_inline_b_1=b," + " JSCompiler_object_inline_c_2=void 0,true;" + "if(JSCompiler_object_inline_a_0) " + " g(JSCompiler_object_inline_b_1) + JSCompiler_object_inline_c_2"); testLocal("var x; var b = f(); x = {a:a, b:b}; x.c = c; if(x.a) g(x.b) + x.c", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var b = f();" + "JSCompiler_object_inline_a_0 = a,JSCompiler_object_inline_b_1 = b, " + " JSCompiler_object_inline_c_2=void 0,true;" + "JSCompiler_object_inline_c_2 = c;" + "if (JSCompiler_object_inline_a_0)" + " g(JSCompiler_object_inline_b_1) + JSCompiler_object_inline_c_2;"); testLocal("var x = {a:a}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0 = a;" + "var JSCompiler_object_inline_b_1;" + "if(b) JSCompiler_object_inline_b_1 = b," + " JSCompiler_object_inline_a_0 = void 0," + " true;" + "f(JSCompiler_object_inline_a_0 || JSCompiler_object_inline_b_1)"); testLocal("var x; var y = 5; x = {a:a, b:b, c:c}; if (b) x={b:b}; f(x.a||x.b);", "var JSCompiler_object_inline_a_0;" + "var JSCompiler_object_inline_b_1;" + "var JSCompiler_object_inline_c_2;" + "var y=5;" + "JSCompiler_object_inline_a_0=a," + "JSCompiler_object_inline_b_1=b," + "JSCompiler_object_inline_c_2=c," + "true;" + "if (b) JSCompiler_object_inline_b_1=b," + " JSCompiler_object_inline_a_0=void 0," + " JSCompiler_object_inline_c_2=void 0," + " true;" + "f(JSCompiler_object_inline_a_0||JSCompiler_object_inline_b_1)"); } public void testObject11() { testSameLocal("var x = {a:b}; (x = {a:a}).c = 5; f(x.a);"); testSameLocal("var x = {a:a}; f(x[a]); g(x[a]);"); } public void testObject12() { testLocal("var a; a = {x:1, y:2}; f(a.x, a.y2);", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "var JSCompiler_object_inline_y2_2;" + "JSCompiler_object_inline_x_0=1," + "JSCompiler_object_inline_y_1=2," + "JSCompiler_object_inline_y2_2=void 0," + "true;" + "f(JSCompiler_object_inline_x_0, JSCompiler_object_inline_y2_2);"); } public void testObject13() { testSameLocal("var x = {a:1, b:2}; x = {a:3, b:x.a};"); } public void testObject14() { testSameLocal("var x = {a:1}; if ('a' in x) { f(); }"); testSameLocal("var x = {a:1}; for (var y in x) { f(y); }"); } public void testObject15() { testSameLocal("x = x || {}; f(x.a);"); } public void testObject16() { testLocal("function f(e) { bar(); x = {a: foo()}; var x; print(x.a); }", "function f(e) { " + " var JSCompiler_object_inline_a_0;" + " bar();" + " JSCompiler_object_inline_a_0 = foo(), true;" + " print(JSCompiler_object_inline_a_0);" + "}"); } public void testObject17() { // Note: Some day, with careful analysis, these two uses could be // disambiguated, and the second assignment could be inlined. testSameLocal( "var a = {a: function(){}};" + "a.a();" + "a = {a1: 100};" + "print(a.a1);"); } public void testObject18() { testSameLocal("var a,b; b=a={x:x, y:y}; f(b.x);"); } public void testObject19() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(b.x);"); } public void testObject20() { testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; } else { b=a={x:y}; } f(a.x);"); } public void testObject21() { testSameLocal("var a,b; b=a={x:x, y:y};"); testSameLocal("var a,b; if(c) { b=a={x:x, y:y}; }" + "else { b=a={x:y}; } f(a.x); f(b.x)"); testSameLocal("var a, b; if(c) { if (a={x:x, y:y}) f(); } " + "else { b=a={x:y}; } f(a.x);"); testSameLocal("var a,b; b = (a = {x:x, y:x});"); testSameLocal("var a,b; a = {x:x, y:x}; b = a"); testSameLocal("var a,b; a = {x:x, y:x}; b = x || a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y && a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y ? a : a"); testSameLocal("var a,b; a = {x:x, y:x}; b = y , a"); testSameLocal("b = x || (a = {x:1, y:2});"); } public void testObject22() { testLocal("while(1) { var a = {y:1}; if (b) a.x = 2; f(a.y, a.x);}", "for(;1;){" + " var JSCompiler_object_inline_y_0=1;" + " var JSCompiler_object_inline_x_1;" + " if(b) JSCompiler_object_inline_x_1=2;" + " f(JSCompiler_object_inline_y_0,JSCompiler_object_inline_x_1)" + "}"); testLocal("var a; while (1) { f(a.x, a.y); a = {x:1, y:1};}", "var JSCompiler_object_inline_x_0;" + "var JSCompiler_object_inline_y_1;" + "for(;1;) {" + " f(JSCompiler_object_inline_x_0,JSCompiler_object_inline_y_1);" + " JSCompiler_object_inline_x_0=1," + " JSCompiler_object_inline_y_1=1," + " true" + "}"); } public void testObject23() { testLocal("function f() {\n" + " var templateData = {\n" + " linkIds: {\n" + " CHROME: 'cl',\n" + " DISMISS: 'd'\n" + " }\n" + " };\n" + " var html = templateData.linkIds.CHROME \n" + " + \":\" + templateData.linkIds.DISMISS;\n" + "}", "function f(){" + "var JSCompiler_object_inline_CHROME_1='cl';" + "var JSCompiler_object_inline_DISMISS_2='d';" + "var html=JSCompiler_object_inline_CHROME_1 +" + " ':' +JSCompiler_object_inline_DISMISS_2}"); } public void testObject24() { testLocal("function f() {\n" + " var linkIds = {\n" + " CHROME: 1,\n" + " };\n" + " var g = function () {var o = {a: linkIds};}\n" + "}", "function f(){var linkIds={CHROME:1};" + "var g=function(){var JSCompiler_object_inline_a_0=linkIds}}"); } public void testObject25() { testLocal("var a = {x:f(), y:g()}; a = {y:g(), x:f()}; f(a.x, a.y);", "var JSCompiler_object_inline_x_0=f();" + "var JSCompiler_object_inline_y_1=g();" + "JSCompiler_object_inline_y_1=g()," + " JSCompiler_object_inline_x_0=f()," + " true;" + "f(JSCompiler_object_inline_x_0,JSCompiler_object_inline_y_1)"); } public void testObject26() { testLocal("var a = {}; a.b = function() {}; new a.b.c", "var JSCompiler_object_inline_b_0;" + "JSCompiler_object_inline_b_0=function(){};" + "new JSCompiler_object_inline_b_0.c"); } public void testBug545() { testLocal("var a = {}", ""); testLocal("var a; a = {}", "true"); } private final String LOCAL_PREFIX = "function local(){"; private final String LOCAL_POSTFIX = "}"; private void testLocal(String code, String result) { test(LOCAL_PREFIX + code + LOCAL_POSTFIX, LOCAL_PREFIX + result + LOCAL_POSTFIX); } private void testSameLocal(String code) { testLocal(code, code); } }
public void testPcts() { f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); f.addValue(threeL); f.addValue(threeL); f.addValue(3); f.addValue(threeI); assertEquals("one pct",0.25,f.getPct(1),tolerance); assertEquals("two pct",0.25,f.getPct(Long.valueOf(2)),tolerance); assertEquals("three pct",0.5,f.getPct(threeL),tolerance); // MATH-329 assertEquals("three (Object) pct",0.5,f.getPct((Object) (Integer.valueOf(3))),tolerance); assertEquals("five pct",0,f.getPct(5),tolerance); assertEquals("foo pct",0,f.getPct("foo"),tolerance); assertEquals("one cum pct",0.25,f.getCumPct(1),tolerance); assertEquals("two cum pct",0.50,f.getCumPct(Long.valueOf(2)),tolerance); assertEquals("Integer argument",0.50,f.getCumPct(Integer.valueOf(2)),tolerance); assertEquals("three cum pct",1.0,f.getCumPct(threeL),tolerance); assertEquals("five cum pct",1.0,f.getCumPct(5),tolerance); assertEquals("zero cum pct",0.0,f.getCumPct(0),tolerance); assertEquals("foo cum pct",0,f.getCumPct("foo"),tolerance); }
org.apache.commons.math.stat.FrequencyTest::testPcts
src/test/java/org/apache/commons/math/stat/FrequencyTest.java
157
src/test/java/org/apache/commons/math/stat/FrequencyTest.java
testPcts
/* * 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; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import org.apache.commons.math.TestUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test cases for the {@link Frequency} class. * * @version $Revision$ $Date$ */ public final class FrequencyTest extends TestCase { private long oneL = 1; private long twoL = 2; private long threeL = 3; private int oneI = 1; private int twoI = 2; private int threeI=3; private double tolerance = 10E-15; private Frequency f = null; public FrequencyTest(String name) { super(name); } @Override public void setUp() { f = new Frequency(); } public static Test suite() { TestSuite suite = new TestSuite(FrequencyTest.class); suite.setName("Frequency Tests"); return suite; } /** test freq counts */ public void testCounts() { assertEquals("total count",0,f.getSumFreq()); f.addValue(oneL); f.addValue(twoL); f.addValue(1); f.addValue(oneI); assertEquals("one frequency count",3,f.getCount(1)); assertEquals("two frequency count",1,f.getCount(2)); assertEquals("three frequency count",0,f.getCount(3)); assertEquals("total count",4,f.getSumFreq()); assertEquals("zero cumulative frequency", 0, f.getCumFreq(0)); assertEquals("one cumulative frequency", 3, f.getCumFreq(1)); assertEquals("two cumulative frequency", 4, f.getCumFreq(2)); assertEquals("Integer argument cum freq",4, f.getCumFreq(Integer.valueOf(2))); assertEquals("five cumulative frequency", 4, f.getCumFreq(5)); assertEquals("foo cumulative frequency", 0, f.getCumFreq("foo")); f.clear(); assertEquals("total count",0,f.getSumFreq()); // userguide examples ------------------------------------------------------------------- f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one cumulative frequency", 1 , f.getCount("one")); assertEquals("Z cumulative pct", 0.5, f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct", 1.0, f.getCumPct("z"), tolerance); assertEquals("Ot cumulative pct", 0.25, f.getCumPct("Ot"), tolerance); f.clear(); f = null; Frequency f = new Frequency(); f.addValue(1); f.addValue(Integer.valueOf(1)); f.addValue(Long.valueOf(1)); f.addValue(2); f.addValue(Integer.valueOf(-1)); assertEquals("1 count", 3, f.getCount(1)); assertEquals("1 count", 3, f.getCount(Integer.valueOf(1))); assertEquals("0 cum pct", 0.2, f.getCumPct(0), tolerance); assertEquals("1 pct", 0.6, f.getPct(Integer.valueOf(1)), tolerance); assertEquals("-2 cum pct", 0, f.getCumPct(-2), tolerance); assertEquals("10 cum pct", 1, f.getCumPct(10), tolerance); f = null; f = new Frequency(String.CASE_INSENSITIVE_ORDER); f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one count", 3 , f.getCount("one")); assertEquals("Z cumulative pct -- case insensitive", 1 , f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct -- case insensitive", 1 , f.getCumPct("z"), tolerance); f = null; f = new Frequency(); assertEquals(0L, f.getCount('a')); assertEquals(0L, f.getCumFreq('b')); TestUtils.assertEquals(Double.NaN, f.getPct('a'), 0.0); TestUtils.assertEquals(Double.NaN, f.getCumPct('b'), 0.0); f.addValue('a'); f.addValue('b'); f.addValue('c'); f.addValue('d'); assertEquals(1L, f.getCount('a')); assertEquals(2L, f.getCumFreq('b')); assertEquals(0.25, f.getPct('a'), 0.0); assertEquals(0.5, f.getCumPct('b'), 0.0); assertEquals(1.0, f.getCumPct('e'), 0.0); } /** test pcts */ public void testPcts() { f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); f.addValue(threeL); f.addValue(threeL); f.addValue(3); f.addValue(threeI); assertEquals("one pct",0.25,f.getPct(1),tolerance); assertEquals("two pct",0.25,f.getPct(Long.valueOf(2)),tolerance); assertEquals("three pct",0.5,f.getPct(threeL),tolerance); // MATH-329 assertEquals("three (Object) pct",0.5,f.getPct((Object) (Integer.valueOf(3))),tolerance); assertEquals("five pct",0,f.getPct(5),tolerance); assertEquals("foo pct",0,f.getPct("foo"),tolerance); assertEquals("one cum pct",0.25,f.getCumPct(1),tolerance); assertEquals("two cum pct",0.50,f.getCumPct(Long.valueOf(2)),tolerance); assertEquals("Integer argument",0.50,f.getCumPct(Integer.valueOf(2)),tolerance); assertEquals("three cum pct",1.0,f.getCumPct(threeL),tolerance); assertEquals("five cum pct",1.0,f.getCumPct(5),tolerance); assertEquals("zero cum pct",0.0,f.getCumPct(0),tolerance); assertEquals("foo cum pct",0,f.getCumPct("foo"),tolerance); } /** test adding incomparable values */ public void testAdd() { char aChar = 'a'; char bChar = 'b'; String aString = "a"; f.addValue(aChar); f.addValue(bChar); try { f.addValue(aString); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } try { f.addValue(2); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } assertEquals("a pct",0.5,f.getPct(aChar),tolerance); assertEquals("b cum pct",1.0,f.getCumPct(bChar),tolerance); assertEquals("a string pct",0.0,f.getPct(aString),tolerance); assertEquals("a string cum pct",0.0,f.getCumPct(aString),tolerance); f = new Frequency(); f.addValue("One"); try { f.addValue(new Integer("One")); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } // Check what happens when non-Comparable objects are added @SuppressWarnings("deprecation") public void testAddNonComparable(){ try { f.addValue(new Object()); // This was previously OK fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } f.clear(); f.addValue(1); try { f.addValue(new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } /** test empty table */ public void testEmptyTable() { assertEquals("freq sum, empty table", 0, f.getSumFreq()); assertEquals("count, empty table", 0, f.getCount(0)); assertEquals("count, empty table",0, f.getCount(Integer.valueOf(0))); assertEquals("cum freq, empty table", 0, f.getCumFreq(0)); assertEquals("cum freq, empty table", 0, f.getCumFreq("x")); assertTrue("pct, empty table", Double.isNaN(f.getPct(0))); assertTrue("pct, empty table", Double.isNaN(f.getPct(Integer.valueOf(0)))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(0))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(Integer.valueOf(0)))); } /** * Tests toString() */ public void testToString(){ f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); String s = f.toString(); //System.out.println(s); assertNotNull(s); BufferedReader reader = new BufferedReader(new StringReader(s)); try { String line = reader.readLine(); // header line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // no more elements assertNull(line); } catch(IOException ex){ fail(ex.getMessage()); } } public void testIntegerValues() { Comparable<?> obj1 = null; obj1 = Integer.valueOf(1); Integer int1 = Integer.valueOf(1); f.addValue(obj1); f.addValue(int1); f.addValue(2); f.addValue(Long.valueOf(2)); assertEquals("Integer 1 count", 2, f.getCount(1)); assertEquals("Integer 1 count", 2, f.getCount(Integer.valueOf(1))); assertEquals("Integer 1 count", 2, f.getCount(Long.valueOf(1))); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(1), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Long.valueOf(1)), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Integer.valueOf(1)), tolerance); Iterator<?> it = f.valuesIterator(); while (it.hasNext()) { assertTrue(it.next() instanceof Long); } } public void testSerial() { f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); assertEquals(f, TestUtils.serializeAndRecover(f)); } }
// You are a professional Java test case writer, please create a test case named `testPcts` for the issue `Math-MATH-329`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-329 // // ## Issue-Title: // In stat.Frequency, getPct(Object) uses getCumPct(Comparable) instead of getPct(Comparable) // // ## Issue-Description: // // Drop in Replacement of 1.2 with 2.0 not possible because all getPct calls will be cummulative without code change // // // Frequency.java // // // /\*\* // // // * Returns the percentage of values that are equal to v // * @deprecated replaced by // {@link #getPct(Comparable)} // as of 2.0 // // \*/ // // @Deprecated // // public double getPct(Object v) // // // { // return getCumPct((Comparable<?>) v); // } // // // // // public void testPcts() {
157
/** test pcts */
75
134
src/test/java/org/apache/commons/math/stat/FrequencyTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-329 ## Issue-Title: In stat.Frequency, getPct(Object) uses getCumPct(Comparable) instead of getPct(Comparable) ## Issue-Description: Drop in Replacement of 1.2 with 2.0 not possible because all getPct calls will be cummulative without code change Frequency.java /\*\* * Returns the percentage of values that are equal to v * @deprecated replaced by {@link #getPct(Comparable)} as of 2.0 \*/ @Deprecated public double getPct(Object v) { return getCumPct((Comparable<?>) v); } ``` You are a professional Java test case writer, please create a test case named `testPcts` for the issue `Math-MATH-329`, utilizing the provided issue report information and the following function signature. ```java public void testPcts() { ```
134
[ "org.apache.commons.math.stat.Frequency" ]
bef4a7f689fd026b79e3035271ebef442ac6f329258045d95e58c4bd594e8fff
public void testPcts()
// You are a professional Java test case writer, please create a test case named `testPcts` for the issue `Math-MATH-329`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-329 // // ## Issue-Title: // In stat.Frequency, getPct(Object) uses getCumPct(Comparable) instead of getPct(Comparable) // // ## Issue-Description: // // Drop in Replacement of 1.2 with 2.0 not possible because all getPct calls will be cummulative without code change // // // Frequency.java // // // /\*\* // // // * Returns the percentage of values that are equal to v // * @deprecated replaced by // {@link #getPct(Comparable)} // as of 2.0 // // \*/ // // @Deprecated // // public double getPct(Object v) // // // { // return getCumPct((Comparable<?>) v); // } // // // // //
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; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import org.apache.commons.math.TestUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test cases for the {@link Frequency} class. * * @version $Revision$ $Date$ */ public final class FrequencyTest extends TestCase { private long oneL = 1; private long twoL = 2; private long threeL = 3; private int oneI = 1; private int twoI = 2; private int threeI=3; private double tolerance = 10E-15; private Frequency f = null; public FrequencyTest(String name) { super(name); } @Override public void setUp() { f = new Frequency(); } public static Test suite() { TestSuite suite = new TestSuite(FrequencyTest.class); suite.setName("Frequency Tests"); return suite; } /** test freq counts */ public void testCounts() { assertEquals("total count",0,f.getSumFreq()); f.addValue(oneL); f.addValue(twoL); f.addValue(1); f.addValue(oneI); assertEquals("one frequency count",3,f.getCount(1)); assertEquals("two frequency count",1,f.getCount(2)); assertEquals("three frequency count",0,f.getCount(3)); assertEquals("total count",4,f.getSumFreq()); assertEquals("zero cumulative frequency", 0, f.getCumFreq(0)); assertEquals("one cumulative frequency", 3, f.getCumFreq(1)); assertEquals("two cumulative frequency", 4, f.getCumFreq(2)); assertEquals("Integer argument cum freq",4, f.getCumFreq(Integer.valueOf(2))); assertEquals("five cumulative frequency", 4, f.getCumFreq(5)); assertEquals("foo cumulative frequency", 0, f.getCumFreq("foo")); f.clear(); assertEquals("total count",0,f.getSumFreq()); // userguide examples ------------------------------------------------------------------- f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one cumulative frequency", 1 , f.getCount("one")); assertEquals("Z cumulative pct", 0.5, f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct", 1.0, f.getCumPct("z"), tolerance); assertEquals("Ot cumulative pct", 0.25, f.getCumPct("Ot"), tolerance); f.clear(); f = null; Frequency f = new Frequency(); f.addValue(1); f.addValue(Integer.valueOf(1)); f.addValue(Long.valueOf(1)); f.addValue(2); f.addValue(Integer.valueOf(-1)); assertEquals("1 count", 3, f.getCount(1)); assertEquals("1 count", 3, f.getCount(Integer.valueOf(1))); assertEquals("0 cum pct", 0.2, f.getCumPct(0), tolerance); assertEquals("1 pct", 0.6, f.getPct(Integer.valueOf(1)), tolerance); assertEquals("-2 cum pct", 0, f.getCumPct(-2), tolerance); assertEquals("10 cum pct", 1, f.getCumPct(10), tolerance); f = null; f = new Frequency(String.CASE_INSENSITIVE_ORDER); f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one count", 3 , f.getCount("one")); assertEquals("Z cumulative pct -- case insensitive", 1 , f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct -- case insensitive", 1 , f.getCumPct("z"), tolerance); f = null; f = new Frequency(); assertEquals(0L, f.getCount('a')); assertEquals(0L, f.getCumFreq('b')); TestUtils.assertEquals(Double.NaN, f.getPct('a'), 0.0); TestUtils.assertEquals(Double.NaN, f.getCumPct('b'), 0.0); f.addValue('a'); f.addValue('b'); f.addValue('c'); f.addValue('d'); assertEquals(1L, f.getCount('a')); assertEquals(2L, f.getCumFreq('b')); assertEquals(0.25, f.getPct('a'), 0.0); assertEquals(0.5, f.getCumPct('b'), 0.0); assertEquals(1.0, f.getCumPct('e'), 0.0); } /** test pcts */ public void testPcts() { f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); f.addValue(threeL); f.addValue(threeL); f.addValue(3); f.addValue(threeI); assertEquals("one pct",0.25,f.getPct(1),tolerance); assertEquals("two pct",0.25,f.getPct(Long.valueOf(2)),tolerance); assertEquals("three pct",0.5,f.getPct(threeL),tolerance); // MATH-329 assertEquals("three (Object) pct",0.5,f.getPct((Object) (Integer.valueOf(3))),tolerance); assertEquals("five pct",0,f.getPct(5),tolerance); assertEquals("foo pct",0,f.getPct("foo"),tolerance); assertEquals("one cum pct",0.25,f.getCumPct(1),tolerance); assertEquals("two cum pct",0.50,f.getCumPct(Long.valueOf(2)),tolerance); assertEquals("Integer argument",0.50,f.getCumPct(Integer.valueOf(2)),tolerance); assertEquals("three cum pct",1.0,f.getCumPct(threeL),tolerance); assertEquals("five cum pct",1.0,f.getCumPct(5),tolerance); assertEquals("zero cum pct",0.0,f.getCumPct(0),tolerance); assertEquals("foo cum pct",0,f.getCumPct("foo"),tolerance); } /** test adding incomparable values */ public void testAdd() { char aChar = 'a'; char bChar = 'b'; String aString = "a"; f.addValue(aChar); f.addValue(bChar); try { f.addValue(aString); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } try { f.addValue(2); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } assertEquals("a pct",0.5,f.getPct(aChar),tolerance); assertEquals("b cum pct",1.0,f.getCumPct(bChar),tolerance); assertEquals("a string pct",0.0,f.getPct(aString),tolerance); assertEquals("a string cum pct",0.0,f.getCumPct(aString),tolerance); f = new Frequency(); f.addValue("One"); try { f.addValue(new Integer("One")); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } // Check what happens when non-Comparable objects are added @SuppressWarnings("deprecation") public void testAddNonComparable(){ try { f.addValue(new Object()); // This was previously OK fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } f.clear(); f.addValue(1); try { f.addValue(new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } /** test empty table */ public void testEmptyTable() { assertEquals("freq sum, empty table", 0, f.getSumFreq()); assertEquals("count, empty table", 0, f.getCount(0)); assertEquals("count, empty table",0, f.getCount(Integer.valueOf(0))); assertEquals("cum freq, empty table", 0, f.getCumFreq(0)); assertEquals("cum freq, empty table", 0, f.getCumFreq("x")); assertTrue("pct, empty table", Double.isNaN(f.getPct(0))); assertTrue("pct, empty table", Double.isNaN(f.getPct(Integer.valueOf(0)))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(0))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(Integer.valueOf(0)))); } /** * Tests toString() */ public void testToString(){ f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); String s = f.toString(); //System.out.println(s); assertNotNull(s); BufferedReader reader = new BufferedReader(new StringReader(s)); try { String line = reader.readLine(); // header line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // no more elements assertNull(line); } catch(IOException ex){ fail(ex.getMessage()); } } public void testIntegerValues() { Comparable<?> obj1 = null; obj1 = Integer.valueOf(1); Integer int1 = Integer.valueOf(1); f.addValue(obj1); f.addValue(int1); f.addValue(2); f.addValue(Long.valueOf(2)); assertEquals("Integer 1 count", 2, f.getCount(1)); assertEquals("Integer 1 count", 2, f.getCount(Integer.valueOf(1))); assertEquals("Integer 1 count", 2, f.getCount(Long.valueOf(1))); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(1), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Long.valueOf(1)), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Integer.valueOf(1)), tolerance); Iterator<?> it = f.valuesIterator(); while (it.hasNext()) { assertTrue(it.next() instanceof Long); } } public void testSerial() { f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); assertEquals(f, TestUtils.serializeAndRecover(f)); } }
@Test public void testNullRecordSeparatorCsv106() { final CSVFormat format = CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader("H1", "H2"); final String formatStr = format.format("A", "B"); assertNotNull(formatStr); assertFalse(formatStr.endsWith("null")); }
org.apache.commons.csv.CSVFormatTest::testNullRecordSeparatorCsv106
src/test/java/org/apache/commons/csv/CSVFormatTest.java
237
src/test/java/org/apache/commons/csv/CSVFormatTest.java
testNullRecordSeparatorCsv106
/* * 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.csv; import static org.apache.commons.csv.CSVFormat.RFC4180; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.LF; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import org.junit.Test; /** * * * @version $Id$ */ public class CSVFormatTest { private static void assertNotEquals(final Object right, final Object left) { assertFalse(right.equals(left)); assertFalse(left.equals(right)); } private static CSVFormat copy(final CSVFormat format) { return format.withDelimiter(format.getDelimiter()); } @Test(expected = IllegalStateException.class) public void testDelimiterSameAsCommentStartThrowsException() { CSVFormat.DEFAULT.withDelimiter('!').withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testDelimiterSameAsEscapeThrowsException() { CSVFormat.DEFAULT.withDelimiter('!').withEscape('!').validate(); } @Test(expected = IllegalStateException.class) public void testDuplicateHeaderElements() { CSVFormat.DEFAULT.withHeader("A", "A").validate(); } @Test public void testEquals() { final CSVFormat right = CSVFormat.DEFAULT; final CSVFormat left = copy(right); assertFalse(right.equals(null)); assertFalse(right.equals("A String Instance")); assertEquals(right, right); assertEquals(right, left); assertEquals(left, right); assertEquals(right.hashCode(), right.hashCode()); assertEquals(right.hashCode(), left.hashCode()); } @Test public void testEqualsCommentStart() { final CSVFormat right = CSVFormat.newFormat('\'') .withQuoteChar('"') .withCommentStart('#') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withCommentStart('!'); assertNotEquals(right, left); } @Test public void testEqualsDelimiter() { final CSVFormat right = CSVFormat.newFormat('!'); final CSVFormat left = CSVFormat.newFormat('?'); assertNotEquals(right, left); } @Test public void testEqualsEscape() { final CSVFormat right = CSVFormat.newFormat('\'') .withQuoteChar('"') .withCommentStart('#') .withEscape('+') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withEscape('!'); assertNotEquals(right, left); } @Test public void testEqualsHeader() { final CSVFormat right = CSVFormat.newFormat('\'') .withRecordSeparator('*') .withCommentStart('#') .withEscape('+') .withHeader("One", "Two", "Three") .withIgnoreEmptyLines(true) .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withHeader("Three", "Two", "One"); assertNotEquals(right, left); } @Test public void testEqualsIgnoreEmptyLines() { final CSVFormat right = CSVFormat.newFormat('\'') .withCommentStart('#') .withEscape('+') .withIgnoreEmptyLines(true) .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withIgnoreEmptyLines(false); assertNotEquals(right, left); } @Test public void testEqualsIgnoreSurroundingSpaces() { final CSVFormat right = CSVFormat.newFormat('\'') .withCommentStart('#') .withEscape('+') .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withIgnoreSurroundingSpaces(false); assertNotEquals(right, left); } @Test public void testEqualsQuoteChar() { final CSVFormat right = CSVFormat.newFormat('\'').withQuoteChar('"'); final CSVFormat left = right.withQuoteChar('!'); assertNotEquals(right, left); } @Test public void testEqualsQuotePolicy() { final CSVFormat right = CSVFormat.newFormat('\'') .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withQuotePolicy(Quote.MINIMAL); assertNotEquals(right, left); } @Test public void testEqualsRecordSeparator() { final CSVFormat right = CSVFormat.newFormat('\'') .withRecordSeparator('*') .withCommentStart('#') .withEscape('+') .withIgnoreEmptyLines(true) .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withRecordSeparator('!'); assertNotEquals(right, left); } @Test(expected = IllegalStateException.class) public void testEscapeSameAsCommentStartThrowsException() { CSVFormat.DEFAULT.withEscape('!').withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testEscapeSameAsCommentStartThrowsExceptionForWrapperType() { // Cannot assume that callers won't use different Character objects CSVFormat.DEFAULT.withEscape(new Character('!')).withCommentStart(new Character('!')).validate(); } @Test public void testFormat() { final CSVFormat format = CSVFormat.DEFAULT; assertEquals("", format.format()); assertEquals("a,b,c", format.format("a", "b", "c")); assertEquals("\"x,y\",z", format.format("x,y", "z")); } @Test public void testGetHeader() throws Exception { final String[] header = new String[]{"one", "two", "three"}; final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); // getHeader() makes a copy of the header array. final String[] headerCopy = formatWithHeader.getHeader(); headerCopy[0] = "A"; headerCopy[1] = "B"; headerCopy[2] = "C"; assertFalse(Arrays.equals(formatWithHeader.getHeader(), headerCopy)); assertNotSame(formatWithHeader.getHeader(), headerCopy); } @Test public void testNullRecordSeparatorCsv106() { final CSVFormat format = CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader("H1", "H2"); final String formatStr = format.format("A", "B"); assertNotNull(formatStr); assertFalse(formatStr.endsWith("null")); } @Test(expected = IllegalStateException.class) public void testQuoteCharSameAsCommentStartThrowsException() { CSVFormat.DEFAULT.withQuoteChar('!').withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testQuoteCharSameAsCommentStartThrowsExceptionForWrapperType() { // Cannot assume that callers won't use different Character objects CSVFormat.DEFAULT.withQuoteChar(new Character('!')).withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testQuoteCharSameAsDelimiterThrowsException() { CSVFormat.DEFAULT.withQuoteChar('!').withDelimiter('!').validate(); } @Test(expected = IllegalStateException.class) public void testQuotePolicyNoneWithoutEscapeThrowsException() { CSVFormat.newFormat('!').withQuotePolicy(Quote.NONE).validate(); } @Test public void testRFC4180() { assertEquals(null, RFC4180.getCommentStart()); assertEquals(',', RFC4180.getDelimiter()); assertEquals(null, RFC4180.getEscape()); assertFalse(RFC4180.getIgnoreEmptyLines()); assertEquals(Character.valueOf('"'), RFC4180.getQuoteChar()); assertEquals(null, RFC4180.getQuotePolicy()); assertEquals("\r\n", RFC4180.getRecordSeparator()); } @SuppressWarnings("boxing") // no need to worry about boxing here @Test public void testSerialization() throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(CSVFormat.DEFAULT); oos.flush(); oos.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); final CSVFormat format = (CSVFormat) in.readObject(); assertNotNull(format); assertEquals("delimiter", CSVFormat.DEFAULT.getDelimiter(), format.getDelimiter()); assertEquals("encapsulator", CSVFormat.DEFAULT.getQuoteChar(), format.getQuoteChar()); assertEquals("comment start", CSVFormat.DEFAULT.getCommentStart(), format.getCommentStart()); assertEquals("line separator", CSVFormat.DEFAULT.getRecordSeparator(), format.getRecordSeparator()); assertEquals("escape", CSVFormat.DEFAULT.getEscape(), format.getEscape()); assertEquals("trim", CSVFormat.DEFAULT.getIgnoreSurroundingSpaces(), format.getIgnoreSurroundingSpaces()); assertEquals("empty lines", CSVFormat.DEFAULT.getIgnoreEmptyLines(), format.getIgnoreEmptyLines()); } @Test public void testWithCommentStart() throws Exception { final CSVFormat formatWithCommentStart = CSVFormat.DEFAULT.withCommentStart('#'); assertEquals( Character.valueOf('#'), formatWithCommentStart.getCommentStart()); } @Test(expected = IllegalArgumentException.class) public void testWithCommentStartCRThrowsException() { CSVFormat.DEFAULT.withCommentStart(CR).validate(); } @Test public void testWithDelimiter() throws Exception { final CSVFormat formatWithDelimiter = CSVFormat.DEFAULT.withDelimiter('!'); assertEquals('!', formatWithDelimiter.getDelimiter()); } @Test(expected = IllegalArgumentException.class) public void testWithDelimiterLFThrowsException() { CSVFormat.DEFAULT.withDelimiter(LF).validate(); } @Test public void testWithEscape() throws Exception { final CSVFormat formatWithEscape = CSVFormat.DEFAULT.withEscape('&'); assertEquals(Character.valueOf('&'), formatWithEscape.getEscape()); } @Test(expected = IllegalArgumentException.class) public void testWithEscapeCRThrowsExceptions() { CSVFormat.DEFAULT.withEscape(CR).validate(); } @Test public void testWithHeader() throws Exception { final String[] header = new String[]{"one", "two", "three"}; // withHeader() makes a copy of the header array. final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); assertArrayEquals(header, formatWithHeader.getHeader()); assertNotSame(header, formatWithHeader.getHeader()); header[0] = "A"; header[1] = "B"; header[2] = "C"; assertFalse(Arrays.equals(formatWithHeader.getHeader(), header)); } @Test public void testWithIgnoreEmptyLines() throws Exception { assertFalse(CSVFormat.DEFAULT.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); assertTrue(CSVFormat.DEFAULT.withIgnoreEmptyLines(true).getIgnoreEmptyLines()); } @Test public void testWithIgnoreSurround() throws Exception { assertFalse(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); assertTrue(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true).getIgnoreSurroundingSpaces()); } @Test public void testWithNullString() throws Exception { final CSVFormat formatWithNullString = CSVFormat.DEFAULT.withNullString("null"); assertEquals("null", formatWithNullString.getNullString()); } @Test public void testWithQuoteChar() throws Exception { final CSVFormat formatWithQuoteChar = CSVFormat.DEFAULT.withQuoteChar('"'); assertEquals(Character.valueOf('"'), formatWithQuoteChar.getQuoteChar()); } @Test(expected = IllegalArgumentException.class) public void testWithQuoteLFThrowsException() { CSVFormat.DEFAULT.withQuoteChar(LF).validate(); } @Test public void testWithQuotePolicy() throws Exception { final CSVFormat formatWithQuotePolicy = CSVFormat.DEFAULT.withQuotePolicy(Quote.ALL); assertEquals(Quote.ALL, formatWithQuotePolicy.getQuotePolicy()); } @Test public void testWithRecordSeparator() throws Exception { final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator('!'); assertEquals("!", formatWithRecordSeparator.getRecordSeparator()); } }
// You are a professional Java test case writer, please create a test case named `testNullRecordSeparatorCsv106` for the issue `Csv-CSV-106`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-106 // // ## Issue-Title: // CSVFormat.format allways append null // // ## Issue-Description: // // When I now call // // CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader("H1","H2").format("A","B") // // I get the output A;Bnull // // // The expected output would be // // // A;B // // // // // @Test public void testNullRecordSeparatorCsv106() {
237
5
231
src/test/java/org/apache/commons/csv/CSVFormatTest.java
src/test/java
```markdown ## Issue-ID: Csv-CSV-106 ## Issue-Title: CSVFormat.format allways append null ## Issue-Description: When I now call CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader("H1","H2").format("A","B") I get the output A;Bnull The expected output would be A;B ``` You are a professional Java test case writer, please create a test case named `testNullRecordSeparatorCsv106` for the issue `Csv-CSV-106`, utilizing the provided issue report information and the following function signature. ```java @Test public void testNullRecordSeparatorCsv106() { ```
231
[ "org.apache.commons.csv.CSVPrinter" ]
bf8df287b147dae0836de0a9bf911689ae0382100d79db0611263b5205e0a508
@Test public void testNullRecordSeparatorCsv106()
// You are a professional Java test case writer, please create a test case named `testNullRecordSeparatorCsv106` for the issue `Csv-CSV-106`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-106 // // ## Issue-Title: // CSVFormat.format allways append null // // ## Issue-Description: // // When I now call // // CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader("H1","H2").format("A","B") // // I get the output A;Bnull // // // The expected output would be // // // A;B // // // // //
Csv
/* * 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.csv; import static org.apache.commons.csv.CSVFormat.RFC4180; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.LF; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import org.junit.Test; /** * * * @version $Id$ */ public class CSVFormatTest { private static void assertNotEquals(final Object right, final Object left) { assertFalse(right.equals(left)); assertFalse(left.equals(right)); } private static CSVFormat copy(final CSVFormat format) { return format.withDelimiter(format.getDelimiter()); } @Test(expected = IllegalStateException.class) public void testDelimiterSameAsCommentStartThrowsException() { CSVFormat.DEFAULT.withDelimiter('!').withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testDelimiterSameAsEscapeThrowsException() { CSVFormat.DEFAULT.withDelimiter('!').withEscape('!').validate(); } @Test(expected = IllegalStateException.class) public void testDuplicateHeaderElements() { CSVFormat.DEFAULT.withHeader("A", "A").validate(); } @Test public void testEquals() { final CSVFormat right = CSVFormat.DEFAULT; final CSVFormat left = copy(right); assertFalse(right.equals(null)); assertFalse(right.equals("A String Instance")); assertEquals(right, right); assertEquals(right, left); assertEquals(left, right); assertEquals(right.hashCode(), right.hashCode()); assertEquals(right.hashCode(), left.hashCode()); } @Test public void testEqualsCommentStart() { final CSVFormat right = CSVFormat.newFormat('\'') .withQuoteChar('"') .withCommentStart('#') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withCommentStart('!'); assertNotEquals(right, left); } @Test public void testEqualsDelimiter() { final CSVFormat right = CSVFormat.newFormat('!'); final CSVFormat left = CSVFormat.newFormat('?'); assertNotEquals(right, left); } @Test public void testEqualsEscape() { final CSVFormat right = CSVFormat.newFormat('\'') .withQuoteChar('"') .withCommentStart('#') .withEscape('+') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withEscape('!'); assertNotEquals(right, left); } @Test public void testEqualsHeader() { final CSVFormat right = CSVFormat.newFormat('\'') .withRecordSeparator('*') .withCommentStart('#') .withEscape('+') .withHeader("One", "Two", "Three") .withIgnoreEmptyLines(true) .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withHeader("Three", "Two", "One"); assertNotEquals(right, left); } @Test public void testEqualsIgnoreEmptyLines() { final CSVFormat right = CSVFormat.newFormat('\'') .withCommentStart('#') .withEscape('+') .withIgnoreEmptyLines(true) .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withIgnoreEmptyLines(false); assertNotEquals(right, left); } @Test public void testEqualsIgnoreSurroundingSpaces() { final CSVFormat right = CSVFormat.newFormat('\'') .withCommentStart('#') .withEscape('+') .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withIgnoreSurroundingSpaces(false); assertNotEquals(right, left); } @Test public void testEqualsQuoteChar() { final CSVFormat right = CSVFormat.newFormat('\'').withQuoteChar('"'); final CSVFormat left = right.withQuoteChar('!'); assertNotEquals(right, left); } @Test public void testEqualsQuotePolicy() { final CSVFormat right = CSVFormat.newFormat('\'') .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withQuotePolicy(Quote.MINIMAL); assertNotEquals(right, left); } @Test public void testEqualsRecordSeparator() { final CSVFormat right = CSVFormat.newFormat('\'') .withRecordSeparator('*') .withCommentStart('#') .withEscape('+') .withIgnoreEmptyLines(true) .withIgnoreSurroundingSpaces(true) .withQuoteChar('"') .withQuotePolicy(Quote.ALL); final CSVFormat left = right .withRecordSeparator('!'); assertNotEquals(right, left); } @Test(expected = IllegalStateException.class) public void testEscapeSameAsCommentStartThrowsException() { CSVFormat.DEFAULT.withEscape('!').withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testEscapeSameAsCommentStartThrowsExceptionForWrapperType() { // Cannot assume that callers won't use different Character objects CSVFormat.DEFAULT.withEscape(new Character('!')).withCommentStart(new Character('!')).validate(); } @Test public void testFormat() { final CSVFormat format = CSVFormat.DEFAULT; assertEquals("", format.format()); assertEquals("a,b,c", format.format("a", "b", "c")); assertEquals("\"x,y\",z", format.format("x,y", "z")); } @Test public void testGetHeader() throws Exception { final String[] header = new String[]{"one", "two", "three"}; final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); // getHeader() makes a copy of the header array. final String[] headerCopy = formatWithHeader.getHeader(); headerCopy[0] = "A"; headerCopy[1] = "B"; headerCopy[2] = "C"; assertFalse(Arrays.equals(formatWithHeader.getHeader(), headerCopy)); assertNotSame(formatWithHeader.getHeader(), headerCopy); } @Test public void testNullRecordSeparatorCsv106() { final CSVFormat format = CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader("H1", "H2"); final String formatStr = format.format("A", "B"); assertNotNull(formatStr); assertFalse(formatStr.endsWith("null")); } @Test(expected = IllegalStateException.class) public void testQuoteCharSameAsCommentStartThrowsException() { CSVFormat.DEFAULT.withQuoteChar('!').withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testQuoteCharSameAsCommentStartThrowsExceptionForWrapperType() { // Cannot assume that callers won't use different Character objects CSVFormat.DEFAULT.withQuoteChar(new Character('!')).withCommentStart('!').validate(); } @Test(expected = IllegalStateException.class) public void testQuoteCharSameAsDelimiterThrowsException() { CSVFormat.DEFAULT.withQuoteChar('!').withDelimiter('!').validate(); } @Test(expected = IllegalStateException.class) public void testQuotePolicyNoneWithoutEscapeThrowsException() { CSVFormat.newFormat('!').withQuotePolicy(Quote.NONE).validate(); } @Test public void testRFC4180() { assertEquals(null, RFC4180.getCommentStart()); assertEquals(',', RFC4180.getDelimiter()); assertEquals(null, RFC4180.getEscape()); assertFalse(RFC4180.getIgnoreEmptyLines()); assertEquals(Character.valueOf('"'), RFC4180.getQuoteChar()); assertEquals(null, RFC4180.getQuotePolicy()); assertEquals("\r\n", RFC4180.getRecordSeparator()); } @SuppressWarnings("boxing") // no need to worry about boxing here @Test public void testSerialization() throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(CSVFormat.DEFAULT); oos.flush(); oos.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); final CSVFormat format = (CSVFormat) in.readObject(); assertNotNull(format); assertEquals("delimiter", CSVFormat.DEFAULT.getDelimiter(), format.getDelimiter()); assertEquals("encapsulator", CSVFormat.DEFAULT.getQuoteChar(), format.getQuoteChar()); assertEquals("comment start", CSVFormat.DEFAULT.getCommentStart(), format.getCommentStart()); assertEquals("line separator", CSVFormat.DEFAULT.getRecordSeparator(), format.getRecordSeparator()); assertEquals("escape", CSVFormat.DEFAULT.getEscape(), format.getEscape()); assertEquals("trim", CSVFormat.DEFAULT.getIgnoreSurroundingSpaces(), format.getIgnoreSurroundingSpaces()); assertEquals("empty lines", CSVFormat.DEFAULT.getIgnoreEmptyLines(), format.getIgnoreEmptyLines()); } @Test public void testWithCommentStart() throws Exception { final CSVFormat formatWithCommentStart = CSVFormat.DEFAULT.withCommentStart('#'); assertEquals( Character.valueOf('#'), formatWithCommentStart.getCommentStart()); } @Test(expected = IllegalArgumentException.class) public void testWithCommentStartCRThrowsException() { CSVFormat.DEFAULT.withCommentStart(CR).validate(); } @Test public void testWithDelimiter() throws Exception { final CSVFormat formatWithDelimiter = CSVFormat.DEFAULT.withDelimiter('!'); assertEquals('!', formatWithDelimiter.getDelimiter()); } @Test(expected = IllegalArgumentException.class) public void testWithDelimiterLFThrowsException() { CSVFormat.DEFAULT.withDelimiter(LF).validate(); } @Test public void testWithEscape() throws Exception { final CSVFormat formatWithEscape = CSVFormat.DEFAULT.withEscape('&'); assertEquals(Character.valueOf('&'), formatWithEscape.getEscape()); } @Test(expected = IllegalArgumentException.class) public void testWithEscapeCRThrowsExceptions() { CSVFormat.DEFAULT.withEscape(CR).validate(); } @Test public void testWithHeader() throws Exception { final String[] header = new String[]{"one", "two", "three"}; // withHeader() makes a copy of the header array. final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); assertArrayEquals(header, formatWithHeader.getHeader()); assertNotSame(header, formatWithHeader.getHeader()); header[0] = "A"; header[1] = "B"; header[2] = "C"; assertFalse(Arrays.equals(formatWithHeader.getHeader(), header)); } @Test public void testWithIgnoreEmptyLines() throws Exception { assertFalse(CSVFormat.DEFAULT.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); assertTrue(CSVFormat.DEFAULT.withIgnoreEmptyLines(true).getIgnoreEmptyLines()); } @Test public void testWithIgnoreSurround() throws Exception { assertFalse(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); assertTrue(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true).getIgnoreSurroundingSpaces()); } @Test public void testWithNullString() throws Exception { final CSVFormat formatWithNullString = CSVFormat.DEFAULT.withNullString("null"); assertEquals("null", formatWithNullString.getNullString()); } @Test public void testWithQuoteChar() throws Exception { final CSVFormat formatWithQuoteChar = CSVFormat.DEFAULT.withQuoteChar('"'); assertEquals(Character.valueOf('"'), formatWithQuoteChar.getQuoteChar()); } @Test(expected = IllegalArgumentException.class) public void testWithQuoteLFThrowsException() { CSVFormat.DEFAULT.withQuoteChar(LF).validate(); } @Test public void testWithQuotePolicy() throws Exception { final CSVFormat formatWithQuotePolicy = CSVFormat.DEFAULT.withQuotePolicy(Quote.ALL); assertEquals(Quote.ALL, formatWithQuotePolicy.getQuotePolicy()); } @Test public void testWithRecordSeparator() throws Exception { final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator('!'); assertEquals("!", formatWithRecordSeparator.getRecordSeparator()); } }
public void testCachedSerialize() throws IOException { ObjectMapper mapper = new ObjectMapper(); String json = aposToQuotes("{'data':{'1st':'onedata','2nd':'twodata'}}"); // Do deserialization with non-annotated map property NonAnnotatedMapHolderClass ignored = mapper.readValue(json, NonAnnotatedMapHolderClass.class); assertTrue(ignored.data.containsKey("1st")); assertTrue(ignored.data.containsKey("2nd")); //mapper = new ObjectMapper(); MapHolder model2 = mapper.readValue(json, MapHolder.class); if (!model2.data.containsKey("1st (CUSTOM)") || !model2.data.containsKey("2nd (CUSTOM)")) { fail("Not using custom key deserializer for input: "+json+"; resulted in: "+model2.data); } }
com.fasterxml.jackson.databind.deser.jdk.MapDeserializerCachingTest::testCachedSerialize
src/test/java/com/fasterxml/jackson/databind/deser/jdk/MapDeserializerCachingTest.java
50
src/test/java/com/fasterxml/jackson/databind/deser/jdk/MapDeserializerCachingTest.java
testCachedSerialize
package com.fasterxml.jackson.databind.deser.jdk; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; // for [databind#1807] public class MapDeserializerCachingTest extends BaseMapTest { public static class NonAnnotatedMapHolderClass { public Map<String, String> data = new TreeMap<String, String>(); } public static class MapHolder { @JsonDeserialize(keyUsing = MyKeyDeserializer.class) public Map<String, String> data = new TreeMap<String, String>(); } public static class MyKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { return key + " (CUSTOM)"; } } /* /********************************************************** /* Test methods /********************************************************** */ public void testCachedSerialize() throws IOException { ObjectMapper mapper = new ObjectMapper(); String json = aposToQuotes("{'data':{'1st':'onedata','2nd':'twodata'}}"); // Do deserialization with non-annotated map property NonAnnotatedMapHolderClass ignored = mapper.readValue(json, NonAnnotatedMapHolderClass.class); assertTrue(ignored.data.containsKey("1st")); assertTrue(ignored.data.containsKey("2nd")); //mapper = new ObjectMapper(); MapHolder model2 = mapper.readValue(json, MapHolder.class); if (!model2.data.containsKey("1st (CUSTOM)") || !model2.data.containsKey("2nd (CUSTOM)")) { fail("Not using custom key deserializer for input: "+json+"; resulted in: "+model2.data); } } }
// You are a professional Java test case writer, please create a test case named `testCachedSerialize` for the issue `JacksonDatabind-1809`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1809 // // ## Issue-Title: // 2.9.2 deserialization regression // // ## Issue-Description: // There seems to be a regression in the latest 2.9.2 release. // // // Using `org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper` from `org.apache.logging.log4j:log4j-core:2.9.1` to deserialize the appended JSON object is throwing an exception with 2.9.2 but worked with 2.9.1. // // // `org.apache.logging.log4j.core.jackson.Log4jYamlObjectMapper` and `org.apache.logging.log4j.core.jackson.Log4jXmlObjectMapper` fail in similar ways. // // // ### inputString // // // // ``` // { // "timeMillis" : 1493121664118, // "thread" : "main", // "threadId" : 1, // "threadPriority" : 5, // "level" : "INFO", // "loggerName" : "HelloWorld", // "marker" : { // "name" : "child", // "parents" : [ { // "name" : "parent", // "parents" : [ { // "name" : "grandparent" // } ] // } ] // }, // "message" : "Hello, world!", // "thrown" : { // "commonElementCount" : 0, // "message" : "error message", // "name" : "java.lang.RuntimeException", // "extendedStackTrace" : [ { // "class" : "logtest.Main", // "method" : "main", // "file" : "Main.java", // "line" : 29, // "exact" : true, // "location" : "classes/", // "version" : "?" // } ] // }, // "contextStack" : [ "one", "two" ], // "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger", // "endOfBatch" : false, // "contextMap" : { // "bar" : "BAR", // "foo" : "FOO" // }, // "source" : { // "class" : "logtest.Main", // "method" : "main", // "file" : "Main.java", // "line" : 29 // } // } // ``` // // ### Exception // // // // ``` // org.apache.logging.log4j.core.parser.ParseException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.apache.logging.log4j.Level` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('INFO') // at [Source: (byte[])"{ // "timeMillis" : 1493121664118, // "thread" : "main", // "threadId" : 1, // "threadPriority" : 5, // "level" : "INFO", // "loggerName" : "HelloWorld", // "marker" : { // "name" : "child", // "parents" : [ { // "name" : "parent", // "parents" : [ { // "name" : "grandparent" // } ] // } ] // }, // "message" : "Hello, world!", // "thrown" : { // "commonElementCount" : 0, // "message" : "error message", // "name" : "java.lang.RuntimeException", // "extendedStackTrace" : [ { // public void testCachedSerialize() throws IOException {
50
/* /********************************************************** /* Test methods /********************************************************** */
91
34
src/test/java/com/fasterxml/jackson/databind/deser/jdk/MapDeserializerCachingTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1809 ## Issue-Title: 2.9.2 deserialization regression ## Issue-Description: There seems to be a regression in the latest 2.9.2 release. Using `org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper` from `org.apache.logging.log4j:log4j-core:2.9.1` to deserialize the appended JSON object is throwing an exception with 2.9.2 but worked with 2.9.1. `org.apache.logging.log4j.core.jackson.Log4jYamlObjectMapper` and `org.apache.logging.log4j.core.jackson.Log4jXmlObjectMapper` fail in similar ways. ### inputString ``` { "timeMillis" : 1493121664118, "thread" : "main", "threadId" : 1, "threadPriority" : 5, "level" : "INFO", "loggerName" : "HelloWorld", "marker" : { "name" : "child", "parents" : [ { "name" : "parent", "parents" : [ { "name" : "grandparent" } ] } ] }, "message" : "Hello, world!", "thrown" : { "commonElementCount" : 0, "message" : "error message", "name" : "java.lang.RuntimeException", "extendedStackTrace" : [ { "class" : "logtest.Main", "method" : "main", "file" : "Main.java", "line" : 29, "exact" : true, "location" : "classes/", "version" : "?" } ] }, "contextStack" : [ "one", "two" ], "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger", "endOfBatch" : false, "contextMap" : { "bar" : "BAR", "foo" : "FOO" }, "source" : { "class" : "logtest.Main", "method" : "main", "file" : "Main.java", "line" : 29 } } ``` ### Exception ``` org.apache.logging.log4j.core.parser.ParseException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.apache.logging.log4j.Level` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('INFO') at [Source: (byte[])"{ "timeMillis" : 1493121664118, "thread" : "main", "threadId" : 1, "threadPriority" : 5, "level" : "INFO", "loggerName" : "HelloWorld", "marker" : { "name" : "child", "parents" : [ { "name" : "parent", "parents" : [ { "name" : "grandparent" } ] } ] }, "message" : "Hello, world!", "thrown" : { "commonElementCount" : 0, "message" : "error message", "name" : "java.lang.RuntimeException", "extendedStackTrace" : [ { ``` You are a professional Java test case writer, please create a test case named `testCachedSerialize` for the issue `JacksonDatabind-1809`, utilizing the provided issue report information and the following function signature. ```java public void testCachedSerialize() throws IOException { ```
34
[ "com.fasterxml.jackson.databind.deser.DeserializerCache" ]
bfb1f372aadf7e86746626a23d11f3c18a3d7de375039a8c18bc95fed4582261
public void testCachedSerialize() throws IOException
// You are a professional Java test case writer, please create a test case named `testCachedSerialize` for the issue `JacksonDatabind-1809`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1809 // // ## Issue-Title: // 2.9.2 deserialization regression // // ## Issue-Description: // There seems to be a regression in the latest 2.9.2 release. // // // Using `org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper` from `org.apache.logging.log4j:log4j-core:2.9.1` to deserialize the appended JSON object is throwing an exception with 2.9.2 but worked with 2.9.1. // // // `org.apache.logging.log4j.core.jackson.Log4jYamlObjectMapper` and `org.apache.logging.log4j.core.jackson.Log4jXmlObjectMapper` fail in similar ways. // // // ### inputString // // // // ``` // { // "timeMillis" : 1493121664118, // "thread" : "main", // "threadId" : 1, // "threadPriority" : 5, // "level" : "INFO", // "loggerName" : "HelloWorld", // "marker" : { // "name" : "child", // "parents" : [ { // "name" : "parent", // "parents" : [ { // "name" : "grandparent" // } ] // } ] // }, // "message" : "Hello, world!", // "thrown" : { // "commonElementCount" : 0, // "message" : "error message", // "name" : "java.lang.RuntimeException", // "extendedStackTrace" : [ { // "class" : "logtest.Main", // "method" : "main", // "file" : "Main.java", // "line" : 29, // "exact" : true, // "location" : "classes/", // "version" : "?" // } ] // }, // "contextStack" : [ "one", "two" ], // "loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger", // "endOfBatch" : false, // "contextMap" : { // "bar" : "BAR", // "foo" : "FOO" // }, // "source" : { // "class" : "logtest.Main", // "method" : "main", // "file" : "Main.java", // "line" : 29 // } // } // ``` // // ### Exception // // // // ``` // org.apache.logging.log4j.core.parser.ParseException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.apache.logging.log4j.Level` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('INFO') // at [Source: (byte[])"{ // "timeMillis" : 1493121664118, // "thread" : "main", // "threadId" : 1, // "threadPriority" : 5, // "level" : "INFO", // "loggerName" : "HelloWorld", // "marker" : { // "name" : "child", // "parents" : [ { // "name" : "parent", // "parents" : [ { // "name" : "grandparent" // } ] // } ] // }, // "message" : "Hello, world!", // "thrown" : { // "commonElementCount" : 0, // "message" : "error message", // "name" : "java.lang.RuntimeException", // "extendedStackTrace" : [ { //
JacksonDatabind
package com.fasterxml.jackson.databind.deser.jdk; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; // for [databind#1807] public class MapDeserializerCachingTest extends BaseMapTest { public static class NonAnnotatedMapHolderClass { public Map<String, String> data = new TreeMap<String, String>(); } public static class MapHolder { @JsonDeserialize(keyUsing = MyKeyDeserializer.class) public Map<String, String> data = new TreeMap<String, String>(); } public static class MyKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { return key + " (CUSTOM)"; } } /* /********************************************************** /* Test methods /********************************************************** */ public void testCachedSerialize() throws IOException { ObjectMapper mapper = new ObjectMapper(); String json = aposToQuotes("{'data':{'1st':'onedata','2nd':'twodata'}}"); // Do deserialization with non-annotated map property NonAnnotatedMapHolderClass ignored = mapper.readValue(json, NonAnnotatedMapHolderClass.class); assertTrue(ignored.data.containsKey("1st")); assertTrue(ignored.data.containsKey("2nd")); //mapper = new ObjectMapper(); MapHolder model2 = mapper.readValue(json, MapHolder.class); if (!model2.data.containsKey("1st (CUSTOM)") || !model2.data.containsKey("2nd (CUSTOM)")) { fail("Not using custom key deserializer for input: "+json+"; resulted in: "+model2.data); } } }
public void testSimple() throws Exception { Company comp = new Company(); comp.addComputer(new DesktopComputer("computer-1", "Bangkok")); comp.addComputer(new DesktopComputer("computer-2", "Pattaya")); comp.addComputer(new LaptopComputer("computer-3", "Apple")); final ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(comp); System.out.println("JSON: "+json); Company result = mapper.readValue(json, Company.class); assertNotNull(result); assertNotNull(result.computers); assertEquals(3, result.computers.size()); }
com.fasterxml.jackson.databind.jsontype.WrapperObjectWithObjectIdTest::testSimple
src/test/java/com/fasterxml/jackson/databind/jsontype/WrapperObjectWithObjectIdTest.java
86
src/test/java/com/fasterxml/jackson/databind/jsontype/WrapperObjectWithObjectIdTest.java
testSimple
package com.fasterxml.jackson.databind.jsontype; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; // Test for [databind#1051], issue with combination of Type and Object ids, // if (but only if) `JsonTypeInfo.As.WRAPPER_OBJECT` used. public class WrapperObjectWithObjectIdTest extends BaseMapTest { @JsonRootName(value = "company") static class Company { public List<Computer> computers; public Company() { computers = new ArrayList<Computer>(); } public Company addComputer(Computer computer) { if (computers == null) { computers = new ArrayList<Computer>(); } computers.add(computer); return this; } } @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id" ) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, property = "type" ) @JsonSubTypes({ @JsonSubTypes.Type(value = DesktopComputer.class, name = "desktop"), @JsonSubTypes.Type(value = LaptopComputer.class, name = "laptop") }) static class Computer { public String id; } @JsonTypeName("desktop") static class DesktopComputer extends Computer { public String location; protected DesktopComputer() { } public DesktopComputer(String id, String loc) { this.id = id; location = loc; } } @JsonTypeName("laptop") static class LaptopComputer extends Computer { public String vendor; protected LaptopComputer() { } public LaptopComputer(String id, String v) { this.id = id; vendor = v; } } public void testSimple() throws Exception { Company comp = new Company(); comp.addComputer(new DesktopComputer("computer-1", "Bangkok")); comp.addComputer(new DesktopComputer("computer-2", "Pattaya")); comp.addComputer(new LaptopComputer("computer-3", "Apple")); final ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(comp); System.out.println("JSON: "+json); Company result = mapper.readValue(json, Company.class); assertNotNull(result); assertNotNull(result.computers); assertEquals(3, result.computers.size()); } }
// You are a professional Java test case writer, please create a test case named `testSimple` for the issue `JacksonDatabind-1051`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1051 // // ## Issue-Title: // Problem with Object Id and Type Id as Wrapper Object (regression in 2.5.1) // // ## Issue-Description: // (note: originally from [FasterXML/jackson-module-jaxb-annotations#51](https://github.com/FasterXML/jackson-module-jaxb-annotations/issues/51)) // // // Looks like fix for [#669](https://github.com/FasterXML/jackson-databind/issues/669) caused a regression for the special use case of combining type and object ids, with wrapper-object type id inclusion. The problem started with 2.5.1. // // // // public void testSimple() throws Exception {
86
35
68
src/test/java/com/fasterxml/jackson/databind/jsontype/WrapperObjectWithObjectIdTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1051 ## Issue-Title: Problem with Object Id and Type Id as Wrapper Object (regression in 2.5.1) ## Issue-Description: (note: originally from [FasterXML/jackson-module-jaxb-annotations#51](https://github.com/FasterXML/jackson-module-jaxb-annotations/issues/51)) Looks like fix for [#669](https://github.com/FasterXML/jackson-databind/issues/669) caused a regression for the special use case of combining type and object ids, with wrapper-object type id inclusion. The problem started with 2.5.1. ``` You are a professional Java test case writer, please create a test case named `testSimple` for the issue `JacksonDatabind-1051`, utilizing the provided issue report information and the following function signature. ```java public void testSimple() throws Exception { ```
68
[ "com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer" ]
bfbaf1d311e89d6b4b5aaeada3c085a58ca573eabfc70a0126b10b2fda9b31d6
public void testSimple() throws Exception
// You are a professional Java test case writer, please create a test case named `testSimple` for the issue `JacksonDatabind-1051`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1051 // // ## Issue-Title: // Problem with Object Id and Type Id as Wrapper Object (regression in 2.5.1) // // ## Issue-Description: // (note: originally from [FasterXML/jackson-module-jaxb-annotations#51](https://github.com/FasterXML/jackson-module-jaxb-annotations/issues/51)) // // // Looks like fix for [#669](https://github.com/FasterXML/jackson-databind/issues/669) caused a regression for the special use case of combining type and object ids, with wrapper-object type id inclusion. The problem started with 2.5.1. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.jsontype; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; // Test for [databind#1051], issue with combination of Type and Object ids, // if (but only if) `JsonTypeInfo.As.WRAPPER_OBJECT` used. public class WrapperObjectWithObjectIdTest extends BaseMapTest { @JsonRootName(value = "company") static class Company { public List<Computer> computers; public Company() { computers = new ArrayList<Computer>(); } public Company addComputer(Computer computer) { if (computers == null) { computers = new ArrayList<Computer>(); } computers.add(computer); return this; } } @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id" ) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, property = "type" ) @JsonSubTypes({ @JsonSubTypes.Type(value = DesktopComputer.class, name = "desktop"), @JsonSubTypes.Type(value = LaptopComputer.class, name = "laptop") }) static class Computer { public String id; } @JsonTypeName("desktop") static class DesktopComputer extends Computer { public String location; protected DesktopComputer() { } public DesktopComputer(String id, String loc) { this.id = id; location = loc; } } @JsonTypeName("laptop") static class LaptopComputer extends Computer { public String vendor; protected LaptopComputer() { } public LaptopComputer(String id, String v) { this.id = id; vendor = v; } } public void testSimple() throws Exception { Company comp = new Company(); comp.addComputer(new DesktopComputer("computer-1", "Bangkok")); comp.addComputer(new DesktopComputer("computer-2", "Pattaya")); comp.addComputer(new LaptopComputer("computer-3", "Apple")); final ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(comp); System.out.println("JSON: "+json); Company result = mapper.readValue(json, Company.class); assertNotNull(result); assertNotNull(result.computers); assertEquals(3, result.computers.size()); } }
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"); }
com.google.javascript.jscomp.TypeCheckTest::testQualifiedNameInference5
test/com/google/javascript/jscomp/TypeCheckTest.java
4,768
test/com/google/javascript/jscomp/TypeCheckTest.java
testQualifiedNameInference5
/* * 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\"; }", "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 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 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 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 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 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 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 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 `testQualifiedNameInference5` for the issue `Closure-66`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-66 // // ## Issue-Title: // Use @public tag to prevent compression of symbol names // // ## Issue-Description: // Given this input code: // // Glow = {}; // /\*\* @public \*/ Glow.versions = [1,2,3]; // Glow.showVersions = function() { alert(Glow.versions); } // // // exports // window['Glow'] = Glow; // Glow['versions'] = Glow.versions; // Glow['showVersions'] = Glow.showVersions; // // The compiler (with ADVANCED\_OPTIMIZATIONS on) will produce the following // output code: // // Glow = {}; // Glow.a = [1, 2, 3]; // Glow.b = function() { alert(Glow.a) }; // window.Glow = Glow; // Glow.versions = Glow.a; // Glow.showVersions = Glow.b // // From outside the Glow library, a user may do the following (in their own, // uncompressed code): // // Glow.versions = [4,5,6]; // Glow.showVersions(); // // Only in the compiled code will the user-code produces "1,2,3" instead of // the expected "4,5,6". This is because the compiler renamed the reference to // [1,2,3] in `showVersions()` to "Glow.a", whilst the user assigned a new // array to "Glow.versions", and therefore the two different names now refer // to two different arrays. // // I can avoid this by using the stringy-name to refer to Glow["versions"], // but I would then have to do that everywhere in my code which is a annoying // and bug-prone (if I or someone else should ever forget). I'd prefer to tell // the compiler once about my wish to have a property name left uncompresed, // rather than relying on a side effect (the fact that the compiler won't // compress stringy-named properties) and then having to invoke that // side-effect consistently everywhere. // // Instead I'm requesting that when the compiler sees a property is marked by // the author as @public it should then leave that name uncompressed everywhere. // // So, given the input code above, the desired output would be: // // Glow = {}; // Glow.versions = [1, 2, 3]; // Glow.b = function() { alert(Glow.versions) }; // window.Glow = Glow; // Glow.versions = Glow.versions; // not needed now // Glow.showVersions = Glow.b // // I'm not fixed on a particular tag, but @public seems an obvious choice, and // I'd prefer to use tags that already exist in JsDoc Toolkit. // // Note that my proposed feature is different than the `@export Glow.versions` // tag proposal, as that tag would merely be a shortcut for "Glow['versions'] // = Glow.versions;", which, as I've shown above, doesn't solve this problem. // // public void testQualifiedNameInference5() throws Exception {
4,768
95
4,759
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-66 ## Issue-Title: Use @public tag to prevent compression of symbol names ## Issue-Description: Given this input code: Glow = {}; /\*\* @public \*/ Glow.versions = [1,2,3]; Glow.showVersions = function() { alert(Glow.versions); } // exports window['Glow'] = Glow; Glow['versions'] = Glow.versions; Glow['showVersions'] = Glow.showVersions; The compiler (with ADVANCED\_OPTIMIZATIONS on) will produce the following output code: Glow = {}; Glow.a = [1, 2, 3]; Glow.b = function() { alert(Glow.a) }; window.Glow = Glow; Glow.versions = Glow.a; Glow.showVersions = Glow.b From outside the Glow library, a user may do the following (in their own, uncompressed code): Glow.versions = [4,5,6]; Glow.showVersions(); Only in the compiled code will the user-code produces "1,2,3" instead of the expected "4,5,6". This is because the compiler renamed the reference to [1,2,3] in `showVersions()` to "Glow.a", whilst the user assigned a new array to "Glow.versions", and therefore the two different names now refer to two different arrays. I can avoid this by using the stringy-name to refer to Glow["versions"], but I would then have to do that everywhere in my code which is a annoying and bug-prone (if I or someone else should ever forget). I'd prefer to tell the compiler once about my wish to have a property name left uncompresed, rather than relying on a side effect (the fact that the compiler won't compress stringy-named properties) and then having to invoke that side-effect consistently everywhere. Instead I'm requesting that when the compiler sees a property is marked by the author as @public it should then leave that name uncompressed everywhere. So, given the input code above, the desired output would be: Glow = {}; Glow.versions = [1, 2, 3]; Glow.b = function() { alert(Glow.versions) }; window.Glow = Glow; Glow.versions = Glow.versions; // not needed now Glow.showVersions = Glow.b I'm not fixed on a particular tag, but @public seems an obvious choice, and I'd prefer to use tags that already exist in JsDoc Toolkit. Note that my proposed feature is different than the `@export Glow.versions` tag proposal, as that tag would merely be a shortcut for "Glow['versions'] = Glow.versions;", which, as I've shown above, doesn't solve this problem. ``` You are a professional Java test case writer, please create a test case named `testQualifiedNameInference5` for the issue `Closure-66`, utilizing the provided issue report information and the following function signature. ```java public void testQualifiedNameInference5() throws Exception { ```
4,759
[ "com.google.javascript.jscomp.TypedScopeCreator" ]
bfbc014ab602774cd83c579202481870308a0394fb51d73b045b46e5a5638157
public void testQualifiedNameInference5() throws Exception
// You are a professional Java test case writer, please create a test case named `testQualifiedNameInference5` for the issue `Closure-66`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-66 // // ## Issue-Title: // Use @public tag to prevent compression of symbol names // // ## Issue-Description: // Given this input code: // // Glow = {}; // /\*\* @public \*/ Glow.versions = [1,2,3]; // Glow.showVersions = function() { alert(Glow.versions); } // // // exports // window['Glow'] = Glow; // Glow['versions'] = Glow.versions; // Glow['showVersions'] = Glow.showVersions; // // The compiler (with ADVANCED\_OPTIMIZATIONS on) will produce the following // output code: // // Glow = {}; // Glow.a = [1, 2, 3]; // Glow.b = function() { alert(Glow.a) }; // window.Glow = Glow; // Glow.versions = Glow.a; // Glow.showVersions = Glow.b // // From outside the Glow library, a user may do the following (in their own, // uncompressed code): // // Glow.versions = [4,5,6]; // Glow.showVersions(); // // Only in the compiled code will the user-code produces "1,2,3" instead of // the expected "4,5,6". This is because the compiler renamed the reference to // [1,2,3] in `showVersions()` to "Glow.a", whilst the user assigned a new // array to "Glow.versions", and therefore the two different names now refer // to two different arrays. // // I can avoid this by using the stringy-name to refer to Glow["versions"], // but I would then have to do that everywhere in my code which is a annoying // and bug-prone (if I or someone else should ever forget). I'd prefer to tell // the compiler once about my wish to have a property name left uncompresed, // rather than relying on a side effect (the fact that the compiler won't // compress stringy-named properties) and then having to invoke that // side-effect consistently everywhere. // // Instead I'm requesting that when the compiler sees a property is marked by // the author as @public it should then leave that name uncompressed everywhere. // // So, given the input code above, the desired output would be: // // Glow = {}; // Glow.versions = [1, 2, 3]; // Glow.b = function() { alert(Glow.versions) }; // window.Glow = Glow; // Glow.versions = Glow.versions; // not needed now // Glow.showVersions = Glow.b // // I'm not fixed on a particular tag, but @public seems an obvious choice, and // I'd prefer to use tags that already exist in JsDoc Toolkit. // // Note that my proposed feature is different than the `@export Glow.versions` // tag proposal, as that tag would merely be a shortcut for "Glow['versions'] // = Glow.versions;", which, as I've shown above, doesn't solve this problem. // //
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\"; }", "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 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 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 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 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 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 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 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 testBase64Text() throws Exception { // let's actually iterate over sets of encoding modes, lengths final int[] LENS = { 1, 2, 3, 4, 7, 9, 32, 33, 34, 35 }; final Base64Variant[] VARIANTS = { Base64Variants.MIME, Base64Variants.MIME_NO_LINEFEEDS, Base64Variants.MODIFIED_FOR_URL, Base64Variants.PEM }; for (int len : LENS) { byte[] input = new byte[len]; for (int i = 0; i < input.length; ++i) { input[i] = (byte) i; } for (Base64Variant variant : VARIANTS) { TextNode n = new TextNode(variant.encode(input)); byte[] data = null; try { data = n.getBinaryValue(variant); } catch (Exception e) { fail("Failed (variant "+variant+", data length "+len+"): "+e.getMessage()); } assertNotNull(data); assertArrayEquals(data, input); // 15-Aug-2018, tatu: [databind#2096] requires another test JsonParser p = new TreeTraversingParser(n); assertEquals(JsonToken.VALUE_STRING, p.nextToken()); try { data = p.getBinaryValue(variant); } catch (Exception e) { fail("Failed (variant "+variant+", data length "+len+"): "+e.getMessage()); } assertNotNull(data); assertArrayEquals(data, input); p.close(); } } }
com.fasterxml.jackson.databind.node.TestConversions::testBase64Text
src/test/java/com/fasterxml/jackson/databind/node/TestConversions.java
195
src/test/java/com/fasterxml/jackson/databind/node/TestConversions.java
testBase64Text
package com.fasterxml.jackson.databind.node; import java.io.IOException; import java.math.BigDecimal; import java.util.*; import static org.junit.Assert.*; import org.junit.Assert; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.WritableTypeId; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.util.TokenBuffer; /** * Unit tests for verifying functionality of {@link JsonNode} methods that * convert values to other types */ public class TestConversions extends BaseMapTest { static class Root { public Leaf leaf; } static class Leaf { public int value; public Leaf() { } public Leaf(int v) { value = v; } } @JsonDeserialize(using = LeafDeserializer.class) public static class LeafMixIn { } // for [databind#467] @JsonSerialize(using=Issue467Serializer.class) static class Issue467Bean { public int i; public Issue467Bean(int i0) { i = i0; } public Issue467Bean() { this(0); } } @JsonSerialize(using=Issue467TreeSerializer.class) static class Issue467Tree { } static class Issue467Serializer extends JsonSerializer<Issue467Bean> { @Override public void serialize(Issue467Bean value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeObject(new Issue467TmpBean(value.i)); } } static class Issue467TreeSerializer extends JsonSerializer<Issue467Tree> { @Override public void serialize(Issue467Tree value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeTree(BooleanNode.TRUE); } } static class Issue467TmpBean { public int x; public Issue467TmpBean(int i) { x = i; } } static class Issue709Bean { public byte[] data; } @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="_class") static class LongContainer1940 { public Long longObj; } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); public void testAsInt() throws Exception { assertEquals(9, IntNode.valueOf(9).asInt()); assertEquals(7, LongNode.valueOf(7L).asInt()); assertEquals(13, new TextNode("13").asInt()); assertEquals(0, new TextNode("foobar").asInt()); assertEquals(27, new TextNode("foobar").asInt(27)); assertEquals(1, BooleanNode.TRUE.asInt()); } public void testAsBoolean() throws Exception { assertEquals(false, BooleanNode.FALSE.asBoolean()); assertEquals(true, BooleanNode.TRUE.asBoolean()); assertEquals(false, IntNode.valueOf(0).asBoolean()); assertEquals(true, IntNode.valueOf(1).asBoolean()); assertEquals(false, LongNode.valueOf(0).asBoolean()); assertEquals(true, LongNode.valueOf(-34L).asBoolean()); assertEquals(true, new TextNode("true").asBoolean()); assertEquals(false, new TextNode("false").asBoolean()); assertEquals(false, new TextNode("barf").asBoolean()); assertEquals(true, new TextNode("barf").asBoolean(true)); assertEquals(true, new POJONode(Boolean.TRUE).asBoolean()); } // Deserializer to trigger the problem described in [JACKSON-554] public static class LeafDeserializer extends JsonDeserializer<Leaf> { @Override public Leaf deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode tree = (JsonNode) jp.readValueAsTree(); Leaf leaf = new Leaf(); leaf.value = tree.get("value").intValue(); return leaf; } } public void testTreeToValue() throws Exception { String JSON = "{\"leaf\":{\"value\":13}}"; ObjectMapper mapper = new ObjectMapper(); mapper.addMixIn(Leaf.class, LeafMixIn.class); JsonNode root = mapper.readTree(JSON); // Ok, try converting to bean using two mechanisms Root r1 = mapper.treeToValue(root, Root.class); assertNotNull(r1); assertEquals(13, r1.leaf.value); } // [databind#1208]: should coerce POJOs at least at root level public void testTreeToValueWithPOJO() throws Exception { Calendar c = Calendar.getInstance(); c.setTime(new java.util.Date(0)); ValueNode pojoNode = MAPPER.getNodeFactory().pojoNode(c); Calendar result = MAPPER.treeToValue(pojoNode, Calendar.class); assertNotNull(result); assertEquals(result.getTimeInMillis(), c.getTimeInMillis()); } public void testBase64Text() throws Exception { // let's actually iterate over sets of encoding modes, lengths final int[] LENS = { 1, 2, 3, 4, 7, 9, 32, 33, 34, 35 }; final Base64Variant[] VARIANTS = { Base64Variants.MIME, Base64Variants.MIME_NO_LINEFEEDS, Base64Variants.MODIFIED_FOR_URL, Base64Variants.PEM }; for (int len : LENS) { byte[] input = new byte[len]; for (int i = 0; i < input.length; ++i) { input[i] = (byte) i; } for (Base64Variant variant : VARIANTS) { TextNode n = new TextNode(variant.encode(input)); byte[] data = null; try { data = n.getBinaryValue(variant); } catch (Exception e) { fail("Failed (variant "+variant+", data length "+len+"): "+e.getMessage()); } assertNotNull(data); assertArrayEquals(data, input); // 15-Aug-2018, tatu: [databind#2096] requires another test JsonParser p = new TreeTraversingParser(n); assertEquals(JsonToken.VALUE_STRING, p.nextToken()); try { data = p.getBinaryValue(variant); } catch (Exception e) { fail("Failed (variant "+variant+", data length "+len+"): "+e.getMessage()); } assertNotNull(data); assertArrayEquals(data, input); p.close(); } } } /** * Simple test to verify that byte[] values can be handled properly when * converting, as long as there is metadata (from POJO definitions). */ public void testIssue709() throws Exception { byte[] inputData = new byte[] { 1, 2, 3 }; ObjectNode node = MAPPER.createObjectNode(); node.put("data", inputData); Issue709Bean result = MAPPER.treeToValue(node, Issue709Bean.class); String json = MAPPER.writeValueAsString(node); Issue709Bean resultFromString = MAPPER.readValue(json, Issue709Bean.class); Issue709Bean resultFromConvert = MAPPER.convertValue(node, Issue709Bean.class); // all methods should work equally well: Assert.assertArrayEquals(inputData, resultFromString.data); Assert.assertArrayEquals(inputData, resultFromConvert.data); Assert.assertArrayEquals(inputData, result.data); } public void testEmbeddedByteArray() throws Exception { TokenBuffer buf = new TokenBuffer(MAPPER, false); buf.writeObject(new byte[3]); JsonNode node = MAPPER.readTree(buf.asParser()); buf.close(); assertTrue(node.isBinary()); byte[] data = node.binaryValue(); assertNotNull(data); assertEquals(3, data.length); } // [databind#232] public void testBigDecimalAsPlainStringTreeConversion() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN); Map<String, Object> map = new HashMap<String, Object>(); String PI_STR = "3.00000000"; map.put("pi", new BigDecimal(PI_STR)); JsonNode tree = mapper.valueToTree(map); assertNotNull(tree); assertEquals(1, tree.size()); assertTrue(tree.has("pi")); } static class CustomSerializedPojo implements JsonSerializable { private final ObjectNode node = JsonNodeFactory.instance.objectNode(); public void setFoo(final String foo) { node.put("foo", foo); } @Override public void serialize(final JsonGenerator jgen, final SerializerProvider provider) throws IOException { jgen.writeTree(node); } @Override public void serializeWithType(JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) throws IOException { WritableTypeId typeIdDef = new WritableTypeId(this, JsonToken.START_OBJECT); typeSer.writeTypePrefix(g, typeIdDef); serialize(g, provider); typeSer.writeTypePrefix(g, typeIdDef); } } // [databind#433] public void testBeanToTree() throws Exception { final CustomSerializedPojo pojo = new CustomSerializedPojo(); pojo.setFoo("bar"); final JsonNode node = MAPPER.valueToTree(pojo); assertEquals(JsonNodeType.OBJECT, node.getNodeType()); } // [databind#467] public void testConversionOfPojos() throws Exception { final Issue467Bean input = new Issue467Bean(13); final String EXP = "{\"x\":13}"; // first, sanity check String json = MAPPER.writeValueAsString(input); assertEquals(EXP, json); // then via conversions: should become JSON Object JsonNode tree = MAPPER.valueToTree(input); assertTrue("Expected Object, got "+tree.getNodeType(), tree.isObject()); assertEquals(EXP, MAPPER.writeValueAsString(tree)); } // [databind#467] public void testConversionOfTrees() throws Exception { final Issue467Tree input = new Issue467Tree(); final String EXP = "true"; // first, sanity check String json = MAPPER.writeValueAsString(input); assertEquals(EXP, json); // then via conversions: should become JSON Object JsonNode tree = MAPPER.valueToTree(input); assertTrue("Expected Object, got "+tree.getNodeType(), tree.isBoolean()); assertEquals(EXP, MAPPER.writeValueAsString(tree)); } // [databind#1940]: losing of precision due to coercion public void testBufferedLongViaCoercion() throws Exception { long EXP = 1519348261000L; JsonNode tree = MAPPER.readTree("{\"longObj\": "+EXP+".0, \"_class\": \""+LongContainer1940.class.getName()+"\"}"); LongContainer1940 obj = MAPPER.treeToValue(tree, LongContainer1940.class); assertEquals(Long.valueOf(EXP), obj.longObj); } }
// You are a professional Java test case writer, please create a test case named `testBase64Text` for the issue `JacksonDatabind-2096`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2096 // // ## Issue-Title: // TreeTraversingParser does not take base64 variant into account // // ## Issue-Description: // This affects at least 2.6.4 to current versions. In [TreeTraversingParser#getBinaryValue](https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/node/TreeTraversingParser.java#L348), a `Base64Variant` is accepted but ignored. The call to `n.binaryValue()`, when `n` is a `TextNode`, then uses the default Base64 variant instead of what's specified. It seems the correct behavior would be to call `TextNode#getBinaryValue` instead. // // // // public void testBase64Text() throws Exception {
195
100
154
src/test/java/com/fasterxml/jackson/databind/node/TestConversions.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-2096 ## Issue-Title: TreeTraversingParser does not take base64 variant into account ## Issue-Description: This affects at least 2.6.4 to current versions. In [TreeTraversingParser#getBinaryValue](https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/node/TreeTraversingParser.java#L348), a `Base64Variant` is accepted but ignored. The call to `n.binaryValue()`, when `n` is a `TextNode`, then uses the default Base64 variant instead of what's specified. It seems the correct behavior would be to call `TextNode#getBinaryValue` instead. ``` You are a professional Java test case writer, please create a test case named `testBase64Text` for the issue `JacksonDatabind-2096`, utilizing the provided issue report information and the following function signature. ```java public void testBase64Text() throws Exception { ```
154
[ "com.fasterxml.jackson.databind.node.TreeTraversingParser" ]
c0e9d9ffff9045a778ddb3fb22b5e908fdb6155b60b82042ddb3c2b6060ecd22
public void testBase64Text() throws Exception
// You are a professional Java test case writer, please create a test case named `testBase64Text` for the issue `JacksonDatabind-2096`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2096 // // ## Issue-Title: // TreeTraversingParser does not take base64 variant into account // // ## Issue-Description: // This affects at least 2.6.4 to current versions. In [TreeTraversingParser#getBinaryValue](https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/node/TreeTraversingParser.java#L348), a `Base64Variant` is accepted but ignored. The call to `n.binaryValue()`, when `n` is a `TextNode`, then uses the default Base64 variant instead of what's specified. It seems the correct behavior would be to call `TextNode#getBinaryValue` instead. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.node; import java.io.IOException; import java.math.BigDecimal; import java.util.*; import static org.junit.Assert.*; import org.junit.Assert; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.type.WritableTypeId; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.util.TokenBuffer; /** * Unit tests for verifying functionality of {@link JsonNode} methods that * convert values to other types */ public class TestConversions extends BaseMapTest { static class Root { public Leaf leaf; } static class Leaf { public int value; public Leaf() { } public Leaf(int v) { value = v; } } @JsonDeserialize(using = LeafDeserializer.class) public static class LeafMixIn { } // for [databind#467] @JsonSerialize(using=Issue467Serializer.class) static class Issue467Bean { public int i; public Issue467Bean(int i0) { i = i0; } public Issue467Bean() { this(0); } } @JsonSerialize(using=Issue467TreeSerializer.class) static class Issue467Tree { } static class Issue467Serializer extends JsonSerializer<Issue467Bean> { @Override public void serialize(Issue467Bean value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeObject(new Issue467TmpBean(value.i)); } } static class Issue467TreeSerializer extends JsonSerializer<Issue467Tree> { @Override public void serialize(Issue467Tree value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeTree(BooleanNode.TRUE); } } static class Issue467TmpBean { public int x; public Issue467TmpBean(int i) { x = i; } } static class Issue709Bean { public byte[] data; } @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="_class") static class LongContainer1940 { public Long longObj; } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = objectMapper(); public void testAsInt() throws Exception { assertEquals(9, IntNode.valueOf(9).asInt()); assertEquals(7, LongNode.valueOf(7L).asInt()); assertEquals(13, new TextNode("13").asInt()); assertEquals(0, new TextNode("foobar").asInt()); assertEquals(27, new TextNode("foobar").asInt(27)); assertEquals(1, BooleanNode.TRUE.asInt()); } public void testAsBoolean() throws Exception { assertEquals(false, BooleanNode.FALSE.asBoolean()); assertEquals(true, BooleanNode.TRUE.asBoolean()); assertEquals(false, IntNode.valueOf(0).asBoolean()); assertEquals(true, IntNode.valueOf(1).asBoolean()); assertEquals(false, LongNode.valueOf(0).asBoolean()); assertEquals(true, LongNode.valueOf(-34L).asBoolean()); assertEquals(true, new TextNode("true").asBoolean()); assertEquals(false, new TextNode("false").asBoolean()); assertEquals(false, new TextNode("barf").asBoolean()); assertEquals(true, new TextNode("barf").asBoolean(true)); assertEquals(true, new POJONode(Boolean.TRUE).asBoolean()); } // Deserializer to trigger the problem described in [JACKSON-554] public static class LeafDeserializer extends JsonDeserializer<Leaf> { @Override public Leaf deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode tree = (JsonNode) jp.readValueAsTree(); Leaf leaf = new Leaf(); leaf.value = tree.get("value").intValue(); return leaf; } } public void testTreeToValue() throws Exception { String JSON = "{\"leaf\":{\"value\":13}}"; ObjectMapper mapper = new ObjectMapper(); mapper.addMixIn(Leaf.class, LeafMixIn.class); JsonNode root = mapper.readTree(JSON); // Ok, try converting to bean using two mechanisms Root r1 = mapper.treeToValue(root, Root.class); assertNotNull(r1); assertEquals(13, r1.leaf.value); } // [databind#1208]: should coerce POJOs at least at root level public void testTreeToValueWithPOJO() throws Exception { Calendar c = Calendar.getInstance(); c.setTime(new java.util.Date(0)); ValueNode pojoNode = MAPPER.getNodeFactory().pojoNode(c); Calendar result = MAPPER.treeToValue(pojoNode, Calendar.class); assertNotNull(result); assertEquals(result.getTimeInMillis(), c.getTimeInMillis()); } public void testBase64Text() throws Exception { // let's actually iterate over sets of encoding modes, lengths final int[] LENS = { 1, 2, 3, 4, 7, 9, 32, 33, 34, 35 }; final Base64Variant[] VARIANTS = { Base64Variants.MIME, Base64Variants.MIME_NO_LINEFEEDS, Base64Variants.MODIFIED_FOR_URL, Base64Variants.PEM }; for (int len : LENS) { byte[] input = new byte[len]; for (int i = 0; i < input.length; ++i) { input[i] = (byte) i; } for (Base64Variant variant : VARIANTS) { TextNode n = new TextNode(variant.encode(input)); byte[] data = null; try { data = n.getBinaryValue(variant); } catch (Exception e) { fail("Failed (variant "+variant+", data length "+len+"): "+e.getMessage()); } assertNotNull(data); assertArrayEquals(data, input); // 15-Aug-2018, tatu: [databind#2096] requires another test JsonParser p = new TreeTraversingParser(n); assertEquals(JsonToken.VALUE_STRING, p.nextToken()); try { data = p.getBinaryValue(variant); } catch (Exception e) { fail("Failed (variant "+variant+", data length "+len+"): "+e.getMessage()); } assertNotNull(data); assertArrayEquals(data, input); p.close(); } } } /** * Simple test to verify that byte[] values can be handled properly when * converting, as long as there is metadata (from POJO definitions). */ public void testIssue709() throws Exception { byte[] inputData = new byte[] { 1, 2, 3 }; ObjectNode node = MAPPER.createObjectNode(); node.put("data", inputData); Issue709Bean result = MAPPER.treeToValue(node, Issue709Bean.class); String json = MAPPER.writeValueAsString(node); Issue709Bean resultFromString = MAPPER.readValue(json, Issue709Bean.class); Issue709Bean resultFromConvert = MAPPER.convertValue(node, Issue709Bean.class); // all methods should work equally well: Assert.assertArrayEquals(inputData, resultFromString.data); Assert.assertArrayEquals(inputData, resultFromConvert.data); Assert.assertArrayEquals(inputData, result.data); } public void testEmbeddedByteArray() throws Exception { TokenBuffer buf = new TokenBuffer(MAPPER, false); buf.writeObject(new byte[3]); JsonNode node = MAPPER.readTree(buf.asParser()); buf.close(); assertTrue(node.isBinary()); byte[] data = node.binaryValue(); assertNotNull(data); assertEquals(3, data.length); } // [databind#232] public void testBigDecimalAsPlainStringTreeConversion() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN); Map<String, Object> map = new HashMap<String, Object>(); String PI_STR = "3.00000000"; map.put("pi", new BigDecimal(PI_STR)); JsonNode tree = mapper.valueToTree(map); assertNotNull(tree); assertEquals(1, tree.size()); assertTrue(tree.has("pi")); } static class CustomSerializedPojo implements JsonSerializable { private final ObjectNode node = JsonNodeFactory.instance.objectNode(); public void setFoo(final String foo) { node.put("foo", foo); } @Override public void serialize(final JsonGenerator jgen, final SerializerProvider provider) throws IOException { jgen.writeTree(node); } @Override public void serializeWithType(JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) throws IOException { WritableTypeId typeIdDef = new WritableTypeId(this, JsonToken.START_OBJECT); typeSer.writeTypePrefix(g, typeIdDef); serialize(g, provider); typeSer.writeTypePrefix(g, typeIdDef); } } // [databind#433] public void testBeanToTree() throws Exception { final CustomSerializedPojo pojo = new CustomSerializedPojo(); pojo.setFoo("bar"); final JsonNode node = MAPPER.valueToTree(pojo); assertEquals(JsonNodeType.OBJECT, node.getNodeType()); } // [databind#467] public void testConversionOfPojos() throws Exception { final Issue467Bean input = new Issue467Bean(13); final String EXP = "{\"x\":13}"; // first, sanity check String json = MAPPER.writeValueAsString(input); assertEquals(EXP, json); // then via conversions: should become JSON Object JsonNode tree = MAPPER.valueToTree(input); assertTrue("Expected Object, got "+tree.getNodeType(), tree.isObject()); assertEquals(EXP, MAPPER.writeValueAsString(tree)); } // [databind#467] public void testConversionOfTrees() throws Exception { final Issue467Tree input = new Issue467Tree(); final String EXP = "true"; // first, sanity check String json = MAPPER.writeValueAsString(input); assertEquals(EXP, json); // then via conversions: should become JSON Object JsonNode tree = MAPPER.valueToTree(input); assertTrue("Expected Object, got "+tree.getNodeType(), tree.isBoolean()); assertEquals(EXP, MAPPER.writeValueAsString(tree)); } // [databind#1940]: losing of precision due to coercion public void testBufferedLongViaCoercion() throws Exception { long EXP = 1519348261000L; JsonNode tree = MAPPER.readTree("{\"longObj\": "+EXP+".0, \"_class\": \""+LongContainer1940.class.getName()+"\"}"); LongContainer1940 obj = MAPPER.treeToValue(tree, LongContainer1940.class); assertEquals(Long.valueOf(EXP), obj.longObj); } }
public void testAddNonComparable(){ try { f.addValue(new Object()); // This was previously OK fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } f.clear(); f.addValue(1); try { f.addValue(new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } }
org.apache.commons.math.stat.FrequencyTest::testAddNonComparable
src/test/org/apache/commons/math/stat/FrequencyTest.java
205
src/test/org/apache/commons/math/stat/FrequencyTest.java
testAddNonComparable
/* * 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; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import org.apache.commons.math.TestUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test cases for the {@link Frequency} class. * * @version $Revision$ $Date$ */ public final class FrequencyTest extends TestCase { private long oneL = 1; private long twoL = 2; private long threeL = 3; private int oneI = 1; private int twoI = 2; private int threeI=3; private double tolerance = 10E-15; private Frequency f = null; public FrequencyTest(String name) { super(name); } @Override public void setUp() { f = new Frequency(); } public static Test suite() { TestSuite suite = new TestSuite(FrequencyTest.class); suite.setName("Frequency Tests"); return suite; } /** test freq counts */ public void testCounts() { assertEquals("total count",0,f.getSumFreq()); f.addValue(oneL); f.addValue(twoL); f.addValue(1); f.addValue(oneI); assertEquals("one frequency count",3,f.getCount(1)); assertEquals("two frequency count",1,f.getCount(2)); assertEquals("three frequency count",0,f.getCount(3)); assertEquals("total count",4,f.getSumFreq()); assertEquals("zero cumulative frequency", 0, f.getCumFreq(0)); assertEquals("one cumulative frequency", 3, f.getCumFreq(1)); assertEquals("two cumulative frequency", 4, f.getCumFreq(2)); assertEquals("Integer argument cum freq",4, f.getCumFreq(Integer.valueOf(2))); assertEquals("five cumulative frequency", 4, f.getCumFreq(5)); assertEquals("foo cumulative frequency", 0, f.getCumFreq("foo")); f.clear(); assertEquals("total count",0,f.getSumFreq()); // userguide examples ------------------------------------------------------------------- f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one cumulative frequency", 1 , f.getCount("one")); assertEquals("Z cumulative pct", 0.5, f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct", 1.0, f.getCumPct("z"), tolerance); assertEquals("Ot cumulative pct", 0.25, f.getCumPct("Ot"), tolerance); f.clear(); f = null; Frequency f = new Frequency(); f.addValue(1); f.addValue(Integer.valueOf(1)); f.addValue(Long.valueOf(1)); f.addValue(2); f.addValue(Integer.valueOf(-1)); assertEquals("1 count", 3, f.getCount(1)); assertEquals("1 count", 3, f.getCount(Integer.valueOf(1))); assertEquals("0 cum pct", 0.2, f.getCumPct(0), tolerance); assertEquals("1 pct", 0.6, f.getPct(Integer.valueOf(1)), tolerance); assertEquals("-2 cum pct", 0, f.getCumPct(-2), tolerance); assertEquals("10 cum pct", 1, f.getCumPct(10), tolerance); f = null; f = new Frequency(String.CASE_INSENSITIVE_ORDER); f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one count", 3 , f.getCount("one")); assertEquals("Z cumulative pct -- case insensitive", 1 , f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct -- case insensitive", 1 , f.getCumPct("z"), tolerance); f = null; f = new Frequency(); assertEquals(0L, f.getCount('a')); assertEquals(0L, f.getCumFreq('b')); TestUtils.assertEquals(Double.NaN, f.getPct('a'), 0.0); TestUtils.assertEquals(Double.NaN, f.getCumPct('b'), 0.0); f.addValue('a'); f.addValue('b'); f.addValue('c'); f.addValue('d'); assertEquals(1L, f.getCount('a')); assertEquals(2L, f.getCumFreq('b')); assertEquals(0.25, f.getPct('a'), 0.0); assertEquals(0.5, f.getCumPct('b'), 0.0); assertEquals(1.0, f.getCumPct('e'), 0.0); } /** test pcts */ public void testPcts() { f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); f.addValue(threeL); f.addValue(threeL); f.addValue(3); f.addValue(threeI); assertEquals("one pct",0.25,f.getPct(1),tolerance); assertEquals("two pct",0.25,f.getPct(Long.valueOf(2)),tolerance); assertEquals("three pct",0.5,f.getPct(threeL),tolerance); assertEquals("five pct",0,f.getPct(5),tolerance); assertEquals("foo pct",0,f.getPct("foo"),tolerance); assertEquals("one cum pct",0.25,f.getCumPct(1),tolerance); assertEquals("two cum pct",0.50,f.getCumPct(Long.valueOf(2)),tolerance); assertEquals("Integer argument",0.50,f.getCumPct(Integer.valueOf(2)),tolerance); assertEquals("three cum pct",1.0,f.getCumPct(threeL),tolerance); assertEquals("five cum pct",1.0,f.getCumPct(5),tolerance); assertEquals("zero cum pct",0.0,f.getCumPct(0),tolerance); assertEquals("foo cum pct",0,f.getCumPct("foo"),tolerance); } /** test adding incomparable values */ public void testAdd() { char aChar = 'a'; char bChar = 'b'; String aString = "a"; f.addValue(aChar); f.addValue(bChar); try { f.addValue(aString); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } try { f.addValue(2); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } assertEquals("a pct",0.5,f.getPct(aChar),tolerance); assertEquals("b cum pct",1.0,f.getCumPct(bChar),tolerance); assertEquals("a string pct",0.0,f.getPct(aString),tolerance); assertEquals("a string cum pct",0.0,f.getCumPct(aString),tolerance); f = new Frequency(); f.addValue("One"); try { f.addValue(new Integer("One")); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } // Check what happens when non-Comparable objects are added public void testAddNonComparable(){ try { f.addValue(new Object()); // This was previously OK fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } f.clear(); f.addValue(1); try { f.addValue(new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } /** test empty table */ public void testEmptyTable() { assertEquals("freq sum, empty table", 0, f.getSumFreq()); assertEquals("count, empty table", 0, f.getCount(0)); assertEquals("count, empty table",0, f.getCount(Integer.valueOf(0))); assertEquals("cum freq, empty table", 0, f.getCumFreq(0)); assertEquals("cum freq, empty table", 0, f.getCumFreq("x")); assertTrue("pct, empty table", Double.isNaN(f.getPct(0))); assertTrue("pct, empty table", Double.isNaN(f.getPct(Integer.valueOf(0)))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(0))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(Integer.valueOf(0)))); } /** * Tests toString() */ public void testToString(){ f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); String s = f.toString(); //System.out.println(s); assertNotNull(s); BufferedReader reader = new BufferedReader(new StringReader(s)); try { String line = reader.readLine(); // header line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // no more elements assertNull(line); } catch(IOException ex){ fail(ex.getMessage()); } } public void testIntegerValues() { Object obj1 = null; obj1 = Integer.valueOf(1); Integer int1 = Integer.valueOf(1); f.addValue(obj1); f.addValue(int1); f.addValue(2); f.addValue(Long.valueOf(2)); assertEquals("Integer 1 count", 2, f.getCount(1)); assertEquals("Integer 1 count", 2, f.getCount(Integer.valueOf(1))); assertEquals("Integer 1 count", 2, f.getCount(Long.valueOf(1))); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(1), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Long.valueOf(1)), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Integer.valueOf(1)), tolerance); Iterator<?> it = f.valuesIterator(); while (it.hasNext()) { assertTrue(it.next() instanceof Long); } } }
// You are a professional Java test case writer, please create a test case named `testAddNonComparable` for the issue `Math-MATH-259`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-259 // // ## Issue-Title: // Bugs in Frequency API // // ## Issue-Description: // // I think the existing Frequency API has some bugs in it. // // // The addValue(Object v) method allows one to add a plain Object, but one cannot add anything further to the instance, as the second add fails with IllegalArgumentException. // // In fact, the problem is with the first call to addValue(Object) which should not allow a plain Object to be added - it should only allow Comparable objects. // // This could be fixed by checking that the object is Comparable. // // // Similar considerations apply to the getCumFreq(Object) and getCumPct(Object) methods - they will only work with objects that implement Comparable. // // // The getCount(Object) and getPct(Object) methods don't fail when given a non-Comparable object (because the class cast exception is caught), however they just return 0 as if the object was not present: // // // // // ``` // final Object OBJ = new Object(); // f.addValue(OBJ); // This ought to fail, but doesn't, causing the unexpected behaviour below // System.out.println(f.getCount(OBJ)); // 0 // System.out.println(f.getPct(OBJ)); // 0.0 // // ``` // // // Rather than adding extra checks for Comparable, it seems to me that the API would be much improved by using Comparable instead of Object. // // Also, it should make it easier to implement generics. // // // However, this would cause compilation failures for some programs that pass Object rather than Comparable to the class. // // These would need recoding, but I think they would continue to run OK against the new API. // // // It would also affect the run-time behaviour slightly, as the first attempt to add a non-Comparable object would fail, rather than the second add of a possibly valid object. // // But is that a viable program? It can only add one object, and any attempt to get statistics will either return 0 or an Exception, and applying the instanceof fix would also cause it to fail. // // // // // public void testAddNonComparable() {
205
// Check what happens when non-Comparable objects are added
89
192
src/test/org/apache/commons/math/stat/FrequencyTest.java
src/test
```markdown ## Issue-ID: Math-MATH-259 ## Issue-Title: Bugs in Frequency API ## Issue-Description: I think the existing Frequency API has some bugs in it. The addValue(Object v) method allows one to add a plain Object, but one cannot add anything further to the instance, as the second add fails with IllegalArgumentException. In fact, the problem is with the first call to addValue(Object) which should not allow a plain Object to be added - it should only allow Comparable objects. This could be fixed by checking that the object is Comparable. Similar considerations apply to the getCumFreq(Object) and getCumPct(Object) methods - they will only work with objects that implement Comparable. The getCount(Object) and getPct(Object) methods don't fail when given a non-Comparable object (because the class cast exception is caught), however they just return 0 as if the object was not present: ``` final Object OBJ = new Object(); f.addValue(OBJ); // This ought to fail, but doesn't, causing the unexpected behaviour below System.out.println(f.getCount(OBJ)); // 0 System.out.println(f.getPct(OBJ)); // 0.0 ``` Rather than adding extra checks for Comparable, it seems to me that the API would be much improved by using Comparable instead of Object. Also, it should make it easier to implement generics. However, this would cause compilation failures for some programs that pass Object rather than Comparable to the class. These would need recoding, but I think they would continue to run OK against the new API. It would also affect the run-time behaviour slightly, as the first attempt to add a non-Comparable object would fail, rather than the second add of a possibly valid object. But is that a viable program? It can only add one object, and any attempt to get statistics will either return 0 or an Exception, and applying the instanceof fix would also cause it to fail. ``` You are a professional Java test case writer, please create a test case named `testAddNonComparable` for the issue `Math-MATH-259`, utilizing the provided issue report information and the following function signature. ```java public void testAddNonComparable() { ```
192
[ "org.apache.commons.math.stat.Frequency" ]
c1014e9d24b10cdd8cbb06333502a5ada785f563208a505df2fc455c44800ddb
public void testAddNonComparable()
// You are a professional Java test case writer, please create a test case named `testAddNonComparable` for the issue `Math-MATH-259`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-259 // // ## Issue-Title: // Bugs in Frequency API // // ## Issue-Description: // // I think the existing Frequency API has some bugs in it. // // // The addValue(Object v) method allows one to add a plain Object, but one cannot add anything further to the instance, as the second add fails with IllegalArgumentException. // // In fact, the problem is with the first call to addValue(Object) which should not allow a plain Object to be added - it should only allow Comparable objects. // // This could be fixed by checking that the object is Comparable. // // // Similar considerations apply to the getCumFreq(Object) and getCumPct(Object) methods - they will only work with objects that implement Comparable. // // // The getCount(Object) and getPct(Object) methods don't fail when given a non-Comparable object (because the class cast exception is caught), however they just return 0 as if the object was not present: // // // // // ``` // final Object OBJ = new Object(); // f.addValue(OBJ); // This ought to fail, but doesn't, causing the unexpected behaviour below // System.out.println(f.getCount(OBJ)); // 0 // System.out.println(f.getPct(OBJ)); // 0.0 // // ``` // // // Rather than adding extra checks for Comparable, it seems to me that the API would be much improved by using Comparable instead of Object. // // Also, it should make it easier to implement generics. // // // However, this would cause compilation failures for some programs that pass Object rather than Comparable to the class. // // These would need recoding, but I think they would continue to run OK against the new API. // // // It would also affect the run-time behaviour slightly, as the first attempt to add a non-Comparable object would fail, rather than the second add of a possibly valid object. // // But is that a viable program? It can only add one object, and any attempt to get statistics will either return 0 or an Exception, and applying the instanceof fix would also cause it to fail. // // // // //
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; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import org.apache.commons.math.TestUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test cases for the {@link Frequency} class. * * @version $Revision$ $Date$ */ public final class FrequencyTest extends TestCase { private long oneL = 1; private long twoL = 2; private long threeL = 3; private int oneI = 1; private int twoI = 2; private int threeI=3; private double tolerance = 10E-15; private Frequency f = null; public FrequencyTest(String name) { super(name); } @Override public void setUp() { f = new Frequency(); } public static Test suite() { TestSuite suite = new TestSuite(FrequencyTest.class); suite.setName("Frequency Tests"); return suite; } /** test freq counts */ public void testCounts() { assertEquals("total count",0,f.getSumFreq()); f.addValue(oneL); f.addValue(twoL); f.addValue(1); f.addValue(oneI); assertEquals("one frequency count",3,f.getCount(1)); assertEquals("two frequency count",1,f.getCount(2)); assertEquals("three frequency count",0,f.getCount(3)); assertEquals("total count",4,f.getSumFreq()); assertEquals("zero cumulative frequency", 0, f.getCumFreq(0)); assertEquals("one cumulative frequency", 3, f.getCumFreq(1)); assertEquals("two cumulative frequency", 4, f.getCumFreq(2)); assertEquals("Integer argument cum freq",4, f.getCumFreq(Integer.valueOf(2))); assertEquals("five cumulative frequency", 4, f.getCumFreq(5)); assertEquals("foo cumulative frequency", 0, f.getCumFreq("foo")); f.clear(); assertEquals("total count",0,f.getSumFreq()); // userguide examples ------------------------------------------------------------------- f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one cumulative frequency", 1 , f.getCount("one")); assertEquals("Z cumulative pct", 0.5, f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct", 1.0, f.getCumPct("z"), tolerance); assertEquals("Ot cumulative pct", 0.25, f.getCumPct("Ot"), tolerance); f.clear(); f = null; Frequency f = new Frequency(); f.addValue(1); f.addValue(Integer.valueOf(1)); f.addValue(Long.valueOf(1)); f.addValue(2); f.addValue(Integer.valueOf(-1)); assertEquals("1 count", 3, f.getCount(1)); assertEquals("1 count", 3, f.getCount(Integer.valueOf(1))); assertEquals("0 cum pct", 0.2, f.getCumPct(0), tolerance); assertEquals("1 pct", 0.6, f.getPct(Integer.valueOf(1)), tolerance); assertEquals("-2 cum pct", 0, f.getCumPct(-2), tolerance); assertEquals("10 cum pct", 1, f.getCumPct(10), tolerance); f = null; f = new Frequency(String.CASE_INSENSITIVE_ORDER); f.addValue("one"); f.addValue("One"); f.addValue("oNe"); f.addValue("Z"); assertEquals("one count", 3 , f.getCount("one")); assertEquals("Z cumulative pct -- case insensitive", 1 , f.getCumPct("Z"), tolerance); assertEquals("z cumulative pct -- case insensitive", 1 , f.getCumPct("z"), tolerance); f = null; f = new Frequency(); assertEquals(0L, f.getCount('a')); assertEquals(0L, f.getCumFreq('b')); TestUtils.assertEquals(Double.NaN, f.getPct('a'), 0.0); TestUtils.assertEquals(Double.NaN, f.getCumPct('b'), 0.0); f.addValue('a'); f.addValue('b'); f.addValue('c'); f.addValue('d'); assertEquals(1L, f.getCount('a')); assertEquals(2L, f.getCumFreq('b')); assertEquals(0.25, f.getPct('a'), 0.0); assertEquals(0.5, f.getCumPct('b'), 0.0); assertEquals(1.0, f.getCumPct('e'), 0.0); } /** test pcts */ public void testPcts() { f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); f.addValue(threeL); f.addValue(threeL); f.addValue(3); f.addValue(threeI); assertEquals("one pct",0.25,f.getPct(1),tolerance); assertEquals("two pct",0.25,f.getPct(Long.valueOf(2)),tolerance); assertEquals("three pct",0.5,f.getPct(threeL),tolerance); assertEquals("five pct",0,f.getPct(5),tolerance); assertEquals("foo pct",0,f.getPct("foo"),tolerance); assertEquals("one cum pct",0.25,f.getCumPct(1),tolerance); assertEquals("two cum pct",0.50,f.getCumPct(Long.valueOf(2)),tolerance); assertEquals("Integer argument",0.50,f.getCumPct(Integer.valueOf(2)),tolerance); assertEquals("three cum pct",1.0,f.getCumPct(threeL),tolerance); assertEquals("five cum pct",1.0,f.getCumPct(5),tolerance); assertEquals("zero cum pct",0.0,f.getCumPct(0),tolerance); assertEquals("foo cum pct",0,f.getCumPct("foo"),tolerance); } /** test adding incomparable values */ public void testAdd() { char aChar = 'a'; char bChar = 'b'; String aString = "a"; f.addValue(aChar); f.addValue(bChar); try { f.addValue(aString); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } try { f.addValue(2); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } assertEquals("a pct",0.5,f.getPct(aChar),tolerance); assertEquals("b cum pct",1.0,f.getCumPct(bChar),tolerance); assertEquals("a string pct",0.0,f.getPct(aString),tolerance); assertEquals("a string cum pct",0.0,f.getCumPct(aString),tolerance); f = new Frequency(); f.addValue("One"); try { f.addValue(new Integer("One")); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } // Check what happens when non-Comparable objects are added public void testAddNonComparable(){ try { f.addValue(new Object()); // This was previously OK fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } f.clear(); f.addValue(1); try { f.addValue(new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } /** test empty table */ public void testEmptyTable() { assertEquals("freq sum, empty table", 0, f.getSumFreq()); assertEquals("count, empty table", 0, f.getCount(0)); assertEquals("count, empty table",0, f.getCount(Integer.valueOf(0))); assertEquals("cum freq, empty table", 0, f.getCumFreq(0)); assertEquals("cum freq, empty table", 0, f.getCumFreq("x")); assertTrue("pct, empty table", Double.isNaN(f.getPct(0))); assertTrue("pct, empty table", Double.isNaN(f.getPct(Integer.valueOf(0)))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(0))); assertTrue("cum pct, empty table", Double.isNaN(f.getCumPct(Integer.valueOf(0)))); } /** * Tests toString() */ public void testToString(){ f.addValue(oneL); f.addValue(twoL); f.addValue(oneI); f.addValue(twoI); String s = f.toString(); //System.out.println(s); assertNotNull(s); BufferedReader reader = new BufferedReader(new StringReader(s)); try { String line = reader.readLine(); // header line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // one's or two's line assertNotNull(line); line = reader.readLine(); // no more elements assertNull(line); } catch(IOException ex){ fail(ex.getMessage()); } } public void testIntegerValues() { Object obj1 = null; obj1 = Integer.valueOf(1); Integer int1 = Integer.valueOf(1); f.addValue(obj1); f.addValue(int1); f.addValue(2); f.addValue(Long.valueOf(2)); assertEquals("Integer 1 count", 2, f.getCount(1)); assertEquals("Integer 1 count", 2, f.getCount(Integer.valueOf(1))); assertEquals("Integer 1 count", 2, f.getCount(Long.valueOf(1))); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(1), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Long.valueOf(1)), tolerance); assertEquals("Integer 1 cumPct", 0.5, f.getCumPct(Integer.valueOf(1)), tolerance); Iterator<?> it = f.valuesIterator(); while (it.hasNext()) { assertTrue(it.next() instanceof Long); } } }
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;" + "}"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue669
test/com/google/javascript/jscomp/TypeCheckTest.java
5,632
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue669
/* * 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.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 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, CodingConventions.getDefault()).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 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 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 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.<number>\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 testParameterizedObject5() 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 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 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 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=): 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-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 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 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 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 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}", "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 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 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 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): 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 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 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 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;}", "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 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"); 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 + "/** @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 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 { // TODO(nicksantos): This should emit a warning. 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 (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); */ } 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 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 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 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 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} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } 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 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;" + "}"); } /** * 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 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 { 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); 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 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 { // We currently do not support goog.bind natively. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): 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 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 {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 Object\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 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() {}" + "/** @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 { 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. May be 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()"); 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 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 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 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 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 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() {};"); 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()); } 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("number")); } 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()); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } 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 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 : Object\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; 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, null, 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( "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()); 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(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, 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 `testIssue669` for the issue `Closure-669`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-669 // // ## Issue-Title: // assignment to object in conditional causes type error on function w/ record type return type // // ## Issue-Description: // slightly dodgy code :) // // /\*\* @returns {{prop1: (Object|undefined), prop2: (string|undefined), prop3: (string|undefined)}} \*/ // function func(a, b) { // var results; // if (a) { // results = {}; // results.prop1 = {a: 3}; // } // if (b) { // results = results || {}; // results.prop2 = 'prop2'; // } else { // results = results || {}; // results.prop3 = 'prop3'; // } // return results; // } // results in this error: // // // JSC\_TYPE\_MISMATCH: inconsistent return type // found : ({prop1: {a: number}}|{}) // required: {prop1: (Object|null|undefined), prop2: (string|undefined), prop3: (string|undefined)} at line 18 character 7 // return results; // // // // defining results on the first line on the function causes it the world. // the still dodgy, but slightly less so, use of this is if the function return type were that record type|undefined and not all branches were guaranteed to be executed. // // public void testIssue669() throws Exception {
5,632
35
5,619
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-669 ## Issue-Title: assignment to object in conditional causes type error on function w/ record type return type ## Issue-Description: slightly dodgy code :) /\*\* @returns {{prop1: (Object|undefined), prop2: (string|undefined), prop3: (string|undefined)}} \*/ function func(a, b) { var results; if (a) { results = {}; results.prop1 = {a: 3}; } if (b) { results = results || {}; results.prop2 = 'prop2'; } else { results = results || {}; results.prop3 = 'prop3'; } return results; } results in this error: JSC\_TYPE\_MISMATCH: inconsistent return type found : ({prop1: {a: number}}|{}) required: {prop1: (Object|null|undefined), prop2: (string|undefined), prop3: (string|undefined)} at line 18 character 7 return results; defining results on the first line on the function causes it the world. the still dodgy, but slightly less so, use of this is if the function return type were that record type|undefined and not all branches were guaranteed to be executed. ``` You are a professional Java test case writer, please create a test case named `testIssue669` for the issue `Closure-669`, utilizing the provided issue report information and the following function signature. ```java public void testIssue669() throws Exception { ```
5,619
[ "com.google.javascript.jscomp.TypeInference" ]
c529612217861f4eb83f8bcb1ba9db4bea48b1f6646f7aa3bf394ebfe4a7a831
public void testIssue669() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue669` for the issue `Closure-669`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-669 // // ## Issue-Title: // assignment to object in conditional causes type error on function w/ record type return type // // ## Issue-Description: // slightly dodgy code :) // // /\*\* @returns {{prop1: (Object|undefined), prop2: (string|undefined), prop3: (string|undefined)}} \*/ // function func(a, b) { // var results; // if (a) { // results = {}; // results.prop1 = {a: 3}; // } // if (b) { // results = results || {}; // results.prop2 = 'prop2'; // } else { // results = results || {}; // results.prop3 = 'prop3'; // } // return results; // } // results in this error: // // // JSC\_TYPE\_MISMATCH: inconsistent return type // found : ({prop1: {a: number}}|{}) // required: {prop1: (Object|null|undefined), prop2: (string|undefined), prop3: (string|undefined)} at line 18 character 7 // return results; // // // // defining results on the first line on the function causes it the world. // the still dodgy, but slightly less so, use of this is if the function return type were that record type|undefined and not all branches were guaranteed to be executed. // //
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.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 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, CodingConventions.getDefault()).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 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 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 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.<number>\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 testParameterizedObject5() 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 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 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 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=): 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-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 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 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 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 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}", "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 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 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 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): 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 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 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 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;}", "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 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"); 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 + "/** @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 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 { // TODO(nicksantos): This should emit a warning. 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 (this:Foo, ...[number]): undefined\n" + "override: function (this:SubFoo, number): undefined"); */ } 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 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 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 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 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} } */" + "document.getElementById;" + "var list = /** @type {!Array.<string>} */ ['hello', 'you'];\n" + "list.push('?');\n" + "document.getElementById('node').innerHTML = list.toString();"); } 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 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;" + "}"); } /** * 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 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 { 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); 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 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 { // We currently do not support goog.bind natively. testClosureTypes( "var goog = {}; goog.bind = function(var_args) {};" + "/** @type {function(number): 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 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 {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 Object\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 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() {}" + "/** @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 { 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. May be 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()"); 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 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 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 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 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 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() {};"); 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()); } 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("number")); } 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()); } public void testBadTemplateType4() throws Exception { testTypes( "/**\n" + "* @template T\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } public void testBadTemplateType5() throws Exception { testTypes( "/**\n" + "* @template T\n" + "* @return {T}\n" + "*/\n" + "function f() {}\n" + "f();", FunctionTypeBuilder.TEMPLATE_TYPE_EXPECTED.format()); } 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 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 : Object\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; 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, null, 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( "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()); 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(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, 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 booleanAttributeOutput() { Document doc = Jsoup.parse("<img src=foo noshade='' nohref async=async autofocus=false>"); Element img = doc.selectFirst("img"); assertEquals("<img src=\"foo\" noshade nohref async autofocus=\"false\">", img.outerHtml()); }
org.jsoup.nodes.ElementTest::booleanAttributeOutput
src/test/java/org/jsoup/nodes/ElementTest.java
1,318
src/test/java/org/jsoup/nodes/ElementTest.java
booleanAttributeOutput
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 testWholeText() { Document doc = Jsoup.parse("<p> Hello\nthere &nbsp; </p>"); assertEquals(" Hello\nthere   ", doc.wholeText()); doc = Jsoup.parse("<p>Hello \n there</p>"); assertEquals("Hello \n there", doc.wholeText()); doc = Jsoup.parse("<p>Hello <div>\n there</div></p>"); assertEquals("Hello \n there", doc.wholeText()); } @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 testNormalizesInvisiblesInText() { // return Character.getType(c) == 16 && (c == 8203 || c == 8204 || c == 8205 || c == 173); String escaped = "This&shy;is&#x200b;one&#x200c;long&#x200d;word"; String decoded = "This\u00ADis\u200Bone\u200Clong\u200Dword"; // browser would not display those soft hyphens / other chars, so we don't want them in the text Document doc = Jsoup.parse("<p>" + escaped); Element p = doc.select("p").first(); doc.outputSettings().charset("ascii"); // so that the outer html is easier to see with escaped invisibles assertEquals("Thisisonelongword", p.text()); // text is normalized assertEquals("<p>" + escaped + "</p>", p.outerHtml()); // html / whole text keeps &shy etc; assertEquals(decoded, p.textNodes().get(0).getWholeText()); Element matched = doc.select("p:contains(Thisisonelongword)").first(); // really just oneloneword, no invisibles assertEquals("p", matched.nodeName()); assertTrue(matched.is(":containsOwn(Thisisonelongword)")); } @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=\"\"")); } @Test public void booleanAttributeOutput() { Document doc = Jsoup.parse("<img src=foo noshade='' nohref async=async autofocus=false>"); Element img = doc.selectFirst("img"); assertEquals("<img src=\"foo\" noshade nohref async autofocus=\"false\">", img.outerHtml()); } }
// You are a professional Java test case writer, please create a test case named `booleanAttributeOutput` for the issue `Jsoup-985`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-985 // // ## Issue-Title: // Regression - Boolean attributes not collapsed when using HTML syntax // // ## Issue-Description: // Hello, // // // First off, thanks for a really useful library. // // // So, upgrading from 1.10.2 to 1.11.2 we see that boolean attributes are no longer collapsed when using html syntax. Example test case: // // // // ``` // @Test // public void test() { // Document document = Jsoup.parse( // "<html><head></head><body><hr size=\"1\" noshade=\"\"></body></html>"); // assertEquals("<html>\n" + // " <head></head>\n" + // " <body>\n" + // " <hr size=\"1\" noshade>\n" + // " </body>\n" + // "</html>", // document.outerHtml()); // } // // ``` // // Tracked it down to commit "Refactored Attributes to be an array pair vs LinkedHashSet " [ea1fb65](https://github.com/jhy/jsoup/commit/ea1fb65e9ff8eee82c4e379dc3236d09a5ab02e1). The `Attibutes.html(final Appendable accum, final Document.OutputSettings out)` method no longer uses `Attribute` and **fails** to check the value of the attribute for an *empty string*(line 320). // // // If I may also suggest to use `Attribute.shouldCollapseAttribute(String key, String val, Document.OutputSettings out)` instead as a single source of truth as the boolean expression is complex enough and easy to make a mistake. Not sure if this would have an impact in performance though but I am guessing that optimizer will inline the call at some point anyways? // // // // @Test public void booleanAttributeOutput() {
1,318
75
1,312
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-985 ## Issue-Title: Regression - Boolean attributes not collapsed when using HTML syntax ## Issue-Description: Hello, First off, thanks for a really useful library. So, upgrading from 1.10.2 to 1.11.2 we see that boolean attributes are no longer collapsed when using html syntax. Example test case: ``` @Test public void test() { Document document = Jsoup.parse( "<html><head></head><body><hr size=\"1\" noshade=\"\"></body></html>"); assertEquals("<html>\n" + " <head></head>\n" + " <body>\n" + " <hr size=\"1\" noshade>\n" + " </body>\n" + "</html>", document.outerHtml()); } ``` Tracked it down to commit "Refactored Attributes to be an array pair vs LinkedHashSet " [ea1fb65](https://github.com/jhy/jsoup/commit/ea1fb65e9ff8eee82c4e379dc3236d09a5ab02e1). The `Attibutes.html(final Appendable accum, final Document.OutputSettings out)` method no longer uses `Attribute` and **fails** to check the value of the attribute for an *empty string*(line 320). If I may also suggest to use `Attribute.shouldCollapseAttribute(String key, String val, Document.OutputSettings out)` instead as a single source of truth as the boolean expression is complex enough and easy to make a mistake. Not sure if this would have an impact in performance though but I am guessing that optimizer will inline the call at some point anyways? ``` You are a professional Java test case writer, please create a test case named `booleanAttributeOutput` for the issue `Jsoup-985`, utilizing the provided issue report information and the following function signature. ```java @Test public void booleanAttributeOutput() { ```
1,312
[ "org.jsoup.nodes.Attributes" ]
c5a4296fb5f4cee7c90beb49b086ba7eaf2d542541fd9ae66e973edd8b204bd7
@Test public void booleanAttributeOutput()
// You are a professional Java test case writer, please create a test case named `booleanAttributeOutput` for the issue `Jsoup-985`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-985 // // ## Issue-Title: // Regression - Boolean attributes not collapsed when using HTML syntax // // ## Issue-Description: // Hello, // // // First off, thanks for a really useful library. // // // So, upgrading from 1.10.2 to 1.11.2 we see that boolean attributes are no longer collapsed when using html syntax. Example test case: // // // // ``` // @Test // public void test() { // Document document = Jsoup.parse( // "<html><head></head><body><hr size=\"1\" noshade=\"\"></body></html>"); // assertEquals("<html>\n" + // " <head></head>\n" + // " <body>\n" + // " <hr size=\"1\" noshade>\n" + // " </body>\n" + // "</html>", // document.outerHtml()); // } // // ``` // // Tracked it down to commit "Refactored Attributes to be an array pair vs LinkedHashSet " [ea1fb65](https://github.com/jhy/jsoup/commit/ea1fb65e9ff8eee82c4e379dc3236d09a5ab02e1). The `Attibutes.html(final Appendable accum, final Document.OutputSettings out)` method no longer uses `Attribute` and **fails** to check the value of the attribute for an *empty string*(line 320). // // // If I may also suggest to use `Attribute.shouldCollapseAttribute(String key, String val, Document.OutputSettings out)` instead as a single source of truth as the boolean expression is complex enough and easy to make a mistake. Not sure if this would have an impact in performance though but I am guessing that optimizer will inline the call at some point anyways? // // // //
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 testWholeText() { Document doc = Jsoup.parse("<p> Hello\nthere &nbsp; </p>"); assertEquals(" Hello\nthere   ", doc.wholeText()); doc = Jsoup.parse("<p>Hello \n there</p>"); assertEquals("Hello \n there", doc.wholeText()); doc = Jsoup.parse("<p>Hello <div>\n there</div></p>"); assertEquals("Hello \n there", doc.wholeText()); } @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 testNormalizesInvisiblesInText() { // return Character.getType(c) == 16 && (c == 8203 || c == 8204 || c == 8205 || c == 173); String escaped = "This&shy;is&#x200b;one&#x200c;long&#x200d;word"; String decoded = "This\u00ADis\u200Bone\u200Clong\u200Dword"; // browser would not display those soft hyphens / other chars, so we don't want them in the text Document doc = Jsoup.parse("<p>" + escaped); Element p = doc.select("p").first(); doc.outputSettings().charset("ascii"); // so that the outer html is easier to see with escaped invisibles assertEquals("Thisisonelongword", p.text()); // text is normalized assertEquals("<p>" + escaped + "</p>", p.outerHtml()); // html / whole text keeps &shy etc; assertEquals(decoded, p.textNodes().get(0).getWholeText()); Element matched = doc.select("p:contains(Thisisonelongword)").first(); // really just oneloneword, no invisibles assertEquals("p", matched.nodeName()); assertTrue(matched.is(":containsOwn(Thisisonelongword)")); } @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=\"\"")); } @Test public void booleanAttributeOutput() { Document doc = Jsoup.parse("<img src=foo noshade='' nohref async=async autofocus=false>"); Element img = doc.selectFirst("img"); assertEquals("<img src=\"foo\" noshade nohref async autofocus=\"false\">", img.outerHtml()); } }
public void testStripLeadingHyphens() { assertEquals("f", Util.stripLeadingHyphens("-f")); assertEquals("foo", Util.stripLeadingHyphens("--foo")); assertNull(Util.stripLeadingHyphens(null)); }
org.apache.commons.cli.UtilTest::testStripLeadingHyphens
src/test/org/apache/commons/cli/UtilTest.java
28
src/test/org/apache/commons/cli/UtilTest.java
testStripLeadingHyphens
/** * 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; /** * @author brianegge */ public class UtilTest extends TestCase { public void testStripLeadingHyphens() { assertEquals("f", Util.stripLeadingHyphens("-f")); assertEquals("foo", Util.stripLeadingHyphens("--foo")); assertNull(Util.stripLeadingHyphens(null)); } }
// You are a professional Java test case writer, please create a test case named `testStripLeadingHyphens` for the issue `Cli-CLI-133`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-133 // // ## Issue-Title: // NullPointerException in Util.stripLeadingHyphens when passed a null argument // // ## Issue-Description: // // If you try to do a hasOption(null), you get a NPE: // // // java.lang.NullPointerException // // at org.apache.commons.cli.Util.stripLeadingHyphens(Util.java:39) // // at org.apache.commons.cli.CommandLine.resolveOption(CommandLine.java:166) // // at org.apache.commons.cli.CommandLine.hasOption(CommandLine.java:68) // // // Either hasOption should reject the null argument, or the function should simply return false. I think the latter makes more since, as this is how Java collections generally work. // // // // // public void testStripLeadingHyphens() {
28
5
24
src/test/org/apache/commons/cli/UtilTest.java
src/test
```markdown ## Issue-ID: Cli-CLI-133 ## Issue-Title: NullPointerException in Util.stripLeadingHyphens when passed a null argument ## Issue-Description: If you try to do a hasOption(null), you get a NPE: java.lang.NullPointerException at org.apache.commons.cli.Util.stripLeadingHyphens(Util.java:39) at org.apache.commons.cli.CommandLine.resolveOption(CommandLine.java:166) at org.apache.commons.cli.CommandLine.hasOption(CommandLine.java:68) Either hasOption should reject the null argument, or the function should simply return false. I think the latter makes more since, as this is how Java collections generally work. ``` You are a professional Java test case writer, please create a test case named `testStripLeadingHyphens` for the issue `Cli-CLI-133`, utilizing the provided issue report information and the following function signature. ```java public void testStripLeadingHyphens() { ```
24
[ "org.apache.commons.cli.Util" ]
c628185c3bba25b047ad02452b4ad8e6a437ca429dbe508e4e728882fc6c2e78
public void testStripLeadingHyphens()
// You are a professional Java test case writer, please create a test case named `testStripLeadingHyphens` for the issue `Cli-CLI-133`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-133 // // ## Issue-Title: // NullPointerException in Util.stripLeadingHyphens when passed a null argument // // ## Issue-Description: // // If you try to do a hasOption(null), you get a NPE: // // // java.lang.NullPointerException // // at org.apache.commons.cli.Util.stripLeadingHyphens(Util.java:39) // // at org.apache.commons.cli.CommandLine.resolveOption(CommandLine.java:166) // // at org.apache.commons.cli.CommandLine.hasOption(CommandLine.java:68) // // // Either hasOption should reject the null argument, or the function should simply return false. I think the latter makes more since, as this is how Java collections generally work. // // // // //
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; /** * @author brianegge */ public class UtilTest extends TestCase { public void testStripLeadingHyphens() { assertEquals("f", Util.stripLeadingHyphens("-f")); assertEquals("foo", Util.stripLeadingHyphens("--foo")); assertNull(Util.stripLeadingHyphens(null)); } }
@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()); }
org.jsoup.parser.ParserTest::createsStructureFromBodySnippet
src/test/java/org/jsoup/parser/ParserTest.java
111
src/test/java/org/jsoup/parser/ParserTest.java
createsStructureFromBodySnippet
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Comment; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** Tests for the Parser @author Jonathan Hedley, [email protected] */ public class ParserTest { @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 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 parsesUnterminatedTag() { String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(1, doc.getElementsByTag("p").size()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); Element d = doc.getElementById("1"); assertEquals(1, d.children().size()); Element p = doc.getElementById("2"); assertNotNull(p); } @Test public void parsesUnterminatedAttribute() { String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); Element p = doc.getElementById("foo"); assertNotNull(p); assertEquals("p", p.tagName()); } @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>Nope</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("Nope", doc.data()); } @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 createsImplicitLists() { String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should have created a default ul. assertEquals(1, ol.size()); assertEquals(2, ol.get(0).children().size()); // 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 createsImplicitTable() { String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("<table><tr><td>Hello</td><td><p>There</p><p>now</p></td></tr></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { 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://bar", doc.baseUri()); // gets updated as base changes, so doc.createElement has latest. Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://bar", anchors.get(2).baseUri()); assertEquals("http://foo/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://bar/4", anchors.get(2).absUrl("href")); } @Test public void handlesCdata() { String h = "<div id=1><![CData[<html>\n<foo><&amp;]]></div>"; // "cdata" insensitive. 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.childNodes().size()); // no elements, one text node } @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 handlesEmptyBlocks() { String h = "<div id=1/><div id=2><img /></div>"; Document doc = Jsoup.parse(h); Element div1 = doc.getElementById("1"); assertTrue(div1.children().isEmpty()); } @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() { String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(4, doc.body().getElementsByTag("dl").first().children().size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @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><body></body></html>", TextUtil.stripNewlines(doc.html())); } @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() {} // Defects4J: flaky method // @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><link /></head><body>Five Six Seven One Two Four Three</body></html>", // TextUtil.stripNewlines(doc.html())); // is spaced OK if not newline & space stripped // } @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())); } }
// You are a professional Java test case writer, please create a test case named `createsStructureFromBodySnippet` for the issue `Jsoup-23`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-23 // // ## Issue-Title: // Parsing a HTML snippet causes the leading text to be moved to back // // ## Issue-Description: // Code: // // // // ``` // String html = "foo <b>bar</b> baz"; // String text = Jsoup.parse(html).text(); // System.out.println(text); // // ``` // // Result: // // // // ``` // bar baz foo // // ``` // // Expected: // // // // ``` // foo bar baz // // ``` // // // @Test public void createsStructureFromBodySnippet() {
111
1
104
src/test/java/org/jsoup/parser/ParserTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-23 ## Issue-Title: Parsing a HTML snippet causes the leading text to be moved to back ## Issue-Description: Code: ``` String html = "foo <b>bar</b> baz"; String text = Jsoup.parse(html).text(); System.out.println(text); ``` Result: ``` bar baz foo ``` Expected: ``` foo bar baz ``` ``` You are a professional Java test case writer, please create a test case named `createsStructureFromBodySnippet` for the issue `Jsoup-23`, utilizing the provided issue report information and the following function signature. ```java @Test public void createsStructureFromBodySnippet() { ```
104
[ "org.jsoup.nodes.Document" ]
c6c5b2bfaed87ec8c03c60f3eb2ca4defe4b0a4c97b71e3ab614100f7fe2ba69
@Test public void createsStructureFromBodySnippet()
// You are a professional Java test case writer, please create a test case named `createsStructureFromBodySnippet` for the issue `Jsoup-23`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-23 // // ## Issue-Title: // Parsing a HTML snippet causes the leading text to be moved to back // // ## Issue-Description: // Code: // // // // ``` // String html = "foo <b>bar</b> baz"; // String text = Jsoup.parse(html).text(); // System.out.println(text); // // ``` // // Result: // // // // ``` // bar baz foo // // ``` // // Expected: // // // // ``` // foo bar baz // // ``` // // //
Jsoup
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Comment; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** Tests for the Parser @author Jonathan Hedley, [email protected] */ public class ParserTest { @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 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 parsesUnterminatedTag() { String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(1, doc.getElementsByTag("p").size()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); Element d = doc.getElementById("1"); assertEquals(1, d.children().size()); Element p = doc.getElementById("2"); assertNotNull(p); } @Test public void parsesUnterminatedAttribute() { String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); Element p = doc.getElementById("foo"); assertNotNull(p); assertEquals("p", p.tagName()); } @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>Nope</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("Nope", doc.data()); } @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 createsImplicitLists() { String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should have created a default ul. assertEquals(1, ol.size()); assertEquals(2, ol.get(0).children().size()); // 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 createsImplicitTable() { String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("<table><tr><td>Hello</td><td><p>There</p><p>now</p></td></tr></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { 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://bar", doc.baseUri()); // gets updated as base changes, so doc.createElement has latest. Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://bar", anchors.get(2).baseUri()); assertEquals("http://foo/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://bar/4", anchors.get(2).absUrl("href")); } @Test public void handlesCdata() { String h = "<div id=1><![CData[<html>\n<foo><&amp;]]></div>"; // "cdata" insensitive. 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.childNodes().size()); // no elements, one text node } @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 handlesEmptyBlocks() { String h = "<div id=1/><div id=2><img /></div>"; Document doc = Jsoup.parse(h); Element div1 = doc.getElementById("1"); assertTrue(div1.children().isEmpty()); } @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() { String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(4, doc.body().getElementsByTag("dl").first().children().size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @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><body></body></html>", TextUtil.stripNewlines(doc.html())); } @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() {} // Defects4J: flaky method // @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><link /></head><body>Five Six Seven One Two Four Three</body></html>", // TextUtil.stripNewlines(doc.html())); // is spaced OK if not newline & space stripped // } @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())); } }
public void testNullColumn() throws Exception { assertEquals("[null,\"bar\"]", MAPPER.writeValueAsString(new TwoStringsBean())); }
com.fasterxml.jackson.databind.struct.TestPOJOAsArray::testNullColumn
src/test/java/com/fasterxml/jackson/databind/struct/TestPOJOAsArray.java
151
src/test/java/com/fasterxml/jackson/databind/struct/TestPOJOAsArray.java
testNullColumn
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonFormat.Shape; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; public class TestPOJOAsArray extends BaseMapTest { static class Pojo { @JsonFormat(shape=JsonFormat.Shape.ARRAY) public PojoValue value; public Pojo() { } public Pojo(String name, int x, int y, boolean c) { value = new PojoValue(name, x, y, c); } } // note: must be serialized/deserialized alphabetically; fields NOT declared in that order @JsonPropertyOrder(alphabetic=true) static class PojoValue { public int x, y; public String name; public boolean complete; public PojoValue() { } public PojoValue(String name, int x, int y, boolean c) { this.name = name; this.x = x; this.y = y; this.complete = c; } } @JsonPropertyOrder(alphabetic=true) @JsonFormat(shape=JsonFormat.Shape.ARRAY) static class FlatPojo { public int x, y; public String name; public boolean complete; public FlatPojo() { } public FlatPojo(String name, int x, int y, boolean c) { this.name = name; this.x = x; this.y = y; this.complete = c; } } static class ForceArraysIntrospector extends JacksonAnnotationIntrospector { private static final long serialVersionUID = 1L; @Override public JsonFormat.Value findFormat(Annotated a) { return new JsonFormat.Value().withShape(JsonFormat.Shape.ARRAY); } } static class A { public B value = new B(); } @JsonPropertyOrder(alphabetic=true) static class B { public int x = 1; public int y = 2; } // for [JACKSON-805] @JsonFormat(shape=Shape.ARRAY) static class SingleBean { public String name = "foo"; } @JsonPropertyOrder(alphabetic=true) @JsonFormat(shape=Shape.ARRAY) static class TwoStringsBean { public String bar = null; public String foo = "bar"; } /* /***************************************************** /* Basic tests /***************************************************** */ private final static ObjectMapper MAPPER = new ObjectMapper(); /** * Test that verifies that property annotation works */ public void testReadSimplePropertyValue() throws Exception { String json = "{\"value\":[true,\"Foobar\",42,13]}"; Pojo p = MAPPER.readValue(json, Pojo.class); assertNotNull(p.value); assertTrue(p.value.complete); assertEquals("Foobar", p.value.name); assertEquals(42, p.value.x); assertEquals(13, p.value.y); } /** * Test that verifies that Class annotation works */ public void testReadSimpleRootValue() throws Exception { String json = "[false,\"Bubba\",1,2]"; FlatPojo p = MAPPER.readValue(json, FlatPojo.class); assertFalse(p.complete); assertEquals("Bubba", p.name); assertEquals(1, p.x); assertEquals(2, p.y); } /** * Test that verifies that property annotation works */ public void testWriteSimplePropertyValue() throws Exception { String json = MAPPER.writeValueAsString(new Pojo("Foobar", 42, 13, true)); // will have wrapper POJO, then POJO-as-array.. assertEquals("{\"value\":[true,\"Foobar\",42,13]}", json); } /** * Test that verifies that Class annotation works */ public void testWriteSimpleRootValue() throws Exception { String json = MAPPER.writeValueAsString(new FlatPojo("Bubba", 1, 2, false)); // will have wrapper POJO, then POJO-as-array.. assertEquals("[false,\"Bubba\",1,2]", json); } // [Issue#223] public void testNullColumn() throws Exception { assertEquals("[null,\"bar\"]", MAPPER.writeValueAsString(new TwoStringsBean())); } /* /***************************************************** /* Compatibility with "single-elem as array" feature /***************************************************** */ // for [JACKSON-805] public void testSerializeAsArrayWithSingleProperty() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED); String json = mapper.writeValueAsString(new SingleBean()); assertEquals("\"foo\"", json); } /* /***************************************************** /* Round-trip tests /***************************************************** */ public void testAnnotationOverride() throws Exception { // by default, POJOs become JSON Objects; assertEquals("{\"value\":{\"x\":1,\"y\":2}}", MAPPER.writeValueAsString(new A())); // but override should change it: ObjectMapper mapper2 = new ObjectMapper(); mapper2.setAnnotationIntrospector(new ForceArraysIntrospector()); assertEquals("[[1,2]]", mapper2.writeValueAsString(new A())); } }
// You are a professional Java test case writer, please create a test case named `testNullColumn` for the issue `JacksonDatabind-223`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-223 // // ## Issue-Title: // NULL values are duplicated when serializing as array [via @JsonFormat(shape = JsonFormat.Shape.ARRAY)] // // ## Issue-Description: // Example: // // // // ``` // public class TestOuter { // // @JsonFormat(shape = JsonFormat.Shape.ARRAY) // public ArrayList<TestInner> array; // // public TestOuter() { // this.array = new ArrayList<TestInner>(); // this.array.add(new TestInner(1, "one")); // this.array.add(new TestInner(0, null)); // } // // private class TestInner { // public int i; // public String mayBeNull; // // public TestInner(int i, String s) { // this.i = i; // this.mayBeNull = s; // } // } // } // ``` // // Serializing an instance of TestOuter will produce the following incorrect result (as of Jackson 2.2.1): // // // // ``` // "array": [[1, "one"], [0, null, null]] // ``` // // where the null value is duplicated. The expected result would be: // // // // ``` // "array": [[1, "one"], [0, null]] // ``` // // I tracked the issue down to: // // // // ``` // package com.fasterxml.jackson.databind.ser; // // ... // public class BeanPropertyWriter { // // ... // public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov) // throws Exception // { // Object value = get(bean); // if (value == null) { // nulls need specialized handling // if (\_nullSerializer != null) { // \_nullSerializer.serialize(null, jgen, prov); // } else { // can NOT suppress entries in tabular output // jgen.writeNull(); // } // } // // otherwise find serializer to use // JsonSerializer<Object> ser = \_serializer; // // ... ... // ``` // // where I suspect there is a missing "return", to exit the function once handling of the null value in the dedicated branch is done. // // As it is now, a null value is first serialized in the dedicated branch (jgen.writeNull()), and then execution continues on the "normal" (non-null) path and eventually the value is serialized once again. // // // // public void testNullColumn() throws Exception {
151
// [Issue#223]
1
148
src/test/java/com/fasterxml/jackson/databind/struct/TestPOJOAsArray.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-223 ## Issue-Title: NULL values are duplicated when serializing as array [via @JsonFormat(shape = JsonFormat.Shape.ARRAY)] ## Issue-Description: Example: ``` public class TestOuter { @JsonFormat(shape = JsonFormat.Shape.ARRAY) public ArrayList<TestInner> array; public TestOuter() { this.array = new ArrayList<TestInner>(); this.array.add(new TestInner(1, "one")); this.array.add(new TestInner(0, null)); } private class TestInner { public int i; public String mayBeNull; public TestInner(int i, String s) { this.i = i; this.mayBeNull = s; } } } ``` Serializing an instance of TestOuter will produce the following incorrect result (as of Jackson 2.2.1): ``` "array": [[1, "one"], [0, null, null]] ``` where the null value is duplicated. The expected result would be: ``` "array": [[1, "one"], [0, null]] ``` I tracked the issue down to: ``` package com.fasterxml.jackson.databind.ser; // ... public class BeanPropertyWriter { // ... public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov) throws Exception { Object value = get(bean); if (value == null) { // nulls need specialized handling if (\_nullSerializer != null) { \_nullSerializer.serialize(null, jgen, prov); } else { // can NOT suppress entries in tabular output jgen.writeNull(); } } // otherwise find serializer to use JsonSerializer<Object> ser = \_serializer; // ... ... ``` where I suspect there is a missing "return", to exit the function once handling of the null value in the dedicated branch is done. As it is now, a null value is first serialized in the dedicated branch (jgen.writeNull()), and then execution continues on the "normal" (non-null) path and eventually the value is serialized once again. ``` You are a professional Java test case writer, please create a test case named `testNullColumn` for the issue `JacksonDatabind-223`, utilizing the provided issue report information and the following function signature. ```java public void testNullColumn() throws Exception { ```
148
[ "com.fasterxml.jackson.databind.ser.BeanPropertyWriter" ]
c728f79e60ad3c073c0e6ce0ffad02c99442a6e84e27c193206c8dbce2d6222a
public void testNullColumn() throws Exception
// You are a professional Java test case writer, please create a test case named `testNullColumn` for the issue `JacksonDatabind-223`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-223 // // ## Issue-Title: // NULL values are duplicated when serializing as array [via @JsonFormat(shape = JsonFormat.Shape.ARRAY)] // // ## Issue-Description: // Example: // // // // ``` // public class TestOuter { // // @JsonFormat(shape = JsonFormat.Shape.ARRAY) // public ArrayList<TestInner> array; // // public TestOuter() { // this.array = new ArrayList<TestInner>(); // this.array.add(new TestInner(1, "one")); // this.array.add(new TestInner(0, null)); // } // // private class TestInner { // public int i; // public String mayBeNull; // // public TestInner(int i, String s) { // this.i = i; // this.mayBeNull = s; // } // } // } // ``` // // Serializing an instance of TestOuter will produce the following incorrect result (as of Jackson 2.2.1): // // // // ``` // "array": [[1, "one"], [0, null, null]] // ``` // // where the null value is duplicated. The expected result would be: // // // // ``` // "array": [[1, "one"], [0, null]] // ``` // // I tracked the issue down to: // // // // ``` // package com.fasterxml.jackson.databind.ser; // // ... // public class BeanPropertyWriter { // // ... // public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov) // throws Exception // { // Object value = get(bean); // if (value == null) { // nulls need specialized handling // if (\_nullSerializer != null) { // \_nullSerializer.serialize(null, jgen, prov); // } else { // can NOT suppress entries in tabular output // jgen.writeNull(); // } // } // // otherwise find serializer to use // JsonSerializer<Object> ser = \_serializer; // // ... ... // ``` // // where I suspect there is a missing "return", to exit the function once handling of the null value in the dedicated branch is done. // // As it is now, a null value is first serialized in the dedicated branch (jgen.writeNull()), and then execution continues on the "normal" (non-null) path and eventually the value is serialized once again. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonFormat.Shape; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; public class TestPOJOAsArray extends BaseMapTest { static class Pojo { @JsonFormat(shape=JsonFormat.Shape.ARRAY) public PojoValue value; public Pojo() { } public Pojo(String name, int x, int y, boolean c) { value = new PojoValue(name, x, y, c); } } // note: must be serialized/deserialized alphabetically; fields NOT declared in that order @JsonPropertyOrder(alphabetic=true) static class PojoValue { public int x, y; public String name; public boolean complete; public PojoValue() { } public PojoValue(String name, int x, int y, boolean c) { this.name = name; this.x = x; this.y = y; this.complete = c; } } @JsonPropertyOrder(alphabetic=true) @JsonFormat(shape=JsonFormat.Shape.ARRAY) static class FlatPojo { public int x, y; public String name; public boolean complete; public FlatPojo() { } public FlatPojo(String name, int x, int y, boolean c) { this.name = name; this.x = x; this.y = y; this.complete = c; } } static class ForceArraysIntrospector extends JacksonAnnotationIntrospector { private static final long serialVersionUID = 1L; @Override public JsonFormat.Value findFormat(Annotated a) { return new JsonFormat.Value().withShape(JsonFormat.Shape.ARRAY); } } static class A { public B value = new B(); } @JsonPropertyOrder(alphabetic=true) static class B { public int x = 1; public int y = 2; } // for [JACKSON-805] @JsonFormat(shape=Shape.ARRAY) static class SingleBean { public String name = "foo"; } @JsonPropertyOrder(alphabetic=true) @JsonFormat(shape=Shape.ARRAY) static class TwoStringsBean { public String bar = null; public String foo = "bar"; } /* /***************************************************** /* Basic tests /***************************************************** */ private final static ObjectMapper MAPPER = new ObjectMapper(); /** * Test that verifies that property annotation works */ public void testReadSimplePropertyValue() throws Exception { String json = "{\"value\":[true,\"Foobar\",42,13]}"; Pojo p = MAPPER.readValue(json, Pojo.class); assertNotNull(p.value); assertTrue(p.value.complete); assertEquals("Foobar", p.value.name); assertEquals(42, p.value.x); assertEquals(13, p.value.y); } /** * Test that verifies that Class annotation works */ public void testReadSimpleRootValue() throws Exception { String json = "[false,\"Bubba\",1,2]"; FlatPojo p = MAPPER.readValue(json, FlatPojo.class); assertFalse(p.complete); assertEquals("Bubba", p.name); assertEquals(1, p.x); assertEquals(2, p.y); } /** * Test that verifies that property annotation works */ public void testWriteSimplePropertyValue() throws Exception { String json = MAPPER.writeValueAsString(new Pojo("Foobar", 42, 13, true)); // will have wrapper POJO, then POJO-as-array.. assertEquals("{\"value\":[true,\"Foobar\",42,13]}", json); } /** * Test that verifies that Class annotation works */ public void testWriteSimpleRootValue() throws Exception { String json = MAPPER.writeValueAsString(new FlatPojo("Bubba", 1, 2, false)); // will have wrapper POJO, then POJO-as-array.. assertEquals("[false,\"Bubba\",1,2]", json); } // [Issue#223] public void testNullColumn() throws Exception { assertEquals("[null,\"bar\"]", MAPPER.writeValueAsString(new TwoStringsBean())); } /* /***************************************************** /* Compatibility with "single-elem as array" feature /***************************************************** */ // for [JACKSON-805] public void testSerializeAsArrayWithSingleProperty() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED); String json = mapper.writeValueAsString(new SingleBean()); assertEquals("\"foo\"", json); } /* /***************************************************** /* Round-trip tests /***************************************************** */ public void testAnnotationOverride() throws Exception { // by default, POJOs become JSON Objects; assertEquals("{\"value\":{\"x\":1,\"y\":2}}", MAPPER.writeValueAsString(new A())); // but override should change it: ObjectMapper mapper2 = new ObjectMapper(); mapper2.setAnnotationIntrospector(new ForceArraysIntrospector()); assertEquals("[[1,2]]", mapper2.writeValueAsString(new A())); } }
public void testEquals() { final CharSequence fooCs = FOO, barCs = BAR, foobarCs = FOOBAR; assertTrue(StringUtils.equals(null, null)); assertTrue(StringUtils.equals(fooCs, fooCs)); assertTrue(StringUtils.equals(fooCs, (CharSequence) new StringBuilder(FOO))); assertTrue(StringUtils.equals(fooCs, (CharSequence) new String(new char[] { 'f', 'o', 'o' }))); assertTrue(StringUtils.equals(fooCs, (CharSequence) new CustomCharSequence(FOO))); assertTrue(StringUtils.equals((CharSequence) new CustomCharSequence(FOO), fooCs)); assertFalse(StringUtils.equals(fooCs, (CharSequence) new String(new char[] { 'f', 'O', 'O' }))); assertFalse(StringUtils.equals(fooCs, barCs)); assertFalse(StringUtils.equals(fooCs, null)); assertFalse(StringUtils.equals(null, fooCs)); assertFalse(StringUtils.equals(fooCs, foobarCs)); assertFalse(StringUtils.equals(foobarCs, fooCs)); }
org.apache.commons.lang3.StringUtilsEqualsIndexOfTest::testEquals
src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java
499
src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java
testEquals
/* * 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.util.Locale; import junit.framework.TestCase; import org.hamcrest.core.IsNot; import static org.junit.Assert.assertThat; /** * Unit tests {@link org.apache.commons.lang3.StringUtils} - Substring methods * * @version $Id$ */ public class StringUtilsEqualsIndexOfTest extends TestCase { private static final String BAR = "bar"; /** * Supplementary character U+20000 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharU20000 = "\uD840\uDC00"; /** * Supplementary character U+20001 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharU20001 = "\uD840\uDC01"; /** * Incomplete supplementary character U+20000, high surrogate only. * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharUSuppCharHigh = "\uDC00"; /** * Incomplete supplementary character U+20000, low surrogate only. * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharUSuppCharLow = "\uD840"; private static final String FOO = "foo"; private static final String FOOBAR = "foobar"; private static final String[] FOOBAR_SUB_ARRAY = new String[] {"ob", "ba"}; public StringUtilsEqualsIndexOfTest(String name) { super(name); } public void testContains_Char() { assertEquals(false, StringUtils.contains(null, ' ')); assertEquals(false, StringUtils.contains("", ' ')); assertEquals(false, StringUtils.contains("", null)); assertEquals(false, StringUtils.contains(null, null)); assertEquals(true, StringUtils.contains("abc", 'a')); assertEquals(true, StringUtils.contains("abc", 'b')); assertEquals(true, StringUtils.contains("abc", 'c')); assertEquals(false, StringUtils.contains("abc", 'z')); } public void testContains_String() { assertEquals(false, StringUtils.contains(null, null)); assertEquals(false, StringUtils.contains(null, "")); assertEquals(false, StringUtils.contains(null, "a")); assertEquals(false, StringUtils.contains("", null)); assertEquals(true, StringUtils.contains("", "")); assertEquals(false, StringUtils.contains("", "a")); assertEquals(true, StringUtils.contains("abc", "a")); assertEquals(true, StringUtils.contains("abc", "b")); assertEquals(true, StringUtils.contains("abc", "c")); assertEquals(true, StringUtils.contains("abc", "abc")); assertEquals(false, StringUtils.contains("abc", "z")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContains_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.contains(CharUSuppCharHigh, CharU20001)); assertEquals(false, StringUtils.contains(CharUSuppCharLow, CharU20001)); assertEquals(false, StringUtils.contains(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.contains(CharU20001, CharUSuppCharLow)); assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharLow + "a", "a")); assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharHigh + "a", "a")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContains_StringWithSupplementaryChars() { assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20000)); assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20001)); assertEquals(true, StringUtils.contains(CharU20000, CharU20000)); assertEquals(false, StringUtils.contains(CharU20000, CharU20001)); } public void testContainsAny_StringCharArray() { assertFalse(StringUtils.containsAny(null, (char[]) null)); assertFalse(StringUtils.containsAny(null, new char[0])); assertFalse(StringUtils.containsAny(null, new char[] { 'a', 'b' })); assertFalse(StringUtils.containsAny("", (char[]) null)); assertFalse(StringUtils.containsAny("", new char[0])); assertFalse(StringUtils.containsAny("", new char[] { 'a', 'b' })); assertFalse(StringUtils.containsAny("zzabyycdxx", (char[]) null)); assertFalse(StringUtils.containsAny("zzabyycdxx", new char[0])); assertTrue(StringUtils.containsAny("zzabyycdxx", new char[] { 'z', 'a' })); assertTrue(StringUtils.containsAny("zzabyycdxx", new char[] { 'b', 'y' })); assertFalse(StringUtils.containsAny("ab", new char[] { 'z' })); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringCharArrayWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny("abc" + CharUSuppCharHigh + "xyz", CharU20001.toCharArray())); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh.toCharArray())); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow.toCharArray())); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringCharArrayWithSupplementaryChars() { assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(true, StringUtils.containsAny("a" + CharU20000 + CharU20001, "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + "a" + CharU20001, "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001 + "a", "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000.toCharArray())); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000.toCharArray())); } public void testContainsAny_StringString() { assertFalse(StringUtils.containsAny(null, (String) null)); assertFalse(StringUtils.containsAny(null, "")); assertFalse(StringUtils.containsAny(null, "ab")); assertFalse(StringUtils.containsAny("", (String) null)); assertFalse(StringUtils.containsAny("", "")); assertFalse(StringUtils.containsAny("", "ab")); assertFalse(StringUtils.containsAny("zzabyycdxx", (String) null)); assertFalse(StringUtils.containsAny("zzabyycdxx", "")); assertTrue(StringUtils.containsAny("zzabyycdxx", "za")); assertTrue(StringUtils.containsAny("zzabyycdxx", "by")); assertFalse(StringUtils.containsAny("ab", "z")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001)); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001)); assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringWithSupplementaryChars() { assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000)); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001)); assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000)); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001)); assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000)); } public void testContainsIgnoreCase_LocaleIndependence() { Locale orig = Locale.getDefault(); Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() }; String[][] tdata = { { "i", "I" }, { "I", "i" }, { "\u03C2", "\u03C3" }, { "\u03A3", "\u03C2" }, { "\u03A3", "\u03C3" }, }; String[][] fdata = { { "\u00DF", "SS" }, }; try { for (Locale locale : locales) { Locale.setDefault(locale); for (int j = 0; j < tdata.length; j++) { assertTrue(Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1], StringUtils .containsIgnoreCase(tdata[j][0], tdata[j][1])); } for (int j = 0; j < fdata.length; j++) { assertFalse(Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1], StringUtils .containsIgnoreCase(fdata[j][0], fdata[j][1])); } } } finally { Locale.setDefault(orig); } } public void testContainsIgnoreCase_StringString() { assertFalse(StringUtils.containsIgnoreCase(null, null)); // Null tests assertFalse(StringUtils.containsIgnoreCase(null, "")); assertFalse(StringUtils.containsIgnoreCase(null, "a")); assertFalse(StringUtils.containsIgnoreCase(null, "abc")); assertFalse(StringUtils.containsIgnoreCase("", null)); assertFalse(StringUtils.containsIgnoreCase("a", null)); assertFalse(StringUtils.containsIgnoreCase("abc", null)); // Match len = 0 assertTrue(StringUtils.containsIgnoreCase("", "")); assertTrue(StringUtils.containsIgnoreCase("a", "")); assertTrue(StringUtils.containsIgnoreCase("abc", "")); // Match len = 1 assertFalse(StringUtils.containsIgnoreCase("", "a")); assertTrue(StringUtils.containsIgnoreCase("a", "a")); assertTrue(StringUtils.containsIgnoreCase("abc", "a")); assertFalse(StringUtils.containsIgnoreCase("", "A")); assertTrue(StringUtils.containsIgnoreCase("a", "A")); assertTrue(StringUtils.containsIgnoreCase("abc", "A")); // Match len > 1 assertFalse(StringUtils.containsIgnoreCase("", "abc")); assertFalse(StringUtils.containsIgnoreCase("a", "abc")); assertTrue(StringUtils.containsIgnoreCase("xabcz", "abc")); assertFalse(StringUtils.containsIgnoreCase("", "ABC")); assertFalse(StringUtils.containsIgnoreCase("a", "ABC")); assertTrue(StringUtils.containsIgnoreCase("xabcz", "ABC")); } public void testContainsNone_CharArray() { String str1 = "a"; String str2 = "b"; String str3 = "ab."; char[] chars1= {'b'}; char[] chars2= {'.'}; char[] chars3= {'c', 'd'}; char[] emptyChars = new char[0]; assertEquals(true, StringUtils.containsNone(null, (char[]) null)); assertEquals(true, StringUtils.containsNone("", (char[]) null)); assertEquals(true, StringUtils.containsNone(null, emptyChars)); assertEquals(true, StringUtils.containsNone(str1, emptyChars)); assertEquals(true, StringUtils.containsNone("", emptyChars)); assertEquals(true, StringUtils.containsNone("", chars1)); assertEquals(true, StringUtils.containsNone(str1, chars1)); assertEquals(true, StringUtils.containsNone(str1, chars2)); assertEquals(true, StringUtils.containsNone(str1, chars3)); assertEquals(false, StringUtils.containsNone(str2, chars1)); assertEquals(true, StringUtils.containsNone(str2, chars2)); assertEquals(true, StringUtils.containsNone(str2, chars3)); assertEquals(false, StringUtils.containsNone(str3, chars1)); assertEquals(false, StringUtils.containsNone(str3, chars2)); assertEquals(true, StringUtils.containsNone(str3, chars3)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_CharArrayWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001.toCharArray())); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001.toCharArray())); assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh)); assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh.toCharArray())); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow.toCharArray())); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_CharArrayWithSupplementaryChars() { assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000.toCharArray())); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001.toCharArray())); assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000.toCharArray())); } public void testContainsNone_String() { String str1 = "a"; String str2 = "b"; String str3 = "ab."; String chars1= "b"; String chars2= "."; String chars3= "cd"; assertEquals(true, StringUtils.containsNone(null, (String) null)); assertEquals(true, StringUtils.containsNone("", (String) null)); assertEquals(true, StringUtils.containsNone(null, "")); assertEquals(true, StringUtils.containsNone(str1, "")); assertEquals(true, StringUtils.containsNone("", "")); assertEquals(true, StringUtils.containsNone("", chars1)); assertEquals(true, StringUtils.containsNone(str1, chars1)); assertEquals(true, StringUtils.containsNone(str1, chars2)); assertEquals(true, StringUtils.containsNone(str1, chars3)); assertEquals(false, StringUtils.containsNone(str2, chars1)); assertEquals(true, StringUtils.containsNone(str2, chars2)); assertEquals(true, StringUtils.containsNone(str2, chars3)); assertEquals(false, StringUtils.containsNone(str3, chars1)); assertEquals(false, StringUtils.containsNone(str3, chars2)); assertEquals(true, StringUtils.containsNone(str3, chars3)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001)); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001)); assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh)); assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_StringWithSupplementaryChars() { assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000)); assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001)); assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000)); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001)); assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000)); } public void testContainsOnly_CharArray() { String str1 = "a"; String str2 = "b"; String str3 = "ab"; char[] chars1= {'b'}; char[] chars2= {'a'}; char[] chars3= {'a', 'b'}; char[] emptyChars = new char[0]; assertEquals(false, StringUtils.containsOnly(null, (char[]) null)); assertEquals(false, StringUtils.containsOnly("", (char[]) null)); assertEquals(false, StringUtils.containsOnly(null, emptyChars)); assertEquals(false, StringUtils.containsOnly(str1, emptyChars)); assertEquals(true, StringUtils.containsOnly("", emptyChars)); assertEquals(true, StringUtils.containsOnly("", chars1)); assertEquals(false, StringUtils.containsOnly(str1, chars1)); assertEquals(true, StringUtils.containsOnly(str1, chars2)); assertEquals(true, StringUtils.containsOnly(str1, chars3)); assertEquals(true, StringUtils.containsOnly(str2, chars1)); assertEquals(false, StringUtils.containsOnly(str2, chars2)); assertEquals(true, StringUtils.containsOnly(str2, chars3)); assertEquals(false, StringUtils.containsOnly(str3, chars1)); assertEquals(false, StringUtils.containsOnly(str3, chars2)); assertEquals(true, StringUtils.containsOnly(str3, chars3)); } public void testContainsOnly_String() { String str1 = "a"; String str2 = "b"; String str3 = "ab"; String chars1= "b"; String chars2= "a"; String chars3= "ab"; assertEquals(false, StringUtils.containsOnly(null, (String) null)); assertEquals(false, StringUtils.containsOnly("", (String) null)); assertEquals(false, StringUtils.containsOnly(null, "")); assertEquals(false, StringUtils.containsOnly(str1, "")); assertEquals(true, StringUtils.containsOnly("", "")); assertEquals(true, StringUtils.containsOnly("", chars1)); assertEquals(false, StringUtils.containsOnly(str1, chars1)); assertEquals(true, StringUtils.containsOnly(str1, chars2)); assertEquals(true, StringUtils.containsOnly(str1, chars3)); assertEquals(true, StringUtils.containsOnly(str2, chars1)); assertEquals(false, StringUtils.containsOnly(str2, chars2)); assertEquals(true, StringUtils.containsOnly(str2, chars3)); assertEquals(false, StringUtils.containsOnly(str3, chars1)); assertEquals(false, StringUtils.containsOnly(str3, chars2)); assertEquals(true, StringUtils.containsOnly(str3, chars3)); } public void testContainsWhitespace() { assertFalse( StringUtils.containsWhitespace("") ); assertTrue( StringUtils.containsWhitespace(" ") ); assertFalse( StringUtils.containsWhitespace("a") ); assertTrue( StringUtils.containsWhitespace("a ") ); assertTrue( StringUtils.containsWhitespace(" a") ); assertTrue( StringUtils.containsWhitespace("a\t") ); assertTrue( StringUtils.containsWhitespace("\n") ); } // The purpose of this class is to test StringUtils#equals(CharSequence, CharSequence) // with a CharSequence implementation whose equals(Object) override requires that the // other object be an instance of CustomCharSequence, even though, as char sequences, // `seq` may equal the other object. private static class CustomCharSequence implements CharSequence { private CharSequence seq; public CustomCharSequence(CharSequence seq) { this.seq = seq; } public char charAt(int index) { return seq.charAt(index); } public int length() { return seq.length(); } public CharSequence subSequence(int start, int end) { return new CustomCharSequence(seq.subSequence(start, end)); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof CustomCharSequence)) { return false; } CustomCharSequence other = (CustomCharSequence) obj; return seq.equals(other.seq); } public String toString() { return seq.toString(); } } public void testCustomCharSequence() { assertThat((CharSequence) new CustomCharSequence(FOO), IsNot.<CharSequence>not(FOO)); assertThat((CharSequence) FOO, IsNot.<CharSequence>not(new CustomCharSequence(FOO))); assertEquals(new CustomCharSequence(FOO), new CustomCharSequence(FOO)); } public void testEquals() { final CharSequence fooCs = FOO, barCs = BAR, foobarCs = FOOBAR; assertTrue(StringUtils.equals(null, null)); assertTrue(StringUtils.equals(fooCs, fooCs)); assertTrue(StringUtils.equals(fooCs, (CharSequence) new StringBuilder(FOO))); assertTrue(StringUtils.equals(fooCs, (CharSequence) new String(new char[] { 'f', 'o', 'o' }))); assertTrue(StringUtils.equals(fooCs, (CharSequence) new CustomCharSequence(FOO))); assertTrue(StringUtils.equals((CharSequence) new CustomCharSequence(FOO), fooCs)); assertFalse(StringUtils.equals(fooCs, (CharSequence) new String(new char[] { 'f', 'O', 'O' }))); assertFalse(StringUtils.equals(fooCs, barCs)); assertFalse(StringUtils.equals(fooCs, null)); assertFalse(StringUtils.equals(null, fooCs)); assertFalse(StringUtils.equals(fooCs, foobarCs)); assertFalse(StringUtils.equals(foobarCs, fooCs)); } public void testEqualsOnStrings() { assertTrue(StringUtils.equals(null, null)); assertTrue(StringUtils.equals(FOO, FOO)); assertTrue(StringUtils.equals(FOO, new String(new char[] { 'f', 'o', 'o' }))); assertFalse(StringUtils.equals(FOO, new String(new char[] { 'f', 'O', 'O' }))); assertFalse(StringUtils.equals(FOO, BAR)); assertFalse(StringUtils.equals(FOO, null)); assertFalse(StringUtils.equals(null, FOO)); assertFalse(StringUtils.equals(FOO, FOOBAR)); assertFalse(StringUtils.equals(FOOBAR, FOO)); } public void testEqualsIgnoreCase() { assertEquals(true, StringUtils.equalsIgnoreCase(null, null)); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, FOO)); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'o', 'o' }))); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'O', 'O' }))); assertEquals(false, StringUtils.equalsIgnoreCase(FOO, BAR)); assertEquals(false, StringUtils.equalsIgnoreCase(FOO, null)); assertEquals(false, StringUtils.equalsIgnoreCase(null, FOO)); } //----------------------------------------------------------------------- public void testIndexOf_char() { assertEquals(-1, StringUtils.indexOf(null, ' ')); assertEquals(-1, StringUtils.indexOf("", ' ')); assertEquals(0, StringUtils.indexOf("aabaabaa", 'a')); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b')); assertEquals(2, StringUtils.indexOf(new StringBuilder("aabaabaa"), 'b')); } public void testIndexOf_charInt() { assertEquals(-1, StringUtils.indexOf(null, ' ', 0)); assertEquals(-1, StringUtils.indexOf(null, ' ', -1)); assertEquals(-1, StringUtils.indexOf("", ' ', 0)); assertEquals(-1, StringUtils.indexOf("", ' ', -1)); assertEquals(0, StringUtils.indexOf("aabaabaa", 'a', 0)); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b', 0)); assertEquals(5, StringUtils.indexOf("aabaabaa", 'b', 3)); assertEquals(-1, StringUtils.indexOf("aabaabaa", 'b', 9)); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b', -1)); assertEquals(5, StringUtils.indexOf(new StringBuilder("aabaabaa"), 'b', 3)); } public void testIndexOf_String() { assertEquals(-1, StringUtils.indexOf(null, null)); assertEquals(-1, StringUtils.indexOf("", null)); assertEquals(0, StringUtils.indexOf("", "")); assertEquals(0, StringUtils.indexOf("aabaabaa", "a")); assertEquals(2, StringUtils.indexOf("aabaabaa", "b")); assertEquals(1, StringUtils.indexOf("aabaabaa", "ab")); assertEquals(0, StringUtils.indexOf("aabaabaa", "")); assertEquals(2, StringUtils.indexOf(new StringBuilder("aabaabaa"), "b")); } public void testIndexOf_StringInt() { assertEquals(-1, StringUtils.indexOf(null, null, 0)); assertEquals(-1, StringUtils.indexOf(null, null, -1)); assertEquals(-1, StringUtils.indexOf(null, "", 0)); assertEquals(-1, StringUtils.indexOf(null, "", -1)); assertEquals(-1, StringUtils.indexOf("", null, 0)); assertEquals(-1, StringUtils.indexOf("", null, -1)); assertEquals(0, StringUtils.indexOf("", "", 0)); assertEquals(0, StringUtils.indexOf("", "", -1)); assertEquals(0, StringUtils.indexOf("", "", 9)); assertEquals(0, StringUtils.indexOf("abc", "", 0)); assertEquals(0, StringUtils.indexOf("abc", "", -1)); assertEquals(3, StringUtils.indexOf("abc", "", 9)); assertEquals(3, StringUtils.indexOf("abc", "", 3)); assertEquals(0, StringUtils.indexOf("aabaabaa", "a", 0)); assertEquals(2, StringUtils.indexOf("aabaabaa", "b", 0)); assertEquals(1, StringUtils.indexOf("aabaabaa", "ab", 0)); assertEquals(5, StringUtils.indexOf("aabaabaa", "b", 3)); assertEquals(-1, StringUtils.indexOf("aabaabaa", "b", 9)); assertEquals(2, StringUtils.indexOf("aabaabaa", "b", -1)); assertEquals(2,StringUtils.indexOf("aabaabaa", "", 2)); assertEquals(5, StringUtils.indexOf(new StringBuilder("aabaabaa"), "b", 3)); } public void testIndexOfAny_StringCharArray() { assertEquals(-1, StringUtils.indexOfAny(null, (char[]) null)); assertEquals(-1, StringUtils.indexOfAny(null, new char[0])); assertEquals(-1, StringUtils.indexOfAny(null, new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAny("", (char[]) null)); assertEquals(-1, StringUtils.indexOfAny("", new char[0])); assertEquals(-1, StringUtils.indexOfAny("", new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", (char[]) null)); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", new char[0])); assertEquals(0, StringUtils.indexOfAny("zzabyycdxx", new char[] {'z','a'})); assertEquals(3, StringUtils.indexOfAny("zzabyycdxx", new char[] {'b','y'})); assertEquals(-1, StringUtils.indexOfAny("ab", new char[] {'z'})); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testIndexOfAny_StringCharArrayWithSupplementaryChars() { assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(0, StringUtils.indexOfAny(CharU20000, CharU20000.toCharArray())); assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001.toCharArray())); } public void testIndexOfAny_StringString() { assertEquals(-1, StringUtils.indexOfAny(null, (String) null)); assertEquals(-1, StringUtils.indexOfAny(null, "")); assertEquals(-1, StringUtils.indexOfAny(null, "ab")); assertEquals(-1, StringUtils.indexOfAny("", (String) null)); assertEquals(-1, StringUtils.indexOfAny("", "")); assertEquals(-1, StringUtils.indexOfAny("", "ab")); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", (String) null)); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", "")); assertEquals(0, StringUtils.indexOfAny("zzabyycdxx", "za")); assertEquals(3, StringUtils.indexOfAny("zzabyycdxx", "by")); assertEquals(-1, StringUtils.indexOfAny("ab", "z")); } public void testIndexOfAny_StringStringArray() { assertEquals(-1, StringUtils.indexOfAny(null, (String[]) null)); assertEquals(-1, StringUtils.indexOfAny(null, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, (String[]) null)); assertEquals(2, StringUtils.indexOfAny(FOOBAR, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[0])); assertEquals(-1, StringUtils.indexOfAny(null, new String[0])); assertEquals(-1, StringUtils.indexOfAny("", new String[0])); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[] {"llll"})); assertEquals(0, StringUtils.indexOfAny(FOOBAR, new String[] {""})); assertEquals(0, StringUtils.indexOfAny("", new String[] {""})); assertEquals(-1, StringUtils.indexOfAny("", new String[] {"a"})); assertEquals(-1, StringUtils.indexOfAny("", new String[] {null})); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[] {null})); assertEquals(-1, StringUtils.indexOfAny(null, new String[] {null})); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testIndexOfAny_StringStringWithSupplementaryChars() { assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000)); assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001)); assertEquals(0, StringUtils.indexOfAny(CharU20000, CharU20000)); assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001)); } public void testIndexOfAnyBut_StringCharArray() { assertEquals(-1, StringUtils.indexOfAnyBut(null, (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut(null, new char[0])); assertEquals(-1, StringUtils.indexOfAnyBut(null, new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAnyBut("", (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut("", new char[0])); assertEquals(-1, StringUtils.indexOfAnyBut("", new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", new char[0])); assertEquals(3, StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z','a'})); assertEquals(0, StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'b','y'})); assertEquals(-1, StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'})); assertEquals(0, StringUtils.indexOfAnyBut("aba", new char[] {'z'})); } public void testIndexOfAnyBut_StringCharArrayWithSupplementaryChars() { assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(-1, StringUtils.indexOfAnyBut(CharU20000, CharU20000.toCharArray())); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001.toCharArray())); } public void testIndexOfAnyBut_StringString() { assertEquals(-1, StringUtils.indexOfAnyBut(null, (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut(null, "")); assertEquals(-1, StringUtils.indexOfAnyBut(null, "ab")); assertEquals(-1, StringUtils.indexOfAnyBut("", (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut("", "")); assertEquals(-1, StringUtils.indexOfAnyBut("", "ab")); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", "")); assertEquals(3, StringUtils.indexOfAnyBut("zzabyycdxx", "za")); assertEquals(0, StringUtils.indexOfAnyBut("zzabyycdxx", "by")); assertEquals(0, StringUtils.indexOfAnyBut("ab", "z")); } public void testIndexOfAnyBut_StringStringWithSupplementaryChars() { assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000)); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001)); assertEquals(-1, StringUtils.indexOfAnyBut(CharU20000, CharU20000)); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001)); } public void testIndexOfIgnoreCase_String() { assertEquals(-1, StringUtils.indexOfIgnoreCase(null, null)); assertEquals(-1, StringUtils.indexOfIgnoreCase(null, "")); assertEquals(-1, StringUtils.indexOfIgnoreCase("", null)); assertEquals(0, StringUtils.indexOfIgnoreCase("", "")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "a")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "A")); assertEquals(2, StringUtils.indexOfIgnoreCase("aabaabaa", "b")); assertEquals(2, StringUtils.indexOfIgnoreCase("aabaabaa", "B")); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "ab")); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "")); } public void testIndexOfIgnoreCase_StringInt() { assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", -1)); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0)); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 1)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 2)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 3)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 4)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 5)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 6)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 7)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 8)); assertEquals(1, StringUtils.indexOfIgnoreCase("aab", "AB", 1)); assertEquals(5, StringUtils.indexOfIgnoreCase("aabaabaa", "", 5)); assertEquals(-1, StringUtils.indexOfIgnoreCase("ab", "AAB", 0)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aab", "AAB", 1)); } public void testLastIndexOf_char() { assertEquals(-1, StringUtils.lastIndexOf(null, ' ')); assertEquals(-1, StringUtils.lastIndexOf("", ' ')); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", 'a')); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b')); assertEquals(5, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), 'b')); } public void testLastIndexOf_charInt() { assertEquals(-1, StringUtils.lastIndexOf(null, ' ', 0)); assertEquals(-1, StringUtils.lastIndexOf(null, ' ', -1)); assertEquals(-1, StringUtils.lastIndexOf("", ' ', 0)); assertEquals(-1, StringUtils.lastIndexOf("", ' ', -1)); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", 'a', 8)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b', 8)); assertEquals(2, StringUtils.lastIndexOf("aabaabaa", 'b', 3)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b', 9)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", 'b', -1)); assertEquals(0, StringUtils.lastIndexOf("aabaabaa", 'a', 0)); assertEquals(2, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), 'b', 2)); } public void testLastIndexOf_String() { assertEquals(-1, StringUtils.lastIndexOf(null, null)); assertEquals(-1, StringUtils.lastIndexOf("", null)); assertEquals(-1, StringUtils.lastIndexOf("", "a")); assertEquals(0, StringUtils.lastIndexOf("", "")); assertEquals(8, StringUtils.lastIndexOf("aabaabaa", "")); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", "a")); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b")); assertEquals(4, StringUtils.lastIndexOf("aabaabaa", "ab")); assertEquals(4, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), "ab")); } public void testLastIndexOf_StringInt() { assertEquals(-1, StringUtils.lastIndexOf(null, null, 0)); assertEquals(-1, StringUtils.lastIndexOf(null, null, -1)); assertEquals(-1, StringUtils.lastIndexOf(null, "", 0)); assertEquals(-1, StringUtils.lastIndexOf(null, "", -1)); assertEquals(-1, StringUtils.lastIndexOf("", null, 0)); assertEquals(-1, StringUtils.lastIndexOf("", null, -1)); assertEquals(0, StringUtils.lastIndexOf("", "", 0)); assertEquals(-1, StringUtils.lastIndexOf("", "", -1)); assertEquals(0, StringUtils.lastIndexOf("", "", 9)); assertEquals(0, StringUtils.lastIndexOf("abc", "", 0)); assertEquals(-1, StringUtils.lastIndexOf("abc", "", -1)); assertEquals(3, StringUtils.lastIndexOf("abc", "", 9)); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", "a", 8)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b", 8)); assertEquals(4, StringUtils.lastIndexOf("aabaabaa", "ab", 8)); assertEquals(2, StringUtils.lastIndexOf("aabaabaa", "b", 3)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b", 9)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", -1)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", 0)); assertEquals(0, StringUtils.lastIndexOf("aabaabaa", "a", 0)); assertEquals(2, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), "b", 3)); } public void testLastIndexOfAny_StringStringArray() { assertEquals(-1, StringUtils.lastIndexOfAny(null, (CharSequence) null)); // test both types of ... assertEquals(-1, StringUtils.lastIndexOfAny(null, (CharSequence[]) null)); // ... varargs invocation assertEquals(-1, StringUtils.lastIndexOfAny(null)); // Missing varag assertEquals(-1, StringUtils.lastIndexOfAny(null, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, (CharSequence) null)); // test both types of ... assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, (CharSequence[]) null)); // ... varargs invocation assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR)); // Missing vararg assertEquals(3, StringUtils.lastIndexOfAny(FOOBAR, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny(null, new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[] {"llll"})); assertEquals(6, StringUtils.lastIndexOfAny(FOOBAR, new String[] {""})); assertEquals(0, StringUtils.lastIndexOfAny("", new String[] {""})); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[] {"a"})); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[] {null})); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[] {null})); assertEquals(-1, StringUtils.lastIndexOfAny(null, new String[] {null})); } public void testLastIndexOfIgnoreCase_String() { assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "")); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", "a")); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "")); assertEquals(8, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "")); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "a")); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A")); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "b")); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B")); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "ab")); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB")); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("ab", "AAB")); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("aab", "AAB")); } public void testLastIndexOfIgnoreCase_StringInt() { assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "", -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null, 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null, -1)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", "", -1)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "", 9)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("abc", "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("abc", "", -1)); assertEquals(3, StringUtils.lastIndexOfIgnoreCase("abc", "", 9)); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8)); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8)); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8)); assertEquals(2, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 3)); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0)); assertEquals(1, StringUtils.lastIndexOfIgnoreCase("aab", "AB", 1)); } public void testLastOrdinalIndexOf() { assertEquals(-1, StringUtils.lastOrdinalIndexOf(null, "*", 42) ); assertEquals(-1, StringUtils.lastOrdinalIndexOf("*", null, 42) ); assertEquals(0, StringUtils.lastOrdinalIndexOf("", "", 42) ); assertEquals(7, StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) ); assertEquals(6, StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) ); assertEquals(5, StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) ); assertEquals(2, StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) ); assertEquals(4, StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) ); assertEquals(1, StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) ); assertEquals(8, StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) ); assertEquals(8, StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) ); } public void testOrdinalIndexOf() { assertEquals(-1, StringUtils.ordinalIndexOf(null, null, Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, -1)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, -1)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", -1)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 0)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 0)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", 0)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 1)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 1)); assertEquals(0, StringUtils.ordinalIndexOf("", "", 1)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "a", 1)); assertEquals(2, StringUtils.ordinalIndexOf("aabaabaa", "b", 1)); assertEquals(1, StringUtils.ordinalIndexOf("aabaabaa", "ab", 1)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", 1)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 2)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 2)); assertEquals(0, StringUtils.ordinalIndexOf("", "", 2)); assertEquals(1, StringUtils.ordinalIndexOf("aabaabaa", "a", 2)); assertEquals(5, StringUtils.ordinalIndexOf("aabaabaa", "b", 2)); assertEquals(4, StringUtils.ordinalIndexOf("aabaabaa", "ab", 2)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", 2)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, Integer.MAX_VALUE)); assertEquals(0, StringUtils.ordinalIndexOf("", "", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", Integer.MAX_VALUE)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 0)); assertEquals(0, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 1)); assertEquals(1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 2)); assertEquals(2, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 3)); assertEquals(3, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 4)); assertEquals(4, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 5)); assertEquals(5, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 6)); assertEquals(6, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 7)); assertEquals(7, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 8)); assertEquals(8, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 9)); assertEquals(-1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 10)); } }
// You are a professional Java test case writer, please create a test case named `testEquals` for the issue `Lang-LANG-786`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-786 // // ## Issue-Title: // StringUtils equals() relies on undefined behavior // // ## Issue-Description: // // Since the java.lang.CharSequence class was first introduced in 1.4, the JavaDoc block has contained the following note: // // // // > // > This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. // > // > // // // When the signature of the StringUtils equals() method was changed from equals(String, String) to equals(CharSequence, CharSequence) in R920543, the implementation still relied on calling CharSequence#equals(Object) even though, in general, the result is undefined. // // // One example where equals(Object) returns false even though, as CharSequences, two objects represent equal sequences is when one object is an instance of javax.lang.model.element.Name and the other object is a String. // // // // // public void testEquals() {
499
14
485
src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-786 ## Issue-Title: StringUtils equals() relies on undefined behavior ## Issue-Description: Since the java.lang.CharSequence class was first introduced in 1.4, the JavaDoc block has contained the following note: > > This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. > > When the signature of the StringUtils equals() method was changed from equals(String, String) to equals(CharSequence, CharSequence) in R920543, the implementation still relied on calling CharSequence#equals(Object) even though, in general, the result is undefined. One example where equals(Object) returns false even though, as CharSequences, two objects represent equal sequences is when one object is an instance of javax.lang.model.element.Name and the other object is a String. ``` You are a professional Java test case writer, please create a test case named `testEquals` for the issue `Lang-LANG-786`, utilizing the provided issue report information and the following function signature. ```java public void testEquals() { ```
485
[ "org.apache.commons.lang3.StringUtils" ]
c95b66f01336543c46e7d369c0f6bb05a0847a34aa47953da18676abe7bec7e8
public void testEquals()
// You are a professional Java test case writer, please create a test case named `testEquals` for the issue `Lang-LANG-786`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-786 // // ## Issue-Title: // StringUtils equals() relies on undefined behavior // // ## Issue-Description: // // Since the java.lang.CharSequence class was first introduced in 1.4, the JavaDoc block has contained the following note: // // // // > // > This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. // > // > // // // When the signature of the StringUtils equals() method was changed from equals(String, String) to equals(CharSequence, CharSequence) in R920543, the implementation still relied on calling CharSequence#equals(Object) even though, in general, the result is undefined. // // // One example where equals(Object) returns false even though, as CharSequences, two objects represent equal sequences is when one object is an instance of javax.lang.model.element.Name and the other object is a String. // // // // //
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.util.Locale; import junit.framework.TestCase; import org.hamcrest.core.IsNot; import static org.junit.Assert.assertThat; /** * Unit tests {@link org.apache.commons.lang3.StringUtils} - Substring methods * * @version $Id$ */ public class StringUtilsEqualsIndexOfTest extends TestCase { private static final String BAR = "bar"; /** * Supplementary character U+20000 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharU20000 = "\uD840\uDC00"; /** * Supplementary character U+20001 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharU20001 = "\uD840\uDC01"; /** * Incomplete supplementary character U+20000, high surrogate only. * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharUSuppCharHigh = "\uDC00"; /** * Incomplete supplementary character U+20000, low surrogate only. * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharUSuppCharLow = "\uD840"; private static final String FOO = "foo"; private static final String FOOBAR = "foobar"; private static final String[] FOOBAR_SUB_ARRAY = new String[] {"ob", "ba"}; public StringUtilsEqualsIndexOfTest(String name) { super(name); } public void testContains_Char() { assertEquals(false, StringUtils.contains(null, ' ')); assertEquals(false, StringUtils.contains("", ' ')); assertEquals(false, StringUtils.contains("", null)); assertEquals(false, StringUtils.contains(null, null)); assertEquals(true, StringUtils.contains("abc", 'a')); assertEquals(true, StringUtils.contains("abc", 'b')); assertEquals(true, StringUtils.contains("abc", 'c')); assertEquals(false, StringUtils.contains("abc", 'z')); } public void testContains_String() { assertEquals(false, StringUtils.contains(null, null)); assertEquals(false, StringUtils.contains(null, "")); assertEquals(false, StringUtils.contains(null, "a")); assertEquals(false, StringUtils.contains("", null)); assertEquals(true, StringUtils.contains("", "")); assertEquals(false, StringUtils.contains("", "a")); assertEquals(true, StringUtils.contains("abc", "a")); assertEquals(true, StringUtils.contains("abc", "b")); assertEquals(true, StringUtils.contains("abc", "c")); assertEquals(true, StringUtils.contains("abc", "abc")); assertEquals(false, StringUtils.contains("abc", "z")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContains_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.contains(CharUSuppCharHigh, CharU20001)); assertEquals(false, StringUtils.contains(CharUSuppCharLow, CharU20001)); assertEquals(false, StringUtils.contains(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.contains(CharU20001, CharUSuppCharLow)); assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharLow + "a", "a")); assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharHigh + "a", "a")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContains_StringWithSupplementaryChars() { assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20000)); assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20001)); assertEquals(true, StringUtils.contains(CharU20000, CharU20000)); assertEquals(false, StringUtils.contains(CharU20000, CharU20001)); } public void testContainsAny_StringCharArray() { assertFalse(StringUtils.containsAny(null, (char[]) null)); assertFalse(StringUtils.containsAny(null, new char[0])); assertFalse(StringUtils.containsAny(null, new char[] { 'a', 'b' })); assertFalse(StringUtils.containsAny("", (char[]) null)); assertFalse(StringUtils.containsAny("", new char[0])); assertFalse(StringUtils.containsAny("", new char[] { 'a', 'b' })); assertFalse(StringUtils.containsAny("zzabyycdxx", (char[]) null)); assertFalse(StringUtils.containsAny("zzabyycdxx", new char[0])); assertTrue(StringUtils.containsAny("zzabyycdxx", new char[] { 'z', 'a' })); assertTrue(StringUtils.containsAny("zzabyycdxx", new char[] { 'b', 'y' })); assertFalse(StringUtils.containsAny("ab", new char[] { 'z' })); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringCharArrayWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny("abc" + CharUSuppCharHigh + "xyz", CharU20001.toCharArray())); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh.toCharArray())); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow.toCharArray())); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringCharArrayWithSupplementaryChars() { assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(true, StringUtils.containsAny("a" + CharU20000 + CharU20001, "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + "a" + CharU20001, "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001 + "a", "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000.toCharArray())); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000.toCharArray())); } public void testContainsAny_StringString() { assertFalse(StringUtils.containsAny(null, (String) null)); assertFalse(StringUtils.containsAny(null, "")); assertFalse(StringUtils.containsAny(null, "ab")); assertFalse(StringUtils.containsAny("", (String) null)); assertFalse(StringUtils.containsAny("", "")); assertFalse(StringUtils.containsAny("", "ab")); assertFalse(StringUtils.containsAny("zzabyycdxx", (String) null)); assertFalse(StringUtils.containsAny("zzabyycdxx", "")); assertTrue(StringUtils.containsAny("zzabyycdxx", "za")); assertTrue(StringUtils.containsAny("zzabyycdxx", "by")); assertFalse(StringUtils.containsAny("ab", "z")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001)); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001)); assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringWithSupplementaryChars() { assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000)); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001)); assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000)); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001)); assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000)); } public void testContainsIgnoreCase_LocaleIndependence() { Locale orig = Locale.getDefault(); Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() }; String[][] tdata = { { "i", "I" }, { "I", "i" }, { "\u03C2", "\u03C3" }, { "\u03A3", "\u03C2" }, { "\u03A3", "\u03C3" }, }; String[][] fdata = { { "\u00DF", "SS" }, }; try { for (Locale locale : locales) { Locale.setDefault(locale); for (int j = 0; j < tdata.length; j++) { assertTrue(Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1], StringUtils .containsIgnoreCase(tdata[j][0], tdata[j][1])); } for (int j = 0; j < fdata.length; j++) { assertFalse(Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1], StringUtils .containsIgnoreCase(fdata[j][0], fdata[j][1])); } } } finally { Locale.setDefault(orig); } } public void testContainsIgnoreCase_StringString() { assertFalse(StringUtils.containsIgnoreCase(null, null)); // Null tests assertFalse(StringUtils.containsIgnoreCase(null, "")); assertFalse(StringUtils.containsIgnoreCase(null, "a")); assertFalse(StringUtils.containsIgnoreCase(null, "abc")); assertFalse(StringUtils.containsIgnoreCase("", null)); assertFalse(StringUtils.containsIgnoreCase("a", null)); assertFalse(StringUtils.containsIgnoreCase("abc", null)); // Match len = 0 assertTrue(StringUtils.containsIgnoreCase("", "")); assertTrue(StringUtils.containsIgnoreCase("a", "")); assertTrue(StringUtils.containsIgnoreCase("abc", "")); // Match len = 1 assertFalse(StringUtils.containsIgnoreCase("", "a")); assertTrue(StringUtils.containsIgnoreCase("a", "a")); assertTrue(StringUtils.containsIgnoreCase("abc", "a")); assertFalse(StringUtils.containsIgnoreCase("", "A")); assertTrue(StringUtils.containsIgnoreCase("a", "A")); assertTrue(StringUtils.containsIgnoreCase("abc", "A")); // Match len > 1 assertFalse(StringUtils.containsIgnoreCase("", "abc")); assertFalse(StringUtils.containsIgnoreCase("a", "abc")); assertTrue(StringUtils.containsIgnoreCase("xabcz", "abc")); assertFalse(StringUtils.containsIgnoreCase("", "ABC")); assertFalse(StringUtils.containsIgnoreCase("a", "ABC")); assertTrue(StringUtils.containsIgnoreCase("xabcz", "ABC")); } public void testContainsNone_CharArray() { String str1 = "a"; String str2 = "b"; String str3 = "ab."; char[] chars1= {'b'}; char[] chars2= {'.'}; char[] chars3= {'c', 'd'}; char[] emptyChars = new char[0]; assertEquals(true, StringUtils.containsNone(null, (char[]) null)); assertEquals(true, StringUtils.containsNone("", (char[]) null)); assertEquals(true, StringUtils.containsNone(null, emptyChars)); assertEquals(true, StringUtils.containsNone(str1, emptyChars)); assertEquals(true, StringUtils.containsNone("", emptyChars)); assertEquals(true, StringUtils.containsNone("", chars1)); assertEquals(true, StringUtils.containsNone(str1, chars1)); assertEquals(true, StringUtils.containsNone(str1, chars2)); assertEquals(true, StringUtils.containsNone(str1, chars3)); assertEquals(false, StringUtils.containsNone(str2, chars1)); assertEquals(true, StringUtils.containsNone(str2, chars2)); assertEquals(true, StringUtils.containsNone(str2, chars3)); assertEquals(false, StringUtils.containsNone(str3, chars1)); assertEquals(false, StringUtils.containsNone(str3, chars2)); assertEquals(true, StringUtils.containsNone(str3, chars3)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_CharArrayWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001.toCharArray())); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001.toCharArray())); assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh)); assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh.toCharArray())); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow.toCharArray())); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_CharArrayWithSupplementaryChars() { assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000.toCharArray())); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001.toCharArray())); assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000.toCharArray())); } public void testContainsNone_String() { String str1 = "a"; String str2 = "b"; String str3 = "ab."; String chars1= "b"; String chars2= "."; String chars3= "cd"; assertEquals(true, StringUtils.containsNone(null, (String) null)); assertEquals(true, StringUtils.containsNone("", (String) null)); assertEquals(true, StringUtils.containsNone(null, "")); assertEquals(true, StringUtils.containsNone(str1, "")); assertEquals(true, StringUtils.containsNone("", "")); assertEquals(true, StringUtils.containsNone("", chars1)); assertEquals(true, StringUtils.containsNone(str1, chars1)); assertEquals(true, StringUtils.containsNone(str1, chars2)); assertEquals(true, StringUtils.containsNone(str1, chars3)); assertEquals(false, StringUtils.containsNone(str2, chars1)); assertEquals(true, StringUtils.containsNone(str2, chars2)); assertEquals(true, StringUtils.containsNone(str2, chars3)); assertEquals(false, StringUtils.containsNone(str3, chars1)); assertEquals(false, StringUtils.containsNone(str3, chars2)); assertEquals(true, StringUtils.containsNone(str3, chars3)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001)); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001)); assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh)); assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_StringWithSupplementaryChars() { assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000)); assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001)); assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000)); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001)); assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000)); } public void testContainsOnly_CharArray() { String str1 = "a"; String str2 = "b"; String str3 = "ab"; char[] chars1= {'b'}; char[] chars2= {'a'}; char[] chars3= {'a', 'b'}; char[] emptyChars = new char[0]; assertEquals(false, StringUtils.containsOnly(null, (char[]) null)); assertEquals(false, StringUtils.containsOnly("", (char[]) null)); assertEquals(false, StringUtils.containsOnly(null, emptyChars)); assertEquals(false, StringUtils.containsOnly(str1, emptyChars)); assertEquals(true, StringUtils.containsOnly("", emptyChars)); assertEquals(true, StringUtils.containsOnly("", chars1)); assertEquals(false, StringUtils.containsOnly(str1, chars1)); assertEquals(true, StringUtils.containsOnly(str1, chars2)); assertEquals(true, StringUtils.containsOnly(str1, chars3)); assertEquals(true, StringUtils.containsOnly(str2, chars1)); assertEquals(false, StringUtils.containsOnly(str2, chars2)); assertEquals(true, StringUtils.containsOnly(str2, chars3)); assertEquals(false, StringUtils.containsOnly(str3, chars1)); assertEquals(false, StringUtils.containsOnly(str3, chars2)); assertEquals(true, StringUtils.containsOnly(str3, chars3)); } public void testContainsOnly_String() { String str1 = "a"; String str2 = "b"; String str3 = "ab"; String chars1= "b"; String chars2= "a"; String chars3= "ab"; assertEquals(false, StringUtils.containsOnly(null, (String) null)); assertEquals(false, StringUtils.containsOnly("", (String) null)); assertEquals(false, StringUtils.containsOnly(null, "")); assertEquals(false, StringUtils.containsOnly(str1, "")); assertEquals(true, StringUtils.containsOnly("", "")); assertEquals(true, StringUtils.containsOnly("", chars1)); assertEquals(false, StringUtils.containsOnly(str1, chars1)); assertEquals(true, StringUtils.containsOnly(str1, chars2)); assertEquals(true, StringUtils.containsOnly(str1, chars3)); assertEquals(true, StringUtils.containsOnly(str2, chars1)); assertEquals(false, StringUtils.containsOnly(str2, chars2)); assertEquals(true, StringUtils.containsOnly(str2, chars3)); assertEquals(false, StringUtils.containsOnly(str3, chars1)); assertEquals(false, StringUtils.containsOnly(str3, chars2)); assertEquals(true, StringUtils.containsOnly(str3, chars3)); } public void testContainsWhitespace() { assertFalse( StringUtils.containsWhitespace("") ); assertTrue( StringUtils.containsWhitespace(" ") ); assertFalse( StringUtils.containsWhitespace("a") ); assertTrue( StringUtils.containsWhitespace("a ") ); assertTrue( StringUtils.containsWhitespace(" a") ); assertTrue( StringUtils.containsWhitespace("a\t") ); assertTrue( StringUtils.containsWhitespace("\n") ); } // The purpose of this class is to test StringUtils#equals(CharSequence, CharSequence) // with a CharSequence implementation whose equals(Object) override requires that the // other object be an instance of CustomCharSequence, even though, as char sequences, // `seq` may equal the other object. private static class CustomCharSequence implements CharSequence { private CharSequence seq; public CustomCharSequence(CharSequence seq) { this.seq = seq; } public char charAt(int index) { return seq.charAt(index); } public int length() { return seq.length(); } public CharSequence subSequence(int start, int end) { return new CustomCharSequence(seq.subSequence(start, end)); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof CustomCharSequence)) { return false; } CustomCharSequence other = (CustomCharSequence) obj; return seq.equals(other.seq); } public String toString() { return seq.toString(); } } public void testCustomCharSequence() { assertThat((CharSequence) new CustomCharSequence(FOO), IsNot.<CharSequence>not(FOO)); assertThat((CharSequence) FOO, IsNot.<CharSequence>not(new CustomCharSequence(FOO))); assertEquals(new CustomCharSequence(FOO), new CustomCharSequence(FOO)); } public void testEquals() { final CharSequence fooCs = FOO, barCs = BAR, foobarCs = FOOBAR; assertTrue(StringUtils.equals(null, null)); assertTrue(StringUtils.equals(fooCs, fooCs)); assertTrue(StringUtils.equals(fooCs, (CharSequence) new StringBuilder(FOO))); assertTrue(StringUtils.equals(fooCs, (CharSequence) new String(new char[] { 'f', 'o', 'o' }))); assertTrue(StringUtils.equals(fooCs, (CharSequence) new CustomCharSequence(FOO))); assertTrue(StringUtils.equals((CharSequence) new CustomCharSequence(FOO), fooCs)); assertFalse(StringUtils.equals(fooCs, (CharSequence) new String(new char[] { 'f', 'O', 'O' }))); assertFalse(StringUtils.equals(fooCs, barCs)); assertFalse(StringUtils.equals(fooCs, null)); assertFalse(StringUtils.equals(null, fooCs)); assertFalse(StringUtils.equals(fooCs, foobarCs)); assertFalse(StringUtils.equals(foobarCs, fooCs)); } public void testEqualsOnStrings() { assertTrue(StringUtils.equals(null, null)); assertTrue(StringUtils.equals(FOO, FOO)); assertTrue(StringUtils.equals(FOO, new String(new char[] { 'f', 'o', 'o' }))); assertFalse(StringUtils.equals(FOO, new String(new char[] { 'f', 'O', 'O' }))); assertFalse(StringUtils.equals(FOO, BAR)); assertFalse(StringUtils.equals(FOO, null)); assertFalse(StringUtils.equals(null, FOO)); assertFalse(StringUtils.equals(FOO, FOOBAR)); assertFalse(StringUtils.equals(FOOBAR, FOO)); } public void testEqualsIgnoreCase() { assertEquals(true, StringUtils.equalsIgnoreCase(null, null)); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, FOO)); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'o', 'o' }))); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'O', 'O' }))); assertEquals(false, StringUtils.equalsIgnoreCase(FOO, BAR)); assertEquals(false, StringUtils.equalsIgnoreCase(FOO, null)); assertEquals(false, StringUtils.equalsIgnoreCase(null, FOO)); } //----------------------------------------------------------------------- public void testIndexOf_char() { assertEquals(-1, StringUtils.indexOf(null, ' ')); assertEquals(-1, StringUtils.indexOf("", ' ')); assertEquals(0, StringUtils.indexOf("aabaabaa", 'a')); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b')); assertEquals(2, StringUtils.indexOf(new StringBuilder("aabaabaa"), 'b')); } public void testIndexOf_charInt() { assertEquals(-1, StringUtils.indexOf(null, ' ', 0)); assertEquals(-1, StringUtils.indexOf(null, ' ', -1)); assertEquals(-1, StringUtils.indexOf("", ' ', 0)); assertEquals(-1, StringUtils.indexOf("", ' ', -1)); assertEquals(0, StringUtils.indexOf("aabaabaa", 'a', 0)); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b', 0)); assertEquals(5, StringUtils.indexOf("aabaabaa", 'b', 3)); assertEquals(-1, StringUtils.indexOf("aabaabaa", 'b', 9)); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b', -1)); assertEquals(5, StringUtils.indexOf(new StringBuilder("aabaabaa"), 'b', 3)); } public void testIndexOf_String() { assertEquals(-1, StringUtils.indexOf(null, null)); assertEquals(-1, StringUtils.indexOf("", null)); assertEquals(0, StringUtils.indexOf("", "")); assertEquals(0, StringUtils.indexOf("aabaabaa", "a")); assertEquals(2, StringUtils.indexOf("aabaabaa", "b")); assertEquals(1, StringUtils.indexOf("aabaabaa", "ab")); assertEquals(0, StringUtils.indexOf("aabaabaa", "")); assertEquals(2, StringUtils.indexOf(new StringBuilder("aabaabaa"), "b")); } public void testIndexOf_StringInt() { assertEquals(-1, StringUtils.indexOf(null, null, 0)); assertEquals(-1, StringUtils.indexOf(null, null, -1)); assertEquals(-1, StringUtils.indexOf(null, "", 0)); assertEquals(-1, StringUtils.indexOf(null, "", -1)); assertEquals(-1, StringUtils.indexOf("", null, 0)); assertEquals(-1, StringUtils.indexOf("", null, -1)); assertEquals(0, StringUtils.indexOf("", "", 0)); assertEquals(0, StringUtils.indexOf("", "", -1)); assertEquals(0, StringUtils.indexOf("", "", 9)); assertEquals(0, StringUtils.indexOf("abc", "", 0)); assertEquals(0, StringUtils.indexOf("abc", "", -1)); assertEquals(3, StringUtils.indexOf("abc", "", 9)); assertEquals(3, StringUtils.indexOf("abc", "", 3)); assertEquals(0, StringUtils.indexOf("aabaabaa", "a", 0)); assertEquals(2, StringUtils.indexOf("aabaabaa", "b", 0)); assertEquals(1, StringUtils.indexOf("aabaabaa", "ab", 0)); assertEquals(5, StringUtils.indexOf("aabaabaa", "b", 3)); assertEquals(-1, StringUtils.indexOf("aabaabaa", "b", 9)); assertEquals(2, StringUtils.indexOf("aabaabaa", "b", -1)); assertEquals(2,StringUtils.indexOf("aabaabaa", "", 2)); assertEquals(5, StringUtils.indexOf(new StringBuilder("aabaabaa"), "b", 3)); } public void testIndexOfAny_StringCharArray() { assertEquals(-1, StringUtils.indexOfAny(null, (char[]) null)); assertEquals(-1, StringUtils.indexOfAny(null, new char[0])); assertEquals(-1, StringUtils.indexOfAny(null, new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAny("", (char[]) null)); assertEquals(-1, StringUtils.indexOfAny("", new char[0])); assertEquals(-1, StringUtils.indexOfAny("", new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", (char[]) null)); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", new char[0])); assertEquals(0, StringUtils.indexOfAny("zzabyycdxx", new char[] {'z','a'})); assertEquals(3, StringUtils.indexOfAny("zzabyycdxx", new char[] {'b','y'})); assertEquals(-1, StringUtils.indexOfAny("ab", new char[] {'z'})); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testIndexOfAny_StringCharArrayWithSupplementaryChars() { assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(0, StringUtils.indexOfAny(CharU20000, CharU20000.toCharArray())); assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001.toCharArray())); } public void testIndexOfAny_StringString() { assertEquals(-1, StringUtils.indexOfAny(null, (String) null)); assertEquals(-1, StringUtils.indexOfAny(null, "")); assertEquals(-1, StringUtils.indexOfAny(null, "ab")); assertEquals(-1, StringUtils.indexOfAny("", (String) null)); assertEquals(-1, StringUtils.indexOfAny("", "")); assertEquals(-1, StringUtils.indexOfAny("", "ab")); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", (String) null)); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", "")); assertEquals(0, StringUtils.indexOfAny("zzabyycdxx", "za")); assertEquals(3, StringUtils.indexOfAny("zzabyycdxx", "by")); assertEquals(-1, StringUtils.indexOfAny("ab", "z")); } public void testIndexOfAny_StringStringArray() { assertEquals(-1, StringUtils.indexOfAny(null, (String[]) null)); assertEquals(-1, StringUtils.indexOfAny(null, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, (String[]) null)); assertEquals(2, StringUtils.indexOfAny(FOOBAR, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[0])); assertEquals(-1, StringUtils.indexOfAny(null, new String[0])); assertEquals(-1, StringUtils.indexOfAny("", new String[0])); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[] {"llll"})); assertEquals(0, StringUtils.indexOfAny(FOOBAR, new String[] {""})); assertEquals(0, StringUtils.indexOfAny("", new String[] {""})); assertEquals(-1, StringUtils.indexOfAny("", new String[] {"a"})); assertEquals(-1, StringUtils.indexOfAny("", new String[] {null})); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[] {null})); assertEquals(-1, StringUtils.indexOfAny(null, new String[] {null})); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testIndexOfAny_StringStringWithSupplementaryChars() { assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000)); assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001)); assertEquals(0, StringUtils.indexOfAny(CharU20000, CharU20000)); assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001)); } public void testIndexOfAnyBut_StringCharArray() { assertEquals(-1, StringUtils.indexOfAnyBut(null, (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut(null, new char[0])); assertEquals(-1, StringUtils.indexOfAnyBut(null, new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAnyBut("", (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut("", new char[0])); assertEquals(-1, StringUtils.indexOfAnyBut("", new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", new char[0])); assertEquals(3, StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z','a'})); assertEquals(0, StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'b','y'})); assertEquals(-1, StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'})); assertEquals(0, StringUtils.indexOfAnyBut("aba", new char[] {'z'})); } public void testIndexOfAnyBut_StringCharArrayWithSupplementaryChars() { assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(-1, StringUtils.indexOfAnyBut(CharU20000, CharU20000.toCharArray())); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001.toCharArray())); } public void testIndexOfAnyBut_StringString() { assertEquals(-1, StringUtils.indexOfAnyBut(null, (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut(null, "")); assertEquals(-1, StringUtils.indexOfAnyBut(null, "ab")); assertEquals(-1, StringUtils.indexOfAnyBut("", (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut("", "")); assertEquals(-1, StringUtils.indexOfAnyBut("", "ab")); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", "")); assertEquals(3, StringUtils.indexOfAnyBut("zzabyycdxx", "za")); assertEquals(0, StringUtils.indexOfAnyBut("zzabyycdxx", "by")); assertEquals(0, StringUtils.indexOfAnyBut("ab", "z")); } public void testIndexOfAnyBut_StringStringWithSupplementaryChars() { assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000)); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001)); assertEquals(-1, StringUtils.indexOfAnyBut(CharU20000, CharU20000)); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001)); } public void testIndexOfIgnoreCase_String() { assertEquals(-1, StringUtils.indexOfIgnoreCase(null, null)); assertEquals(-1, StringUtils.indexOfIgnoreCase(null, "")); assertEquals(-1, StringUtils.indexOfIgnoreCase("", null)); assertEquals(0, StringUtils.indexOfIgnoreCase("", "")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "a")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "A")); assertEquals(2, StringUtils.indexOfIgnoreCase("aabaabaa", "b")); assertEquals(2, StringUtils.indexOfIgnoreCase("aabaabaa", "B")); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "ab")); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "")); } public void testIndexOfIgnoreCase_StringInt() { assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", -1)); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0)); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 1)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 2)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 3)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 4)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 5)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 6)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 7)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 8)); assertEquals(1, StringUtils.indexOfIgnoreCase("aab", "AB", 1)); assertEquals(5, StringUtils.indexOfIgnoreCase("aabaabaa", "", 5)); assertEquals(-1, StringUtils.indexOfIgnoreCase("ab", "AAB", 0)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aab", "AAB", 1)); } public void testLastIndexOf_char() { assertEquals(-1, StringUtils.lastIndexOf(null, ' ')); assertEquals(-1, StringUtils.lastIndexOf("", ' ')); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", 'a')); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b')); assertEquals(5, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), 'b')); } public void testLastIndexOf_charInt() { assertEquals(-1, StringUtils.lastIndexOf(null, ' ', 0)); assertEquals(-1, StringUtils.lastIndexOf(null, ' ', -1)); assertEquals(-1, StringUtils.lastIndexOf("", ' ', 0)); assertEquals(-1, StringUtils.lastIndexOf("", ' ', -1)); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", 'a', 8)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b', 8)); assertEquals(2, StringUtils.lastIndexOf("aabaabaa", 'b', 3)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b', 9)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", 'b', -1)); assertEquals(0, StringUtils.lastIndexOf("aabaabaa", 'a', 0)); assertEquals(2, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), 'b', 2)); } public void testLastIndexOf_String() { assertEquals(-1, StringUtils.lastIndexOf(null, null)); assertEquals(-1, StringUtils.lastIndexOf("", null)); assertEquals(-1, StringUtils.lastIndexOf("", "a")); assertEquals(0, StringUtils.lastIndexOf("", "")); assertEquals(8, StringUtils.lastIndexOf("aabaabaa", "")); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", "a")); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b")); assertEquals(4, StringUtils.lastIndexOf("aabaabaa", "ab")); assertEquals(4, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), "ab")); } public void testLastIndexOf_StringInt() { assertEquals(-1, StringUtils.lastIndexOf(null, null, 0)); assertEquals(-1, StringUtils.lastIndexOf(null, null, -1)); assertEquals(-1, StringUtils.lastIndexOf(null, "", 0)); assertEquals(-1, StringUtils.lastIndexOf(null, "", -1)); assertEquals(-1, StringUtils.lastIndexOf("", null, 0)); assertEquals(-1, StringUtils.lastIndexOf("", null, -1)); assertEquals(0, StringUtils.lastIndexOf("", "", 0)); assertEquals(-1, StringUtils.lastIndexOf("", "", -1)); assertEquals(0, StringUtils.lastIndexOf("", "", 9)); assertEquals(0, StringUtils.lastIndexOf("abc", "", 0)); assertEquals(-1, StringUtils.lastIndexOf("abc", "", -1)); assertEquals(3, StringUtils.lastIndexOf("abc", "", 9)); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", "a", 8)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b", 8)); assertEquals(4, StringUtils.lastIndexOf("aabaabaa", "ab", 8)); assertEquals(2, StringUtils.lastIndexOf("aabaabaa", "b", 3)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b", 9)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", -1)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", 0)); assertEquals(0, StringUtils.lastIndexOf("aabaabaa", "a", 0)); assertEquals(2, StringUtils.lastIndexOf(new StringBuilder("aabaabaa"), "b", 3)); } public void testLastIndexOfAny_StringStringArray() { assertEquals(-1, StringUtils.lastIndexOfAny(null, (CharSequence) null)); // test both types of ... assertEquals(-1, StringUtils.lastIndexOfAny(null, (CharSequence[]) null)); // ... varargs invocation assertEquals(-1, StringUtils.lastIndexOfAny(null)); // Missing varag assertEquals(-1, StringUtils.lastIndexOfAny(null, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, (CharSequence) null)); // test both types of ... assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, (CharSequence[]) null)); // ... varargs invocation assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR)); // Missing vararg assertEquals(3, StringUtils.lastIndexOfAny(FOOBAR, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny(null, new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[] {"llll"})); assertEquals(6, StringUtils.lastIndexOfAny(FOOBAR, new String[] {""})); assertEquals(0, StringUtils.lastIndexOfAny("", new String[] {""})); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[] {"a"})); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[] {null})); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[] {null})); assertEquals(-1, StringUtils.lastIndexOfAny(null, new String[] {null})); } public void testLastIndexOfIgnoreCase_String() { assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "")); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", "a")); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "")); assertEquals(8, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "")); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "a")); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A")); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "b")); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B")); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "ab")); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB")); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("ab", "AAB")); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("aab", "AAB")); } public void testLastIndexOfIgnoreCase_StringInt() { assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "", -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null, 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null, -1)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", "", -1)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "", 9)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("abc", "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("abc", "", -1)); assertEquals(3, StringUtils.lastIndexOfIgnoreCase("abc", "", 9)); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8)); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8)); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8)); assertEquals(2, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 3)); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0)); assertEquals(1, StringUtils.lastIndexOfIgnoreCase("aab", "AB", 1)); } public void testLastOrdinalIndexOf() { assertEquals(-1, StringUtils.lastOrdinalIndexOf(null, "*", 42) ); assertEquals(-1, StringUtils.lastOrdinalIndexOf("*", null, 42) ); assertEquals(0, StringUtils.lastOrdinalIndexOf("", "", 42) ); assertEquals(7, StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) ); assertEquals(6, StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) ); assertEquals(5, StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) ); assertEquals(2, StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) ); assertEquals(4, StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) ); assertEquals(1, StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) ); assertEquals(8, StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) ); assertEquals(8, StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) ); } public void testOrdinalIndexOf() { assertEquals(-1, StringUtils.ordinalIndexOf(null, null, Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, -1)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, -1)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", -1)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 0)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 0)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", 0)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 1)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 1)); assertEquals(0, StringUtils.ordinalIndexOf("", "", 1)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "a", 1)); assertEquals(2, StringUtils.ordinalIndexOf("aabaabaa", "b", 1)); assertEquals(1, StringUtils.ordinalIndexOf("aabaabaa", "ab", 1)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", 1)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 2)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 2)); assertEquals(0, StringUtils.ordinalIndexOf("", "", 2)); assertEquals(1, StringUtils.ordinalIndexOf("aabaabaa", "a", 2)); assertEquals(5, StringUtils.ordinalIndexOf("aabaabaa", "b", 2)); assertEquals(4, StringUtils.ordinalIndexOf("aabaabaa", "ab", 2)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", 2)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, Integer.MAX_VALUE)); assertEquals(0, StringUtils.ordinalIndexOf("", "", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", Integer.MAX_VALUE)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 0)); assertEquals(0, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 1)); assertEquals(1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 2)); assertEquals(2, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 3)); assertEquals(3, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 4)); assertEquals(4, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 5)); assertEquals(5, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 6)); assertEquals(6, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 7)); assertEquals(7, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 8)); assertEquals(8, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 9)); assertEquals(-1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 10)); } }
public void testLANG807() { try { RandomStringUtils.random(3,5,5,false,false); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { // distinguish from Random#nextInt message final String msg = ex.getMessage(); assertTrue("Message (" + msg + ") must contain 'start'", msg.contains("start")); assertTrue("Message (" + msg + ") must contain 'end'", msg.contains("end")); } }
org.apache.commons.lang3.RandomStringUtilsTest::testLANG807
src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
141
src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
testLANG807
/* * 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.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; /** * Unit tests {@link org.apache.commons.lang3.RandomStringUtils}. * * @version $Id$ */ public class RandomStringUtilsTest extends junit.framework.TestCase { /** * Construct a new instance of RandomStringUtilsTest with the specified name */ public RandomStringUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new RandomStringUtils()); Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(RandomStringUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(RandomStringUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Test the implementation */ public void testRandomStringUtils() { String r1 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r1.length()); String r2 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAscii(50); assertEquals("randomAscii(50) length", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("char between 32 and 127", r1.charAt(i) >= 32 && r1.charAt(i) <= 127); } r2 = RandomStringUtils.randomAscii(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphabetic(50); assertEquals("randomAlphabetic(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphabetic", true, Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphanumeric(50); assertEquals("randomAlphanumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphanumeric", true, Character.isLetterOrDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomNumeric(50); assertEquals("randomNumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains numeric", true, Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i))); } r2 = RandomStringUtils.randomNumeric(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); String set = "abcdefg"; r1 = RandomStringUtils.random(50, set); assertEquals("random(50, \"abcdefg\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); set = "stuvwxyz"; r1 = RandomStringUtils.random(50, set.toCharArray()); assertEquals("random(50, \"stuvwxyz\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); long seed = System.currentTimeMillis(); r1 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); r2 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); assertEquals("r1.equals(r2)", r1, r2); r1 = RandomStringUtils.random(0); assertEquals("random(0).equals(\"\")", "", r1); } public void testLANG805() { long seed = System.currentTimeMillis(); assertEquals("aaa", RandomStringUtils.random(3,0,0,false,false,new char[]{'a'},new Random(seed))); } public void testLANG807() { try { RandomStringUtils.random(3,5,5,false,false); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { // distinguish from Random#nextInt message final String msg = ex.getMessage(); assertTrue("Message (" + msg + ") must contain 'start'", msg.contains("start")); assertTrue("Message (" + msg + ") must contain 'end'", msg.contains("end")); } } public void testExceptions() { final char[] DUMMY = new char[]{'a'}; // valid char array try { RandomStringUtils.random(-1); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, true, true); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(1, new char[0]); // must not provide empty array => IAE fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, ""); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, (String)null); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()); fail(); } catch (IllegalArgumentException ex) {} } /** * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7 */ public void testRandomAlphaNumeric() {} // Defects4J: flaky method // public void testRandomAlphaNumeric() { // char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'}; // boolean[] found = {false, false, false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphanumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure '0' and '9' are generated by randomNumeric * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46 */ public void testRandomNumeric() {} // Defects4J: flaky method // public void testRandomNumeric() { // char[] testChars = {'0','9'}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomNumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("digit not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure boundary alpha characters are generated by randomAlphabetic * This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8 */ public void testRandomAlphabetic() {} // Defects4J: flaky method // public void testRandomAlphabetic() { // char[] testChars = {'a', 'z', 'A', 'Z'}; // boolean[] found = {false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphabetic(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure 32 and 127 are generated by randomNumeric * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5 */ public void testRandomAscii() {} // Defects4J: flaky method // public void testRandomAscii() { // char[] testChars = {(char) 32, (char) 126}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAscii(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("ascii character not generated in 1000 attempts: " // + (int) testChars[i] + // " -- repeated failures indicate a problem"); // } // } // } /** * Test homogeneity of random strings generated -- * i.e., test that characters show up with expected frequencies * in generated strings. Will fail randomly about 1 in 1000 times. * Repeated failures indicate a problem. */ public void testRandomStringUtilsHomog() {} // Defects4J: flaky method // public void testRandomStringUtilsHomog() { // String set = "abc"; // char[] chars = set.toCharArray(); // String gen = ""; // int[] counts = {0,0,0}; // int[] expected = {200,200,200}; // for (int i = 0; i< 100; i++) { // gen = RandomStringUtils.random(6,chars); // for (int j = 0; j < 6; j++) { // switch (gen.charAt(j)) { // case 'a': {counts[0]++; break;} // case 'b': {counts[1]++; break;} // case 'c': {counts[2]++; break;} // default: {fail("generated character not in set");} // } // } // } // // Perform chi-square test with df = 3-1 = 2, testing at .001 level // assertTrue("test homogeneity -- will fail about 1 in 1000 times", // chiSquare(expected,counts) < 13.82); // } /** * Computes Chi-Square statistic given observed and expected counts * @param observed array of observed frequency counts * @param expected array of expected frequency counts */ private double chiSquare(int[] expected, int[] observed) { double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { dev = observed[i] - expected[i]; sumSq += dev * dev / expected[i]; } return sumSq; } /** * Checks if the string got by {@link RandomStringUtils#random(int)} * can be converted to UTF-8 and back without loss. * * @see <a href="http://issues.apache.org/jira/browse/LANG-100">LANG-100</a> * * @throws Exception */ public void testLang100() throws Exception { int size = 5000; String encoding = "UTF-8"; String orig = RandomStringUtils.random(size); byte[] bytes = orig.getBytes(encoding); String copy = new String(bytes, encoding); // for a verbose compare: for (int i=0; i < orig.length() && i < copy.length(); i++) { char o = orig.charAt(i); char c = copy.charAt(i); assertEquals("differs at " + i + "(" + Integer.toHexString(new Character(o).hashCode()) + "," + Integer.toHexString(new Character(c).hashCode()) + ")", o, c); } // compare length also assertEquals(orig.length(), copy.length()); // just to be complete assertEquals(orig, copy); } }
// You are a professional Java test case writer, please create a test case named `testLANG807` for the issue `Lang-LANG-807`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-807 // // ## Issue-Title: // RandomStringUtils throws confusing IAE when end <= start // // ## Issue-Description: // // RandomUtils invokes Random#nextInt![](/jira/images/icons/emoticons/thumbs_down.png) where n = end - start. // // // If end <= start, then Random throws: // // // java.lang.IllegalArgumentException: n must be positive // // // This is confusing, and does not identify the source of the problem. // // // // // public void testLANG807() {
141
11
132
src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-807 ## Issue-Title: RandomStringUtils throws confusing IAE when end <= start ## Issue-Description: RandomUtils invokes Random#nextInt![](/jira/images/icons/emoticons/thumbs_down.png) where n = end - start. If end <= start, then Random throws: java.lang.IllegalArgumentException: n must be positive This is confusing, and does not identify the source of the problem. ``` You are a professional Java test case writer, please create a test case named `testLANG807` for the issue `Lang-LANG-807`, utilizing the provided issue report information and the following function signature. ```java public void testLANG807() { ```
132
[ "org.apache.commons.lang3.RandomStringUtils" ]
c9b6544df2483679f6bdc02e3ff61da029bbeb90cd920ed9bf117107040d4d8d
public void testLANG807()
// You are a professional Java test case writer, please create a test case named `testLANG807` for the issue `Lang-LANG-807`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-807 // // ## Issue-Title: // RandomStringUtils throws confusing IAE when end <= start // // ## Issue-Description: // // RandomUtils invokes Random#nextInt![](/jira/images/icons/emoticons/thumbs_down.png) where n = end - start. // // // If end <= start, then Random throws: // // // java.lang.IllegalArgumentException: n must be positive // // // This is confusing, and does not identify the source of the problem. // // // // //
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.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; /** * Unit tests {@link org.apache.commons.lang3.RandomStringUtils}. * * @version $Id$ */ public class RandomStringUtilsTest extends junit.framework.TestCase { /** * Construct a new instance of RandomStringUtilsTest with the specified name */ public RandomStringUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new RandomStringUtils()); Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(RandomStringUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(RandomStringUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Test the implementation */ public void testRandomStringUtils() { String r1 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r1.length()); String r2 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAscii(50); assertEquals("randomAscii(50) length", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("char between 32 and 127", r1.charAt(i) >= 32 && r1.charAt(i) <= 127); } r2 = RandomStringUtils.randomAscii(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphabetic(50); assertEquals("randomAlphabetic(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphabetic", true, Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphanumeric(50); assertEquals("randomAlphanumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphanumeric", true, Character.isLetterOrDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomNumeric(50); assertEquals("randomNumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains numeric", true, Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i))); } r2 = RandomStringUtils.randomNumeric(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); String set = "abcdefg"; r1 = RandomStringUtils.random(50, set); assertEquals("random(50, \"abcdefg\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); set = "stuvwxyz"; r1 = RandomStringUtils.random(50, set.toCharArray()); assertEquals("random(50, \"stuvwxyz\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); long seed = System.currentTimeMillis(); r1 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); r2 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); assertEquals("r1.equals(r2)", r1, r2); r1 = RandomStringUtils.random(0); assertEquals("random(0).equals(\"\")", "", r1); } public void testLANG805() { long seed = System.currentTimeMillis(); assertEquals("aaa", RandomStringUtils.random(3,0,0,false,false,new char[]{'a'},new Random(seed))); } public void testLANG807() { try { RandomStringUtils.random(3,5,5,false,false); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { // distinguish from Random#nextInt message final String msg = ex.getMessage(); assertTrue("Message (" + msg + ") must contain 'start'", msg.contains("start")); assertTrue("Message (" + msg + ") must contain 'end'", msg.contains("end")); } } public void testExceptions() { final char[] DUMMY = new char[]{'a'}; // valid char array try { RandomStringUtils.random(-1); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, true, true); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(1, new char[0]); // must not provide empty array => IAE fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, ""); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, (String)null); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()); fail(); } catch (IllegalArgumentException ex) {} } /** * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7 */ public void testRandomAlphaNumeric() {} // Defects4J: flaky method // public void testRandomAlphaNumeric() { // char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'}; // boolean[] found = {false, false, false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphanumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure '0' and '9' are generated by randomNumeric * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46 */ public void testRandomNumeric() {} // Defects4J: flaky method // public void testRandomNumeric() { // char[] testChars = {'0','9'}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomNumeric(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("digit not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure boundary alpha characters are generated by randomAlphabetic * This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8 */ public void testRandomAlphabetic() {} // Defects4J: flaky method // public void testRandomAlphabetic() { // char[] testChars = {'a', 'z', 'A', 'Z'}; // boolean[] found = {false, false, false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAlphabetic(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("alphanumeric character not generated in 1000 attempts: " // + testChars[i] +" -- repeated failures indicate a problem "); // } // } // } /** * Make sure 32 and 127 are generated by randomNumeric * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5 */ public void testRandomAscii() {} // Defects4J: flaky method // public void testRandomAscii() { // char[] testChars = {(char) 32, (char) 126}; // boolean[] found = {false, false}; // for (int i = 0; i < 100; i++) { // String randString = RandomStringUtils.randomAscii(10); // for (int j = 0; j < testChars.length; j++) { // if (randString.indexOf(testChars[j]) > 0) { // found[j] = true; // } // } // } // for (int i = 0; i < testChars.length; i++) { // if (!found[i]) { // fail("ascii character not generated in 1000 attempts: " // + (int) testChars[i] + // " -- repeated failures indicate a problem"); // } // } // } /** * Test homogeneity of random strings generated -- * i.e., test that characters show up with expected frequencies * in generated strings. Will fail randomly about 1 in 1000 times. * Repeated failures indicate a problem. */ public void testRandomStringUtilsHomog() {} // Defects4J: flaky method // public void testRandomStringUtilsHomog() { // String set = "abc"; // char[] chars = set.toCharArray(); // String gen = ""; // int[] counts = {0,0,0}; // int[] expected = {200,200,200}; // for (int i = 0; i< 100; i++) { // gen = RandomStringUtils.random(6,chars); // for (int j = 0; j < 6; j++) { // switch (gen.charAt(j)) { // case 'a': {counts[0]++; break;} // case 'b': {counts[1]++; break;} // case 'c': {counts[2]++; break;} // default: {fail("generated character not in set");} // } // } // } // // Perform chi-square test with df = 3-1 = 2, testing at .001 level // assertTrue("test homogeneity -- will fail about 1 in 1000 times", // chiSquare(expected,counts) < 13.82); // } /** * Computes Chi-Square statistic given observed and expected counts * @param observed array of observed frequency counts * @param expected array of expected frequency counts */ private double chiSquare(int[] expected, int[] observed) { double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { dev = observed[i] - expected[i]; sumSq += dev * dev / expected[i]; } return sumSq; } /** * Checks if the string got by {@link RandomStringUtils#random(int)} * can be converted to UTF-8 and back without loss. * * @see <a href="http://issues.apache.org/jira/browse/LANG-100">LANG-100</a> * * @throws Exception */ public void testLang100() throws Exception { int size = 5000; String encoding = "UTF-8"; String orig = RandomStringUtils.random(size); byte[] bytes = orig.getBytes(encoding); String copy = new String(bytes, encoding); // for a verbose compare: for (int i=0; i < orig.length() && i < copy.length(); i++) { char o = orig.charAt(i); char c = copy.charAt(i); assertEquals("differs at " + i + "(" + Integer.toHexString(new Character(o).hashCode()) + "," + Integer.toHexString(new Character(c).hashCode()) + ")", o, c); } // compare length also assertEquals(orig.length(), copy.length()); // just to be complete assertEquals(orig, copy); } }
@Test public void testSupportsNonAsciiTags() { String body = "<進捗推移グラフ>Yes</進捗推移グラフ>"; Document doc = Jsoup.parse(body); Elements els = doc.select("進捗推移グラフ"); assertEquals("Yes", els.text()); }
org.jsoup.parser.HtmlParserTest::testSupportsNonAsciiTags
src/test/java/org/jsoup/parser/HtmlParserTest.java
891
src/test/java/org/jsoup/parser/HtmlParserTest.java
testSupportsNonAsciiTags
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, [email protected] */ 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</進捗推移グラフ>"; Document doc = Jsoup.parse(body); Elements els = doc.select("進捗推移グラフ"); assertEquals("Yes", els.text()); } }
// You are a professional Java test case writer, please create a test case named `testSupportsNonAsciiTags` for the issue `Jsoup-667`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-667 // // ## Issue-Title: // Problem in reading XML file containing Japanese tag names // // ## Issue-Description: // Hello, // // I have XML file containing Japanese tag names and values. // // JSOUP is not parsing this Japanese tags. // // I am using JSOUP library (version: 1.8.3). // // Please help me to solve this issue. // // // // // --- // // // e.g. ( XML File to reproduce problem ) // // // <進捗推移グラフ> // // <開始予定凡例名 表示状態="0" 線色="00CED1">&#9312;&#35373;&#35336; &#38283;&#22987;&#20104;&#23450;</開始予定凡例名> // // // </進捗推移グラフ> // ---------- // // // //// \*\*\*\* Source Code \*\*\*\*\*\* // // Document doc = Jsoup.parse(XMLString.toString(),"UTF-8",Parser.xmlParser()); // // Elements objElementCollection = doc.getAllElements(); // // // int iElementsSize=objElementCollection.size(); // // // for(Element objCurrent : objElementCollection) // // { // // String szTag=objCurrent.tagName(); // // // // ``` // for (TextNode tnTextNode : objCurrent.textNodes()) // { // String szVal=tnTextNode.text(); // } // // ``` // // } // // // // @Test public void testSupportsNonAsciiTags() {
891
51
886
src/test/java/org/jsoup/parser/HtmlParserTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-667 ## Issue-Title: Problem in reading XML file containing Japanese tag names ## Issue-Description: Hello, I have XML file containing Japanese tag names and values. JSOUP is not parsing this Japanese tags. I am using JSOUP library (version: 1.8.3). Please help me to solve this issue. --- e.g. ( XML File to reproduce problem ) <進捗推移グラフ> <開始予定凡例名 表示状態="0" 線色="00CED1">&#9312;&#35373;&#35336; &#38283;&#22987;&#20104;&#23450;</開始予定凡例名> </進捗推移グラフ> ---------- //// \*\*\*\* Source Code \*\*\*\*\*\* Document doc = Jsoup.parse(XMLString.toString(),"UTF-8",Parser.xmlParser()); Elements objElementCollection = doc.getAllElements(); int iElementsSize=objElementCollection.size(); for(Element objCurrent : objElementCollection) { String szTag=objCurrent.tagName(); ``` for (TextNode tnTextNode : objCurrent.textNodes()) { String szVal=tnTextNode.text(); } ``` } ``` You are a professional Java test case writer, please create a test case named `testSupportsNonAsciiTags` for the issue `Jsoup-667`, utilizing the provided issue report information and the following function signature. ```java @Test public void testSupportsNonAsciiTags() { ```
886
[ "org.jsoup.parser.CharacterReader" ]
ca92fc18b70c4df8007396a1c02f3b8e1c9ca9184313adcca7f6fd168292ded3
@Test public void testSupportsNonAsciiTags()
// You are a professional Java test case writer, please create a test case named `testSupportsNonAsciiTags` for the issue `Jsoup-667`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-667 // // ## Issue-Title: // Problem in reading XML file containing Japanese tag names // // ## Issue-Description: // Hello, // // I have XML file containing Japanese tag names and values. // // JSOUP is not parsing this Japanese tags. // // I am using JSOUP library (version: 1.8.3). // // Please help me to solve this issue. // // // // // --- // // // e.g. ( XML File to reproduce problem ) // // // <進捗推移グラフ> // // <開始予定凡例名 表示状態="0" 線色="00CED1">&#9312;&#35373;&#35336; &#38283;&#22987;&#20104;&#23450;</開始予定凡例名> // // // </進捗推移グラフ> // ---------- // // // //// \*\*\*\* Source Code \*\*\*\*\*\* // // Document doc = Jsoup.parse(XMLString.toString(),"UTF-8",Parser.xmlParser()); // // Elements objElementCollection = doc.getAllElements(); // // // int iElementsSize=objElementCollection.size(); // // // for(Element objCurrent : objElementCollection) // // { // // String szTag=objCurrent.tagName(); // // // // ``` // for (TextNode tnTextNode : objCurrent.textNodes()) // { // String szVal=tnTextNode.text(); // } // // ``` // // } // // // //
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, [email protected] */ 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</進捗推移グラフ>"; Document doc = Jsoup.parse(body); Elements els = doc.select("進捗推移グラフ"); assertEquals("Yes", els.text()); } }
public void testUnquotedIssue510() throws Exception { // NOTE! Requires longer input buffer to trigger longer codepath char[] fullChars = new char[4001]; for (int i = 0; i < 3998; i++) { fullChars[i] = ' '; } fullChars[3998] = '{'; fullChars[3999] = 'a'; fullChars[4000] = 256; JsonParser p = UNQUOTED_FIELDS_F.createParser(new java.io.StringReader(new String(fullChars))); assertToken(JsonToken.START_OBJECT, p.nextToken()); try { p.nextToken(); fail("Should not pass"); } catch (JsonParseException e) { ; // should fail here } p.close(); }
com.fasterxml.jackson.core.read.NonStandardUnquotedNamesTest::testUnquotedIssue510
src/test/java/com/fasterxml/jackson/core/read/NonStandardUnquotedNamesTest.java
54
src/test/java/com/fasterxml/jackson/core/read/NonStandardUnquotedNamesTest.java
testUnquotedIssue510
package com.fasterxml.jackson.core.read; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; public class NonStandardUnquotedNamesTest extends com.fasterxml.jackson.core.BaseTest { private final JsonFactory UNQUOTED_FIELDS_F = new JsonFactory(); { UNQUOTED_FIELDS_F.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); } public void testSimpleUnquotedBytes() throws Exception { _testSimpleUnquoted(MODE_INPUT_STREAM); _testSimpleUnquoted(MODE_INPUT_STREAM_THROTTLED); _testSimpleUnquoted(MODE_DATA_INPUT); } public void testSimpleUnquotedChars() throws Exception { _testSimpleUnquoted(MODE_READER); } public void testLargeUnquoted() throws Exception { _testLargeUnquoted(MODE_INPUT_STREAM); _testLargeUnquoted(MODE_INPUT_STREAM_THROTTLED); _testLargeUnquoted(MODE_DATA_INPUT); _testLargeUnquoted(MODE_READER); } // [core#510]: ArrayIndexOutOfBounds public void testUnquotedIssue510() throws Exception { // NOTE! Requires longer input buffer to trigger longer codepath char[] fullChars = new char[4001]; for (int i = 0; i < 3998; i++) { fullChars[i] = ' '; } fullChars[3998] = '{'; fullChars[3999] = 'a'; fullChars[4000] = 256; JsonParser p = UNQUOTED_FIELDS_F.createParser(new java.io.StringReader(new String(fullChars))); assertToken(JsonToken.START_OBJECT, p.nextToken()); try { p.nextToken(); fail("Should not pass"); } catch (JsonParseException e) { ; // should fail here } p.close(); } /* /**************************************************************** /* Secondary test methods /**************************************************************** */ private void _testLargeUnquoted(int mode) throws Exception { StringBuilder sb = new StringBuilder(5000); sb.append("[\n"); //final int REPS = 2000; final int REPS = 1050; for (int i = 0; i < REPS; ++i) { if (i > 0) { sb.append(','); if ((i & 7) == 0) { sb.append('\n'); } } sb.append("{"); sb.append("abc").append(i&127).append(':'); sb.append((i & 1) != 0); sb.append("}\n"); } sb.append("]"); String JSON = sb.toString(); JsonParser p = createParser(UNQUOTED_FIELDS_F, mode, JSON); assertToken(JsonToken.START_ARRAY, p.nextToken()); for (int i = 0; i < REPS; ++i) { assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("abc"+(i&127), p.getCurrentName()); assertToken(((i&1) != 0) ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); } assertToken(JsonToken.END_ARRAY, p.nextToken()); p.close(); } private void _testSimpleUnquoted(int mode) throws Exception { String JSON = "{ a : 1, _foo:true, $:\"money!\", \" \":null }"; JsonParser p = createParser(UNQUOTED_FIELDS_F, mode, JSON); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("a", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("_foo", p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("$", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("money!", p.getText()); // and then regular quoted one should still work too: assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(" ", p.getCurrentName()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); // Another thing, as per [Issue#102]: numbers JSON = "{ 123:true,4:false }"; p = createParser(UNQUOTED_FIELDS_F, mode, JSON); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("123", p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("4", p.getCurrentName()); assertToken(JsonToken.VALUE_FALSE, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); } }
// You are a professional Java test case writer, please create a test case named `testUnquotedIssue510` for the issue `JacksonCore-510`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-510 // // ## Issue-Title: // Fix ArrayIndexOutofBoundsException found by LGTM.com // // ## Issue-Description: // First of all, thank you for reporting this. // // // But would it be possible to write a test that shows how this actually works? It would be great to have a regression test, to guard against this happening in future. // // // // public void testUnquotedIssue510() throws Exception {
54
// [core#510]: ArrayIndexOutOfBounds
25
34
src/test/java/com/fasterxml/jackson/core/read/NonStandardUnquotedNamesTest.java
src/test/java
```markdown ## Issue-ID: JacksonCore-510 ## Issue-Title: Fix ArrayIndexOutofBoundsException found by LGTM.com ## Issue-Description: First of all, thank you for reporting this. But would it be possible to write a test that shows how this actually works? It would be great to have a regression test, to guard against this happening in future. ``` You are a professional Java test case writer, please create a test case named `testUnquotedIssue510` for the issue `JacksonCore-510`, utilizing the provided issue report information and the following function signature. ```java public void testUnquotedIssue510() throws Exception { ```
34
[ "com.fasterxml.jackson.core.json.ReaderBasedJsonParser" ]
caa3a9ad98b7c62056981b8c42b3f1cc71633ba24267573c74baade4295da0d2
public void testUnquotedIssue510() throws Exception
// You are a professional Java test case writer, please create a test case named `testUnquotedIssue510` for the issue `JacksonCore-510`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonCore-510 // // ## Issue-Title: // Fix ArrayIndexOutofBoundsException found by LGTM.com // // ## Issue-Description: // First of all, thank you for reporting this. // // // But would it be possible to write a test that shows how this actually works? It would be great to have a regression test, to guard against this happening in future. // // // //
JacksonCore
package com.fasterxml.jackson.core.read; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; public class NonStandardUnquotedNamesTest extends com.fasterxml.jackson.core.BaseTest { private final JsonFactory UNQUOTED_FIELDS_F = new JsonFactory(); { UNQUOTED_FIELDS_F.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); } public void testSimpleUnquotedBytes() throws Exception { _testSimpleUnquoted(MODE_INPUT_STREAM); _testSimpleUnquoted(MODE_INPUT_STREAM_THROTTLED); _testSimpleUnquoted(MODE_DATA_INPUT); } public void testSimpleUnquotedChars() throws Exception { _testSimpleUnquoted(MODE_READER); } public void testLargeUnquoted() throws Exception { _testLargeUnquoted(MODE_INPUT_STREAM); _testLargeUnquoted(MODE_INPUT_STREAM_THROTTLED); _testLargeUnquoted(MODE_DATA_INPUT); _testLargeUnquoted(MODE_READER); } // [core#510]: ArrayIndexOutOfBounds public void testUnquotedIssue510() throws Exception { // NOTE! Requires longer input buffer to trigger longer codepath char[] fullChars = new char[4001]; for (int i = 0; i < 3998; i++) { fullChars[i] = ' '; } fullChars[3998] = '{'; fullChars[3999] = 'a'; fullChars[4000] = 256; JsonParser p = UNQUOTED_FIELDS_F.createParser(new java.io.StringReader(new String(fullChars))); assertToken(JsonToken.START_OBJECT, p.nextToken()); try { p.nextToken(); fail("Should not pass"); } catch (JsonParseException e) { ; // should fail here } p.close(); } /* /**************************************************************** /* Secondary test methods /**************************************************************** */ private void _testLargeUnquoted(int mode) throws Exception { StringBuilder sb = new StringBuilder(5000); sb.append("[\n"); //final int REPS = 2000; final int REPS = 1050; for (int i = 0; i < REPS; ++i) { if (i > 0) { sb.append(','); if ((i & 7) == 0) { sb.append('\n'); } } sb.append("{"); sb.append("abc").append(i&127).append(':'); sb.append((i & 1) != 0); sb.append("}\n"); } sb.append("]"); String JSON = sb.toString(); JsonParser p = createParser(UNQUOTED_FIELDS_F, mode, JSON); assertToken(JsonToken.START_ARRAY, p.nextToken()); for (int i = 0; i < REPS; ++i) { assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("abc"+(i&127), p.getCurrentName()); assertToken(((i&1) != 0) ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); } assertToken(JsonToken.END_ARRAY, p.nextToken()); p.close(); } private void _testSimpleUnquoted(int mode) throws Exception { String JSON = "{ a : 1, _foo:true, $:\"money!\", \" \":null }"; JsonParser p = createParser(UNQUOTED_FIELDS_F, mode, JSON); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("a", p.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("_foo", p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("$", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("money!", p.getText()); // and then regular quoted one should still work too: assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals(" ", p.getCurrentName()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); // Another thing, as per [Issue#102]: numbers JSON = "{ 123:true,4:false }"; p = createParser(UNQUOTED_FIELDS_F, mode, JSON); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("123", p.getCurrentName()); assertToken(JsonToken.VALUE_TRUE, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("4", p.getCurrentName()); assertToken(JsonToken.VALUE_FALSE, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); } }
@Test public void escapesGtInXmlAttributesButNotInHtml() { // https://github.com/jhy/jsoup/issues/528 - < is OK in HTML attribute values, but not in XML String docHtml = "<a title='<p>One</p>'>One</a>"; Document doc = Jsoup.parse(docHtml); Element element = doc.select("a").first(); doc.outputSettings().escapeMode(base); assertEquals("<a title=\"<p>One</p>\">One</a>", element.outerHtml()); doc.outputSettings().escapeMode(xhtml); assertEquals("<a title=\"&lt;p>One&lt;/p>\">One</a>", element.outerHtml()); }
org.jsoup.nodes.EntitiesTest::escapesGtInXmlAttributesButNotInHtml
src/test/java/org/jsoup/nodes/EntitiesTest.java
102
src/test/java/org/jsoup/nodes/EntitiesTest.java
escapesGtInXmlAttributesButNotInHtml
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.junit.Test; import static org.jsoup.nodes.Document.OutputSettings; import static org.jsoup.nodes.Entities.EscapeMode.*; import static org.junit.Assert.*; public class EntitiesTest { @Test public void escape() { String text = "Hello &<> Å å π 新 there ¾ © »"; String escapedAscii = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(base)); String escapedAsciiFull = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(extended)); String escapedAsciiXhtml = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(xhtml)); String escapedUtfFull = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(extended)); String escapedUtfMin = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(xhtml)); assertEquals("Hello &amp;&lt;&gt; &Aring; &aring; &#x3c0; &#x65b0; there &frac34; &copy; &raquo;", escapedAscii); assertEquals("Hello &amp;&lt;&gt; &angst; &aring; &pi; &#x65b0; there &frac34; &copy; &raquo;", escapedAsciiFull); assertEquals("Hello &amp;&lt;&gt; &#xc5; &#xe5; &#x3c0; &#x65b0; there &#xbe; &#xa9; &#xbb;", escapedAsciiXhtml); assertEquals("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfFull); assertEquals("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfMin); // odd that it's defined as aring in base but angst in full // round trip assertEquals(text, Entities.unescape(escapedAscii)); assertEquals(text, Entities.unescape(escapedAsciiFull)); assertEquals(text, Entities.unescape(escapedAsciiXhtml)); assertEquals(text, Entities.unescape(escapedUtfFull)); assertEquals(text, Entities.unescape(escapedUtfMin)); } @Test public void escapeSupplementaryCharacter(){ String text = new String(Character.toChars(135361)); String escapedAscii = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(base)); assertEquals("&#x210c1;", escapedAscii); String escapedUtf = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(base)); assertEquals(text, escapedUtf); } @Test public void unescape() { String text = "Hello &amp;&LT&gt; &reg &angst; &angst &#960; &#960 &#x65B0; there &! &frac34; &copy; &COPY;"; assertEquals("Hello &<> ® Å &angst π π 新 there &! ¾ © ©", Entities.unescape(text)); assertEquals("&0987654321; &unknown", Entities.unescape("&0987654321; &unknown")); } @Test public void strictUnescape() { // for attributes, enforce strict unescaping (must look like &#xxx; , not just &#xxx) String text = "Hello &amp= &amp;"; assertEquals("Hello &amp= &", Entities.unescape(text, true)); assertEquals("Hello &= &", Entities.unescape(text)); assertEquals("Hello &= &", Entities.unescape(text, false)); } @Test public void caseSensitive() { String unescaped = "Ü ü & &"; assertEquals("&Uuml; &uuml; &amp; &amp;", Entities.escape(unescaped, new OutputSettings().charset("ascii").escapeMode(extended))); String escaped = "&Uuml; &uuml; &amp; &AMP"; assertEquals("Ü ü & &", Entities.unescape(escaped)); } @Test public void quoteReplacements() { String escaped = "&#92; &#36;"; String unescaped = "\\ $"; assertEquals(unescaped, Entities.unescape(escaped)); } @Test public void letterDigitEntities() { String html = "<p>&sup1;&sup2;&sup3;&frac14;&frac12;&frac34;</p>"; Document doc = Jsoup.parse(html); doc.outputSettings().charset("ascii"); Element p = doc.select("p").first(); assertEquals("&sup1;&sup2;&sup3;&frac14;&frac12;&frac34;", p.html()); assertEquals("¹²³¼½¾", p.text()); doc.outputSettings().charset("UTF-8"); assertEquals("¹²³¼½¾", p.html()); } @Test public void noSpuriousDecodes() { String string = "http://www.foo.com?a=1&num_rooms=1&children=0&int=VA&b=2"; assertEquals(string, Entities.unescape(string)); } @Test public void escapesGtInXmlAttributesButNotInHtml() { // https://github.com/jhy/jsoup/issues/528 - < is OK in HTML attribute values, but not in XML String docHtml = "<a title='<p>One</p>'>One</a>"; Document doc = Jsoup.parse(docHtml); Element element = doc.select("a").first(); doc.outputSettings().escapeMode(base); assertEquals("<a title=\"<p>One</p>\">One</a>", element.outerHtml()); doc.outputSettings().escapeMode(xhtml); assertEquals("<a title=\"&lt;p>One&lt;/p>\">One</a>", element.outerHtml()); } }
// You are a professional Java test case writer, please create a test case named `escapesGtInXmlAttributesButNotInHtml` for the issue `Jsoup-528`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-528 // // ## Issue-Title: // Jsoup not retaining &lt in data attributes // // ## Issue-Description: // Jsoup not retaining &lt in data attributes value if there is < // // // In the example below &lt; is converted to < in the output after parsing. // // Please let me know how to retain it. // // Example: // // <http://notes.io/Gww> // // [@uggedal](https://github.com/uggedal) // // @krystiangor // // [@tc](https://github.com/tc) // // [@bbeck](https://github.com/bbeck) // // // // @Test public void escapesGtInXmlAttributesButNotInHtml() {
102
47
89
src/test/java/org/jsoup/nodes/EntitiesTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-528 ## Issue-Title: Jsoup not retaining &lt in data attributes ## Issue-Description: Jsoup not retaining &lt in data attributes value if there is < In the example below &lt; is converted to < in the output after parsing. Please let me know how to retain it. Example: <http://notes.io/Gww> [@uggedal](https://github.com/uggedal) @krystiangor [@tc](https://github.com/tc) [@bbeck](https://github.com/bbeck) ``` You are a professional Java test case writer, please create a test case named `escapesGtInXmlAttributesButNotInHtml` for the issue `Jsoup-528`, utilizing the provided issue report information and the following function signature. ```java @Test public void escapesGtInXmlAttributesButNotInHtml() { ```
89
[ "org.jsoup.nodes.Entities" ]
cb9f0d0abcd2987c6fe1545bc142032dbbc6e0685503ba66252edc49c7cbc60c
@Test public void escapesGtInXmlAttributesButNotInHtml()
// You are a professional Java test case writer, please create a test case named `escapesGtInXmlAttributesButNotInHtml` for the issue `Jsoup-528`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-528 // // ## Issue-Title: // Jsoup not retaining &lt in data attributes // // ## Issue-Description: // Jsoup not retaining &lt in data attributes value if there is < // // // In the example below &lt; is converted to < in the output after parsing. // // Please let me know how to retain it. // // Example: // // <http://notes.io/Gww> // // [@uggedal](https://github.com/uggedal) // // @krystiangor // // [@tc](https://github.com/tc) // // [@bbeck](https://github.com/bbeck) // // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.junit.Test; import static org.jsoup.nodes.Document.OutputSettings; import static org.jsoup.nodes.Entities.EscapeMode.*; import static org.junit.Assert.*; public class EntitiesTest { @Test public void escape() { String text = "Hello &<> Å å π 新 there ¾ © »"; String escapedAscii = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(base)); String escapedAsciiFull = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(extended)); String escapedAsciiXhtml = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(xhtml)); String escapedUtfFull = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(extended)); String escapedUtfMin = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(xhtml)); assertEquals("Hello &amp;&lt;&gt; &Aring; &aring; &#x3c0; &#x65b0; there &frac34; &copy; &raquo;", escapedAscii); assertEquals("Hello &amp;&lt;&gt; &angst; &aring; &pi; &#x65b0; there &frac34; &copy; &raquo;", escapedAsciiFull); assertEquals("Hello &amp;&lt;&gt; &#xc5; &#xe5; &#x3c0; &#x65b0; there &#xbe; &#xa9; &#xbb;", escapedAsciiXhtml); assertEquals("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfFull); assertEquals("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfMin); // odd that it's defined as aring in base but angst in full // round trip assertEquals(text, Entities.unescape(escapedAscii)); assertEquals(text, Entities.unescape(escapedAsciiFull)); assertEquals(text, Entities.unescape(escapedAsciiXhtml)); assertEquals(text, Entities.unescape(escapedUtfFull)); assertEquals(text, Entities.unescape(escapedUtfMin)); } @Test public void escapeSupplementaryCharacter(){ String text = new String(Character.toChars(135361)); String escapedAscii = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(base)); assertEquals("&#x210c1;", escapedAscii); String escapedUtf = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(base)); assertEquals(text, escapedUtf); } @Test public void unescape() { String text = "Hello &amp;&LT&gt; &reg &angst; &angst &#960; &#960 &#x65B0; there &! &frac34; &copy; &COPY;"; assertEquals("Hello &<> ® Å &angst π π 新 there &! ¾ © ©", Entities.unescape(text)); assertEquals("&0987654321; &unknown", Entities.unescape("&0987654321; &unknown")); } @Test public void strictUnescape() { // for attributes, enforce strict unescaping (must look like &#xxx; , not just &#xxx) String text = "Hello &amp= &amp;"; assertEquals("Hello &amp= &", Entities.unescape(text, true)); assertEquals("Hello &= &", Entities.unescape(text)); assertEquals("Hello &= &", Entities.unescape(text, false)); } @Test public void caseSensitive() { String unescaped = "Ü ü & &"; assertEquals("&Uuml; &uuml; &amp; &amp;", Entities.escape(unescaped, new OutputSettings().charset("ascii").escapeMode(extended))); String escaped = "&Uuml; &uuml; &amp; &AMP"; assertEquals("Ü ü & &", Entities.unescape(escaped)); } @Test public void quoteReplacements() { String escaped = "&#92; &#36;"; String unescaped = "\\ $"; assertEquals(unescaped, Entities.unescape(escaped)); } @Test public void letterDigitEntities() { String html = "<p>&sup1;&sup2;&sup3;&frac14;&frac12;&frac34;</p>"; Document doc = Jsoup.parse(html); doc.outputSettings().charset("ascii"); Element p = doc.select("p").first(); assertEquals("&sup1;&sup2;&sup3;&frac14;&frac12;&frac34;", p.html()); assertEquals("¹²³¼½¾", p.text()); doc.outputSettings().charset("UTF-8"); assertEquals("¹²³¼½¾", p.html()); } @Test public void noSpuriousDecodes() { String string = "http://www.foo.com?a=1&num_rooms=1&children=0&int=VA&b=2"; assertEquals(string, Entities.unescape(string)); } @Test public void escapesGtInXmlAttributesButNotInHtml() { // https://github.com/jhy/jsoup/issues/528 - < is OK in HTML attribute values, but not in XML String docHtml = "<a title='<p>One</p>'>One</a>"; Document doc = Jsoup.parse(docHtml); Element element = doc.select("a").first(); doc.outputSettings().escapeMode(base); assertEquals("<a title=\"<p>One</p>\">One</a>", element.outerHtml()); doc.outputSettings().escapeMode(xhtml); assertEquals("<a title=\"&lt;p>One&lt;/p>\">One</a>", element.outerHtml()); } }
@Test(expected=MathIllegalStateException.class) public void testMath844() { final double[] y = { 0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0, 1, 2, 3, 2, 1, 0 }; final int len = y.length; final WeightedObservedPoint[] points = new WeightedObservedPoint[len]; for (int i = 0; i < len; i++) { points[i] = new WeightedObservedPoint(1, i, y[i]); } final HarmonicFitter.ParameterGuesser guesser = new HarmonicFitter.ParameterGuesser(points); // The guesser fails because the function is far from an harmonic // function: It is a triangular periodic function with amplitude 3 // and period 12, and all sample points are taken at integer abscissae // so function values all belong to the integer subset {-3, -2, -1, 0, // 1, 2, 3}. guesser.guess(); }
org.apache.commons.math3.optimization.fitting.HarmonicFitterTest::testMath844
src/test/java/org/apache/commons/math3/optimization/fitting/HarmonicFitterTest.java
202
src/test/java/org/apache/commons/math3/optimization/fitting/HarmonicFitterTest.java
testMath844
// 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.function.HarmonicOscillator; import org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; import org.junit.Test; import org.junit.Assert; public class HarmonicFitterTest { @Test(expected=NumberIsTooSmallException.class) public void testPreconditions1() { HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); fitter.fit(); } // This test fails (throwing "ConvergenceException" instead). // @Test(expected=ZeroException.class) // public void testPreconditions2() { // HarmonicFitter fitter = // new HarmonicFitter(new LevenbergMarquardtOptimizer()); // final double x = 1.2; // fitter.addObservedPoint(1, x, 1); // fitter.addObservedPoint(1, x, -1); // fitter.addObservedPoint(1, x, 0.5); // fitter.addObservedPoint(1, x, 0); // final double[] fitted = fitter.fit(); // } @Test public void testNoError() { final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 1.3; x += 0.01) { fitter.addObservedPoint(1, x, f.value(x)); } final double[] fitted = fitter.fit(); Assert.assertEquals(a, fitted[0], 1.0e-13); Assert.assertEquals(w, fitted[1], 1.0e-13); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1e-13); HarmonicOscillator ff = new HarmonicOscillator(fitted[0], fitted[1], fitted[2]); for (double x = -1.0; x < 1.0; x += 0.01) { Assert.assertTrue(FastMath.abs(f.value(x) - ff.value(x)) < 1e-13); } } @Test public void test1PercentError() { Random randomizer = new Random(64925784252l); final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 10.0; x += 0.1) { fitter.addObservedPoint(1, x, f.value(x) + 0.01 * randomizer.nextGaussian()); } final double[] fitted = fitter.fit(); Assert.assertEquals(a, fitted[0], 7.6e-4); Assert.assertEquals(w, fitted[1], 2.7e-3); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.3e-2); } @Test public void testTinyVariationsData() { Random randomizer = new Random(64925784252l); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 10.0; x += 0.1) { fitter.addObservedPoint(1, x, 1e-7 * randomizer.nextGaussian()); } fitter.fit(); // This test serves to cover the part of the code of "guessAOmega" // when the algorithm using integrals fails. } @Test public void testInitialGuess() { Random randomizer = new Random(45314242l); final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 10.0; x += 0.1) { fitter.addObservedPoint(1, x, f.value(x) + 0.01 * randomizer.nextGaussian()); } final double[] fitted = fitter.fit(new double[] { 0.15, 3.6, 4.5 }); Assert.assertEquals(a, fitted[0], 1.2e-3); Assert.assertEquals(w, fitted[1], 3.3e-3); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.7e-2); } @Test public void testUnsorted() { Random randomizer = new Random(64925784252l); final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); // build a regularly spaced array of measurements int size = 100; double[] xTab = new double[size]; double[] yTab = new double[size]; for (int i = 0; i < size; ++i) { xTab[i] = 0.1 * i; yTab[i] = f.value(xTab[i]) + 0.01 * randomizer.nextGaussian(); } // shake it for (int i = 0; i < size; ++i) { int i1 = randomizer.nextInt(size); int i2 = randomizer.nextInt(size); double xTmp = xTab[i1]; double yTmp = yTab[i1]; xTab[i1] = xTab[i2]; yTab[i1] = yTab[i2]; xTab[i2] = xTmp; yTab[i2] = yTmp; } // pass it to the fitter for (int i = 0; i < size; ++i) { fitter.addObservedPoint(1, xTab[i], yTab[i]); } final double[] fitted = fitter.fit(); Assert.assertEquals(a, fitted[0], 7.6e-4); Assert.assertEquals(w, fitted[1], 3.5e-3); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.5e-2); } @Test(expected=MathIllegalStateException.class) public void testMath844() { final double[] y = { 0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0, 1, 2, 3, 2, 1, 0 }; final int len = y.length; final WeightedObservedPoint[] points = new WeightedObservedPoint[len]; for (int i = 0; i < len; i++) { points[i] = new WeightedObservedPoint(1, i, y[i]); } final HarmonicFitter.ParameterGuesser guesser = new HarmonicFitter.ParameterGuesser(points); // The guesser fails because the function is far from an harmonic // function: It is a triangular periodic function with amplitude 3 // and period 12, and all sample points are taken at integer abscissae // so function values all belong to the integer subset {-3, -2, -1, 0, // 1, 2, 3}. guesser.guess(); } }
// You are a professional Java test case writer, please create a test case named `testMath844` for the issue `Math-MATH-844`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-844 // // ## Issue-Title: // "HarmonicFitter.ParameterGuesser" sometimes fails to return sensible values // // ## Issue-Description: // // The inner class "ParameterGuesser" in "HarmonicFitter" (package "o.a.c.m.optimization.fitting") fails to compute a usable guess for the "amplitude" parameter. // // // // // @Test(expected=MathIllegalStateException.class) public void testMath844() {
202
25
180
src/test/java/org/apache/commons/math3/optimization/fitting/HarmonicFitterTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-844 ## Issue-Title: "HarmonicFitter.ParameterGuesser" sometimes fails to return sensible values ## Issue-Description: The inner class "ParameterGuesser" in "HarmonicFitter" (package "o.a.c.m.optimization.fitting") fails to compute a usable guess for the "amplitude" parameter. ``` You are a professional Java test case writer, please create a test case named `testMath844` for the issue `Math-MATH-844`, utilizing the provided issue report information and the following function signature. ```java @Test(expected=MathIllegalStateException.class) public void testMath844() { ```
180
[ "org.apache.commons.math3.optimization.fitting.HarmonicFitter" ]
cba02968c7549104e746d48388ee23ad0e5eed4a58f0215849474d2c476eec67
@Test(expected=MathIllegalStateException.class) public void testMath844()
// You are a professional Java test case writer, please create a test case named `testMath844` for the issue `Math-MATH-844`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-844 // // ## Issue-Title: // "HarmonicFitter.ParameterGuesser" sometimes fails to return sensible values // // ## Issue-Description: // // The inner class "ParameterGuesser" in "HarmonicFitter" (package "o.a.c.m.optimization.fitting") fails to compute a usable guess for the "amplitude" parameter. // // // // //
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.function.HarmonicOscillator; import org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; import org.junit.Test; import org.junit.Assert; public class HarmonicFitterTest { @Test(expected=NumberIsTooSmallException.class) public void testPreconditions1() { HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); fitter.fit(); } // This test fails (throwing "ConvergenceException" instead). // @Test(expected=ZeroException.class) // public void testPreconditions2() { // HarmonicFitter fitter = // new HarmonicFitter(new LevenbergMarquardtOptimizer()); // final double x = 1.2; // fitter.addObservedPoint(1, x, 1); // fitter.addObservedPoint(1, x, -1); // fitter.addObservedPoint(1, x, 0.5); // fitter.addObservedPoint(1, x, 0); // final double[] fitted = fitter.fit(); // } @Test public void testNoError() { final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 1.3; x += 0.01) { fitter.addObservedPoint(1, x, f.value(x)); } final double[] fitted = fitter.fit(); Assert.assertEquals(a, fitted[0], 1.0e-13); Assert.assertEquals(w, fitted[1], 1.0e-13); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1e-13); HarmonicOscillator ff = new HarmonicOscillator(fitted[0], fitted[1], fitted[2]); for (double x = -1.0; x < 1.0; x += 0.01) { Assert.assertTrue(FastMath.abs(f.value(x) - ff.value(x)) < 1e-13); } } @Test public void test1PercentError() { Random randomizer = new Random(64925784252l); final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 10.0; x += 0.1) { fitter.addObservedPoint(1, x, f.value(x) + 0.01 * randomizer.nextGaussian()); } final double[] fitted = fitter.fit(); Assert.assertEquals(a, fitted[0], 7.6e-4); Assert.assertEquals(w, fitted[1], 2.7e-3); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.3e-2); } @Test public void testTinyVariationsData() { Random randomizer = new Random(64925784252l); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 10.0; x += 0.1) { fitter.addObservedPoint(1, x, 1e-7 * randomizer.nextGaussian()); } fitter.fit(); // This test serves to cover the part of the code of "guessAOmega" // when the algorithm using integrals fails. } @Test public void testInitialGuess() { Random randomizer = new Random(45314242l); final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); for (double x = 0.0; x < 10.0; x += 0.1) { fitter.addObservedPoint(1, x, f.value(x) + 0.01 * randomizer.nextGaussian()); } final double[] fitted = fitter.fit(new double[] { 0.15, 3.6, 4.5 }); Assert.assertEquals(a, fitted[0], 1.2e-3); Assert.assertEquals(w, fitted[1], 3.3e-3); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.7e-2); } @Test public void testUnsorted() { Random randomizer = new Random(64925784252l); final double a = 0.2; final double w = 3.4; final double p = 4.1; HarmonicOscillator f = new HarmonicOscillator(a, w, p); HarmonicFitter fitter = new HarmonicFitter(new LevenbergMarquardtOptimizer()); // build a regularly spaced array of measurements int size = 100; double[] xTab = new double[size]; double[] yTab = new double[size]; for (int i = 0; i < size; ++i) { xTab[i] = 0.1 * i; yTab[i] = f.value(xTab[i]) + 0.01 * randomizer.nextGaussian(); } // shake it for (int i = 0; i < size; ++i) { int i1 = randomizer.nextInt(size); int i2 = randomizer.nextInt(size); double xTmp = xTab[i1]; double yTmp = yTab[i1]; xTab[i1] = xTab[i2]; yTab[i1] = yTab[i2]; xTab[i2] = xTmp; yTab[i2] = yTmp; } // pass it to the fitter for (int i = 0; i < size; ++i) { fitter.addObservedPoint(1, xTab[i], yTab[i]); } final double[] fitted = fitter.fit(); Assert.assertEquals(a, fitted[0], 7.6e-4); Assert.assertEquals(w, fitted[1], 3.5e-3); Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1.5e-2); } @Test(expected=MathIllegalStateException.class) public void testMath844() { final double[] y = { 0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0, 1, 2, 3, 2, 1, 0 }; final int len = y.length; final WeightedObservedPoint[] points = new WeightedObservedPoint[len]; for (int i = 0; i < len; i++) { points[i] = new WeightedObservedPoint(1, i, y[i]); } final HarmonicFitter.ParameterGuesser guesser = new HarmonicFitter.ParameterGuesser(points); // The guesser fails because the function is far from an harmonic // function: It is a triangular periodic function with amplitude 3 // and period 12, and all sample points are taken at integer abscissae // so function values all belong to the integer subset {-3, -2, -1, 0, // 1, 2, 3}. guesser.guess(); } }
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")); }
com.google.javascript.jscomp.LooseTypeCheckTest::testDuplicateLocalVarDecl
test/com/google/javascript/jscomp/LooseTypeCheckTest.java
1,978
test/com/google/javascript/jscomp/LooseTypeCheckTest.java
testDuplicateLocalVarDecl
/* * 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.CheckLevel; 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}. * * This is a temporary fork of the TypeCheckTest for the experimental * "looseTypes" option. These tests should be be folded into TypeCheckTest * or removed along with the looseTypes option. * */ public class LooseTypeCheckTest extends CompilerTypeTestCase { @Override public CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.looseTypes = true; return options; } 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} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16a() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16b() 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|undefined}\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|undefined)\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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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 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 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", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createOptionalType(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"); } // 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|undefined)"); } 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|undefined)>\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 (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 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 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 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("/** @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;"); } 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|undefined)\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|undefined) */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type (null|undefined) */" + "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|null} */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|null} */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 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 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|undefined)\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|undefined)\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)"); } 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 testControlFlowRestrictsType1a() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }\n" + "/** @type {String?} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null|undefined) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1b() throws Exception { testTypes("/** @return {!String|null} */ function f() { return null; }\n" + "/** @type {!String|null} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1c() throws Exception { testTypes("/** @return {!String|undefined} */\n" + "function f() { return undefined; }\n" + "/** @type {!String|undefined} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type undefined */ var c = undefined;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } 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 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|undefined)"); } 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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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();", "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 { // 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 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|undefined)\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(createUnionType(OBJECT_TYPE, NULL_TYPE), VOID_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 4; };" + "/** @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 { 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() {};", "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 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 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() { };", // "cannot reference an interface ouside 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 testWarnDataPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @type {number} */T.prototype.x;", // "interface members can only be plain functions"); //} 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|undefined)"); } // 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|undefined)\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|undefined)"); } 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|undefined)"); } 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 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 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.createOptionalType( 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() { 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); } 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 { 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(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); } 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 `testDuplicateLocalVarDecl` for the issue `Closure-433`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-433 // // ## Issue-Title: // unexpected typed coverage of less than 100% // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Create JavaScript file: // /\*global window\*/ // /\*jslint sub: true\*/ // /\*\* // \* @constructor // \* @param {!Element} element // \*/ // function Example(element) { // /\*\* // \* @param {!string} ns // \* @param {!string} name // \* @return {undefined} // \*/ // this.appendElement = function appendElement(ns, name) { // var e = element.ownerDocument.createElementNS(ns, name); // element.appendChild(e); // }; // } // window["Example"] = Example; // 2. compile it: // java -jar compiler.jar --jscomp\_error checkTypes --summary\_detail\_level 3 --js v.js --js\_output\_file compiled.js // 3. observe the outcome: // 0 error(s), 0 warning(s), 73.7% typed // // **What is the expected output? What do you see instead?** // This was expected: // 0 error(s), 0 warning(s), 100% typed // // **What version of the product are you using? On what operating system?** // Closure Compiler Version: 964, Built on: 2011/04/05 14:31 on GNU/Linux. // // **Please provide any additional information below.** // // public void testDuplicateLocalVarDecl() throws Exception {
1,978
70
1,968
test/com/google/javascript/jscomp/LooseTypeCheckTest.java
test
```markdown ## Issue-ID: Closure-433 ## Issue-Title: unexpected typed coverage of less than 100% ## Issue-Description: **What steps will reproduce the problem?** 1. Create JavaScript file: /\*global window\*/ /\*jslint sub: true\*/ /\*\* \* @constructor \* @param {!Element} element \*/ function Example(element) { /\*\* \* @param {!string} ns \* @param {!string} name \* @return {undefined} \*/ this.appendElement = function appendElement(ns, name) { var e = element.ownerDocument.createElementNS(ns, name); element.appendChild(e); }; } window["Example"] = Example; 2. compile it: java -jar compiler.jar --jscomp\_error checkTypes --summary\_detail\_level 3 --js v.js --js\_output\_file compiled.js 3. observe the outcome: 0 error(s), 0 warning(s), 73.7% typed **What is the expected output? What do you see instead?** This was expected: 0 error(s), 0 warning(s), 100% typed **What version of the product are you using? On what operating system?** Closure Compiler Version: 964, Built on: 2011/04/05 14:31 on GNU/Linux. **Please provide any additional information below.** ``` You are a professional Java test case writer, please create a test case named `testDuplicateLocalVarDecl` for the issue `Closure-433`, utilizing the provided issue report information and the following function signature. ```java public void testDuplicateLocalVarDecl() throws Exception { ```
1,968
[ "com.google.javascript.jscomp.TypedScopeCreator" ]
cc0f9880d46ec30a413a7a2d03422c97d69462fec5790e14c92c75732ef741f7
public void testDuplicateLocalVarDecl() throws Exception
// You are a professional Java test case writer, please create a test case named `testDuplicateLocalVarDecl` for the issue `Closure-433`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-433 // // ## Issue-Title: // unexpected typed coverage of less than 100% // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Create JavaScript file: // /\*global window\*/ // /\*jslint sub: true\*/ // /\*\* // \* @constructor // \* @param {!Element} element // \*/ // function Example(element) { // /\*\* // \* @param {!string} ns // \* @param {!string} name // \* @return {undefined} // \*/ // this.appendElement = function appendElement(ns, name) { // var e = element.ownerDocument.createElementNS(ns, name); // element.appendChild(e); // }; // } // window["Example"] = Example; // 2. compile it: // java -jar compiler.jar --jscomp\_error checkTypes --summary\_detail\_level 3 --js v.js --js\_output\_file compiled.js // 3. observe the outcome: // 0 error(s), 0 warning(s), 73.7% typed // // **What is the expected output? What do you see instead?** // This was expected: // 0 error(s), 0 warning(s), 100% typed // // **What version of the product are you using? On what operating system?** // Closure Compiler Version: 964, Built on: 2011/04/05 14:31 on GNU/Linux. // // **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.CheckLevel; 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}. * * This is a temporary fork of the TypeCheckTest for the experimental * "looseTypes" option. These tests should be be folded into TypeCheckTest * or removed along with the looseTypes option. * */ public class LooseTypeCheckTest extends CompilerTypeTestCase { @Override public CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.looseTypes = true; return options; } 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} */var x;x=null;x=10;", "assignment\n" + "found : number\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16a() throws Exception { testTypes("/**@type {Number|null} */var x='';", "initializing variable\n" + "found : string\n" + "required: (Number|null|undefined)"); } public void testTypeCheck16b() 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|undefined}\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|undefined)\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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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 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 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", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration6() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo;", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration7() throws Exception { testFunctionType( "/** @constructor */ function f() {} " + "/** @type {Function} */ f.prototype.foo = function() {};", "(new f).foo", createOptionalType(createNullableType(U2U_CONSTRUCTOR_TYPE)) .toString()); } public void testStubFunctionDeclaration8() throws Exception { testFunctionType( "/** @type {Function} */ var f = function() {}; ", "f", createOptionalType(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"); } // 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|undefined)"); } 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|undefined)>\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 (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 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 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 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("/** @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;"); } 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|undefined)\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|undefined) */" + "var b = a ? null : a;"); } public void testHookRestrictsType3() throws Exception { testTypes("/** @type {String} */" + "var a;" + "/** @type (null|undefined) */" + "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|null} */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|null} */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 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 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|undefined)\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|undefined)\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)"); } 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 testControlFlowRestrictsType1a() throws Exception { testTypes("/** @return {String?} */ function f() { return null; }\n" + "/** @type {String?} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null|undefined) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1b() throws Exception { testTypes("/** @return {!String|null} */ function f() { return null; }\n" + "/** @type {!String|null} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type (null) */ var c = null;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } public void testControlFlowRestrictsType1c() throws Exception { testTypes("/** @return {!String|undefined} */\n" + "function f() { return undefined; }\n" + "/** @type {!String|undefined} */ var a = f();\n" + "/** @type String */ var b = new String('foo');\n" + "/** @type undefined */ var c = undefined;\n" + "if (a) {\n" + " b = a;\n" + "} else {\n" + " c = a;\n" + "}"); } 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 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|undefined)"); } 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|undefined)"); } 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|undefined)"); } 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 anonymous functions 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();", "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 { // 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 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|undefined)\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(createUnionType(OBJECT_TYPE, NULL_TYPE), VOID_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 4; };" + "/** @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 { 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() {};", "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 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 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() { };", // "cannot reference an interface ouside 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 testWarnDataPropertyOnInterface2() throws Exception { // testTypes("/** @interface */ function T() {};\n" + // "/** @type {number} */T.prototype.x;", // "interface members can only be plain functions"); //} 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|undefined)"); } // 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|undefined)\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|undefined)"); } 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|undefined)"); } 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 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 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.createOptionalType( 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() { 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); } 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 { 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(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); } 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 testIssue301() throws Exception { testTypes( "Array.indexOf = function() {};" + "var s = 'hello';" + "alert(s.toLowerCase.indexOf('1'));", "Property indexOf never defined on String.prototype.toLowerCase"); }
com.google.javascript.jscomp.TypeCheckTest::testIssue301
test/com/google/javascript/jscomp/TypeCheckTest.java
4,959
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue301
/* * 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 = "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\"; }", "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" + "}"); // would like this to be an error. } 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 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 { 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 { /** 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"); } /** * 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 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 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", "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 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());", "Parse error. 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" + "/** @implements {Disposable}\n * @interface */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() {}", "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 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 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 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 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 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"); } /** * 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));", "Parse error. 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();", "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 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() {};", "Parse error. 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() {};", "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 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 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 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 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) {}", "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 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}));", "Parse error. 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}));", "Parse error. 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( "Parse error. expected closing }", "Parse error. 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();"); } 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 { 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 `testIssue301` for the issue `Closure-301`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-301 // // ## Issue-Title: // .indexOf fails to produce missing property warning // // ## Issue-Description: // The following code compiled with VERBOSE warnings or with the missingProperties check enabled fails to produce a warning or error: // // var s = new String("hello"); // alert(s.toLowerCase.indexOf("l")); // // However, other string functions do properly produce the warning: // // var s = new String("hello"); // alert(s.toLowerCase.substr(0, 1)); // // public void testIssue301() throws Exception {
4,959
82
4,953
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-301 ## Issue-Title: .indexOf fails to produce missing property warning ## Issue-Description: The following code compiled with VERBOSE warnings or with the missingProperties check enabled fails to produce a warning or error: var s = new String("hello"); alert(s.toLowerCase.indexOf("l")); However, other string functions do properly produce the warning: var s = new String("hello"); alert(s.toLowerCase.substr(0, 1)); ``` You are a professional Java test case writer, please create a test case named `testIssue301` for the issue `Closure-301`, utilizing the provided issue report information and the following function signature. ```java public void testIssue301() throws Exception { ```
4,953
[ "com.google.javascript.rhino.jstype.JSType" ]
cc3e6d8c7bbd4f82a926ffc07365debb13126a924c10d1d06bb63138a247ccdb
public void testIssue301() throws Exception
// You are a professional Java test case writer, please create a test case named `testIssue301` for the issue `Closure-301`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-301 // // ## Issue-Title: // .indexOf fails to produce missing property warning // // ## Issue-Description: // The following code compiled with VERBOSE warnings or with the missingProperties check enabled fails to produce a warning or error: // // var s = new String("hello"); // alert(s.toLowerCase.indexOf("l")); // // However, other string functions do properly produce the warning: // // var s = new String("hello"); // alert(s.toLowerCase.substr(0, 1)); // //
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 = "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\"; }", "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" + "}"); // would like this to be an error. } 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 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 { 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 { /** 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"); } /** * 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 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 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", "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 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());", "Parse error. 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" + "/** @implements {Disposable}\n * @interface */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() {}", "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 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 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 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 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 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"); } /** * 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));", "Parse error. 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();", "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 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() {};", "Parse error. 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() {};", "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 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 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 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 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) {}", "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 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}));", "Parse error. 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}));", "Parse error. 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( "Parse error. expected closing }", "Parse error. 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();"); } 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 { 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 testCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); assertEquals(null, DataUtil.getCharsetFromContentType("text/html;charset=Unknown")); }
org.jsoup.helper.DataUtilTest::testCharset
src/test/java/org/jsoup/helper/DataUtilTest.java
20
src/test/java/org/jsoup/helper/DataUtilTest.java
testCharset
package org.jsoup.helper; import static org.junit.Assert.assertEquals; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.charset.Charset; public class DataUtilTest { @Test public void testCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); assertEquals(null, DataUtil.getCharsetFromContentType("text/html;charset=Unknown")); } @Test public void testQuotedCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"UTF-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=\"Unsupported\"")); } @Test public void discardsSpuriousByteOrderMark() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, "UTF-8", "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); } }
// You are a professional Java test case writer, please create a test case named `testCharset` for the issue `Jsoup-215`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-215 // // ## Issue-Title: // Invalid HTTP-Response header leads to exception // // ## Issue-Description: // In particular case a HTTP-Webpage responses with a invalid HTTP-Charset field (delivered UFT8 instead of UTF8). // // This leads to an UnsupportedCharsetException in org.jsoup.helper.DataUtil at around Line 93(?) where : // // // // ``` // Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); // docData = Charset.forName(charsetName).decode(byteData).toString(); // ``` // // I fixed it by wrapping a try catch statement around these two lines such that: // // // // ``` // try{ // Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); // docData = Charset.forName(charsetName).decode(byteData).toString(); // } catch(UnsupportedCharsetException e){ // return parseByteData(byteData,(String)null,baseUri,parser); // } // ``` // // It now falls back to the none charset argument assigned clause, and tries to detect the character set via HTML. // // // // @Test public void testCharset() {
20
27
12
src/test/java/org/jsoup/helper/DataUtilTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-215 ## Issue-Title: Invalid HTTP-Response header leads to exception ## Issue-Description: In particular case a HTTP-Webpage responses with a invalid HTTP-Charset field (delivered UFT8 instead of UTF8). This leads to an UnsupportedCharsetException in org.jsoup.helper.DataUtil at around Line 93(?) where : ``` Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); ``` I fixed it by wrapping a try catch statement around these two lines such that: ``` try{ Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } catch(UnsupportedCharsetException e){ return parseByteData(byteData,(String)null,baseUri,parser); } ``` It now falls back to the none charset argument assigned clause, and tries to detect the character set via HTML. ``` You are a professional Java test case writer, please create a test case named `testCharset` for the issue `Jsoup-215`, utilizing the provided issue report information and the following function signature. ```java @Test public void testCharset() { ```
12
[ "org.jsoup.helper.DataUtil" ]
cc618dae9ddf90773344b171ba3c9c5d4ac9b9e4fad0841a5f14bcafb7950d29
@Test public void testCharset()
// You are a professional Java test case writer, please create a test case named `testCharset` for the issue `Jsoup-215`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-215 // // ## Issue-Title: // Invalid HTTP-Response header leads to exception // // ## Issue-Description: // In particular case a HTTP-Webpage responses with a invalid HTTP-Charset field (delivered UFT8 instead of UTF8). // // This leads to an UnsupportedCharsetException in org.jsoup.helper.DataUtil at around Line 93(?) where : // // // // ``` // Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); // docData = Charset.forName(charsetName).decode(byteData).toString(); // ``` // // I fixed it by wrapping a try catch statement around these two lines such that: // // // // ``` // try{ // Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); // docData = Charset.forName(charsetName).decode(byteData).toString(); // } catch(UnsupportedCharsetException e){ // return parseByteData(byteData,(String)null,baseUri,parser); // } // ``` // // It now falls back to the none charset argument assigned clause, and tries to detect the character set via HTML. // // // //
Jsoup
package org.jsoup.helper; import static org.junit.Assert.assertEquals; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.charset.Charset; public class DataUtilTest { @Test public void testCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); assertEquals(null, DataUtil.getCharsetFromContentType("text/html;charset=Unknown")); } @Test public void testQuotedCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"UTF-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=\"Unsupported\"")); } @Test public void discardsSpuriousByteOrderMark() { String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>"; ByteBuffer buffer = Charset.forName("UTF-8").encode(html); Document doc = DataUtil.parseByteData(buffer, "UTF-8", "http://foo.com/", Parser.htmlParser()); assertEquals("One", doc.head().text()); } }
public void testWithDeserializationProblemHandler() throws Exception { final ObjectMapper mapper = new ObjectMapper() .enableDefaultTyping(); mapper.addHandler(new DeserializationProblemHandler() { @Override public JavaType handleUnknownTypeId(DeserializationContext ctxt, JavaType baseType, String subTypeId, TypeIdResolver idResolver, String failureMsg) throws IOException { // System.out.println("Print out a warning here"); return ctxt.constructType(Void.class); } }); GenericContent processableContent = mapper.readValue(JSON, GenericContent.class); assertNotNull(processableContent.getInnerObjects()); assertEquals(2, processableContent.getInnerObjects().size()); }
com.fasterxml.jackson.databind.deser.filter.ProblemHandlerUnknownTypeId2221Test::testWithDeserializationProblemHandler
src/test/java/com/fasterxml/jackson/databind/deser/filter/ProblemHandlerUnknownTypeId2221Test.java
97
src/test/java/com/fasterxml/jackson/databind/deser/filter/ProblemHandlerUnknownTypeId2221Test.java
testWithDeserializationProblemHandler
package com.fasterxml.jackson.databind.deser.filter; import java.io.*; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; // for [databind#2221] public class ProblemHandlerUnknownTypeId2221Test extends BaseMapTest { @SuppressWarnings("rawtypes") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "_class") @JsonInclude(Include.NON_EMPTY) static class GenericContent { private Collection innerObjects; public Collection getInnerObjects() { return innerObjects; } public void setInnerObjects(Collection innerObjects) { this.innerObjects = innerObjects; } } static class DummyContent { private String aField; public DummyContent() { super(); } public DummyContent(String aField) { super(); this.aField = aField; } public String getaField() { return aField; } public void setaField(String aField) { this.aField = aField; } @Override public String toString() { return "DummyContent [aField=" + aField + "]"; } } private final static String CLASS_GENERIC_CONTENT = GenericContent.class.getName(); private final static String CLASS_DUMMY_CONTENT = DummyContent.class.getName(); private final static String JSON = aposToQuotes( "{\n" + " \"_class\":\""+CLASS_GENERIC_CONTENT+"\",\n" + " \"innerObjects\":\n" + " [\n" + " \"java.util.ArrayList\",\n" + " [\n" + " [\n" + " \""+CLASS_DUMMY_CONTENT+"\",\n" + " {\n" + " \"aField\":\"some value\"\n" + " }\n" + " ],\n" + " [\n" + " \"com.fasterxml.jackson.databind.deser.NoSuchClass$AnInventedClassBeingNotOnTheClasspath\",\n" + " {\n" + " \"aField\":\"some value\"\n" + " }\n" + " ]\n" + " ]\n" + " ]\n" + " }" ); public void testWithDeserializationProblemHandler() throws Exception { final ObjectMapper mapper = new ObjectMapper() .enableDefaultTyping(); mapper.addHandler(new DeserializationProblemHandler() { @Override public JavaType handleUnknownTypeId(DeserializationContext ctxt, JavaType baseType, String subTypeId, TypeIdResolver idResolver, String failureMsg) throws IOException { // System.out.println("Print out a warning here"); return ctxt.constructType(Void.class); } }); GenericContent processableContent = mapper.readValue(JSON, GenericContent.class); assertNotNull(processableContent.getInnerObjects()); assertEquals(2, processableContent.getInnerObjects().size()); } public void testWithDisabledFAIL_ON_INVALID_SUBTYPE() throws Exception { final ObjectMapper mapper = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE) .enableDefaultTyping() ; GenericContent processableContent = mapper.readValue(JSON, GenericContent.class); assertNotNull(processableContent.getInnerObjects()); assertEquals(2, processableContent.getInnerObjects().size()); } }
// You are a professional Java test case writer, please create a test case named `testWithDeserializationProblemHandler` for the issue `JacksonDatabind-2221`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2221 // // ## Issue-Title: // DeserializationProblemHandler.handleUnknownTypeId() returning Void.class, enableDefaultTyping causing NPE // // ## Issue-Description: // Returning Void.class from com.fasterxml.jackson.databind.deser.HandleUnknowTypeIdTest.testDeserializationWithDeserializationProblemHandler().new DeserializationProblemHandler() {...}.handleUnknownTypeId(DeserializationContext, JavaType, String, TypeIdResolver, String) is causing a NPE in jackson 2.9. I'll provide a pull request illustrating the issue in a test. // // // // public void testWithDeserializationProblemHandler() throws Exception {
97
107
84
src/test/java/com/fasterxml/jackson/databind/deser/filter/ProblemHandlerUnknownTypeId2221Test.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-2221 ## Issue-Title: DeserializationProblemHandler.handleUnknownTypeId() returning Void.class, enableDefaultTyping causing NPE ## Issue-Description: Returning Void.class from com.fasterxml.jackson.databind.deser.HandleUnknowTypeIdTest.testDeserializationWithDeserializationProblemHandler().new DeserializationProblemHandler() {...}.handleUnknownTypeId(DeserializationContext, JavaType, String, TypeIdResolver, String) is causing a NPE in jackson 2.9. I'll provide a pull request illustrating the issue in a test. ``` You are a professional Java test case writer, please create a test case named `testWithDeserializationProblemHandler` for the issue `JacksonDatabind-2221`, utilizing the provided issue report information and the following function signature. ```java public void testWithDeserializationProblemHandler() throws Exception { ```
84
[ "com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase" ]
cc6d6bdc2c05fd084102759cc7f456e31f5c00aa22936e3966c385082a2619ab
public void testWithDeserializationProblemHandler() throws Exception
// You are a professional Java test case writer, please create a test case named `testWithDeserializationProblemHandler` for the issue `JacksonDatabind-2221`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-2221 // // ## Issue-Title: // DeserializationProblemHandler.handleUnknownTypeId() returning Void.class, enableDefaultTyping causing NPE // // ## Issue-Description: // Returning Void.class from com.fasterxml.jackson.databind.deser.HandleUnknowTypeIdTest.testDeserializationWithDeserializationProblemHandler().new DeserializationProblemHandler() {...}.handleUnknownTypeId(DeserializationContext, JavaType, String, TypeIdResolver, String) is causing a NPE in jackson 2.9. I'll provide a pull request illustrating the issue in a test. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.deser.filter; import java.io.*; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; // for [databind#2221] public class ProblemHandlerUnknownTypeId2221Test extends BaseMapTest { @SuppressWarnings("rawtypes") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "_class") @JsonInclude(Include.NON_EMPTY) static class GenericContent { private Collection innerObjects; public Collection getInnerObjects() { return innerObjects; } public void setInnerObjects(Collection innerObjects) { this.innerObjects = innerObjects; } } static class DummyContent { private String aField; public DummyContent() { super(); } public DummyContent(String aField) { super(); this.aField = aField; } public String getaField() { return aField; } public void setaField(String aField) { this.aField = aField; } @Override public String toString() { return "DummyContent [aField=" + aField + "]"; } } private final static String CLASS_GENERIC_CONTENT = GenericContent.class.getName(); private final static String CLASS_DUMMY_CONTENT = DummyContent.class.getName(); private final static String JSON = aposToQuotes( "{\n" + " \"_class\":\""+CLASS_GENERIC_CONTENT+"\",\n" + " \"innerObjects\":\n" + " [\n" + " \"java.util.ArrayList\",\n" + " [\n" + " [\n" + " \""+CLASS_DUMMY_CONTENT+"\",\n" + " {\n" + " \"aField\":\"some value\"\n" + " }\n" + " ],\n" + " [\n" + " \"com.fasterxml.jackson.databind.deser.NoSuchClass$AnInventedClassBeingNotOnTheClasspath\",\n" + " {\n" + " \"aField\":\"some value\"\n" + " }\n" + " ]\n" + " ]\n" + " ]\n" + " }" ); public void testWithDeserializationProblemHandler() throws Exception { final ObjectMapper mapper = new ObjectMapper() .enableDefaultTyping(); mapper.addHandler(new DeserializationProblemHandler() { @Override public JavaType handleUnknownTypeId(DeserializationContext ctxt, JavaType baseType, String subTypeId, TypeIdResolver idResolver, String failureMsg) throws IOException { // System.out.println("Print out a warning here"); return ctxt.constructType(Void.class); } }); GenericContent processableContent = mapper.readValue(JSON, GenericContent.class); assertNotNull(processableContent.getInnerObjects()); assertEquals(2, processableContent.getInnerObjects().size()); } public void testWithDisabledFAIL_ON_INVALID_SUBTYPE() throws Exception { final ObjectMapper mapper = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE) .enableDefaultTyping() ; GenericContent processableContent = mapper.readValue(JSON, GenericContent.class); assertNotNull(processableContent.getInnerObjects()); assertEquals(2, processableContent.getInnerObjects().size()); } }
public void testIgnoreGetterNotSetter1595() throws Exception { ObjectMapper mapper = new ObjectMapper(); Simple1595 config = new Simple1595(); config.setId(123); config.setName("jack"); String json = mapper.writeValueAsString(config); assertEquals(aposToQuotes("{'id':123}"), json); Simple1595 des = mapper.readValue(aposToQuotes("{'id':123,'name':'jack'}"), Simple1595.class); assertEquals("jack", des.getName()); }
com.fasterxml.jackson.databind.filter.IgnorePropertyOnDeserTest::testIgnoreGetterNotSetter1595
src/test/java/com/fasterxml/jackson/databind/filter/IgnorePropertyOnDeserTest.java
89
src/test/java/com/fasterxml/jackson/databind/filter/IgnorePropertyOnDeserTest.java
testIgnoreGetterNotSetter1595
package com.fasterxml.jackson.databind.filter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; public class IgnorePropertyOnDeserTest extends BaseMapTest { // [databind#1217] static class IgnoreObject { public int x = 1; public int y = 2; } final static class TestIgnoreObject { @JsonIgnoreProperties({ "x" }) public IgnoreObject obj; @JsonIgnoreProperties({ "y" }) public IgnoreObject obj2; } // [databind#1595] @JsonIgnoreProperties(value = {"name"}, allowSetters = true) @JsonPropertyOrder(alphabetic=true) static class Simple1595 { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } /* /**************************************************************** /* Unit tests /**************************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); // [databind#1217] public void testIgnoreOnProperty1217() throws Exception { TestIgnoreObject result = MAPPER.readValue( aposToQuotes("{'obj':{'x': 10, 'y': 20}, 'obj2':{'x': 10, 'y': 20}}"), TestIgnoreObject.class); assertEquals(20, result.obj.y); assertEquals(10, result.obj2.x); assertEquals(1, result.obj.x); assertEquals(2, result.obj2.y); TestIgnoreObject result1 = MAPPER.readValue( aposToQuotes("{'obj':{'x': 20, 'y': 30}, 'obj2':{'x': 20, 'y': 40}}"), TestIgnoreObject.class); assertEquals(1, result1.obj.x); assertEquals(30, result1.obj.y); assertEquals(20, result1.obj2.x); assertEquals(2, result1.obj2.y); } public void testIgnoreViaConfigOverride1217() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.configOverride(Point.class) .setIgnorals(JsonIgnoreProperties.Value.forIgnoredProperties("y")); Point p = mapper.readValue(aposToQuotes("{'x':1,'y':2}"), Point.class); // bind 'x', but ignore 'y' assertEquals(1, p.x); assertEquals(0, p.y); } // [databind#1595] public void testIgnoreGetterNotSetter1595() throws Exception { ObjectMapper mapper = new ObjectMapper(); Simple1595 config = new Simple1595(); config.setId(123); config.setName("jack"); String json = mapper.writeValueAsString(config); assertEquals(aposToQuotes("{'id':123}"), json); Simple1595 des = mapper.readValue(aposToQuotes("{'id':123,'name':'jack'}"), Simple1595.class); assertEquals("jack", des.getName()); } }
// You are a professional Java test case writer, please create a test case named `testIgnoreGetterNotSetter1595` for the issue `JacksonDatabind-1595`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1595 // // ## Issue-Title: // JsonIgnoreProperties.allowSetters is not working in Jackson 2.8 // // ## Issue-Description: // // ``` // @JsonIgnoreProperties(value = { "password" }, ignoreUnknown = true, allowSetters = true) // public class JsonTest { // private String username; // private String password; // // public JsonTest() { // super(); // // TODO Auto-generated constructor stub // } // // public JsonTest(String username, String password) { // super(); // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public static void main(String[] args) { // ObjectMapper mapper = new ObjectMapper(); // // JsonTest json = new JsonTest("user", "password"); // // try { // System.out.println(mapper.writeValueAsString(json)); // } catch (JsonProcessingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // String jsonString = "{ \"username\":\"username\",\"password\":\"password\" }"; // try { // json = mapper.readValue(jsonString, JsonTest.class); // // System.out.println(json.getPassword()); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } // } // // ``` // // the version is 2.8.7. // // the password cannot deserialize. // // the output is: // // {"username":"user"} // // null // // // // public void testIgnoreGetterNotSetter1595() throws Exception {
89
// [databind#1595]
82
79
src/test/java/com/fasterxml/jackson/databind/filter/IgnorePropertyOnDeserTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1595 ## Issue-Title: JsonIgnoreProperties.allowSetters is not working in Jackson 2.8 ## Issue-Description: ``` @JsonIgnoreProperties(value = { "password" }, ignoreUnknown = true, allowSetters = true) public class JsonTest { private String username; private String password; public JsonTest() { super(); // TODO Auto-generated constructor stub } public JsonTest(String username, String password) { super(); this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); JsonTest json = new JsonTest("user", "password"); try { System.out.println(mapper.writeValueAsString(json)); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } String jsonString = "{ \"username\":\"username\",\"password\":\"password\" }"; try { json = mapper.readValue(jsonString, JsonTest.class); System.out.println(json.getPassword()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` the version is 2.8.7. the password cannot deserialize. the output is: {"username":"user"} null ``` You are a professional Java test case writer, please create a test case named `testIgnoreGetterNotSetter1595` for the issue `JacksonDatabind-1595`, utilizing the provided issue report information and the following function signature. ```java public void testIgnoreGetterNotSetter1595() throws Exception { ```
79
[ "com.fasterxml.jackson.databind.deser.BeanDeserializerFactory" ]
cc7a9b3ff29da22edd6bc4efd38bac5de505774421bc5049f4d6a3d461412c02
public void testIgnoreGetterNotSetter1595() throws Exception
// You are a professional Java test case writer, please create a test case named `testIgnoreGetterNotSetter1595` for the issue `JacksonDatabind-1595`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1595 // // ## Issue-Title: // JsonIgnoreProperties.allowSetters is not working in Jackson 2.8 // // ## Issue-Description: // // ``` // @JsonIgnoreProperties(value = { "password" }, ignoreUnknown = true, allowSetters = true) // public class JsonTest { // private String username; // private String password; // // public JsonTest() { // super(); // // TODO Auto-generated constructor stub // } // // public JsonTest(String username, String password) { // super(); // this.username = username; // this.password = password; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public static void main(String[] args) { // ObjectMapper mapper = new ObjectMapper(); // // JsonTest json = new JsonTest("user", "password"); // // try { // System.out.println(mapper.writeValueAsString(json)); // } catch (JsonProcessingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // String jsonString = "{ \"username\":\"username\",\"password\":\"password\" }"; // try { // json = mapper.readValue(jsonString, JsonTest.class); // // System.out.println(json.getPassword()); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } // } // // ``` // // the version is 2.8.7. // // the password cannot deserialize. // // the output is: // // {"username":"user"} // // null // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.filter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; public class IgnorePropertyOnDeserTest extends BaseMapTest { // [databind#1217] static class IgnoreObject { public int x = 1; public int y = 2; } final static class TestIgnoreObject { @JsonIgnoreProperties({ "x" }) public IgnoreObject obj; @JsonIgnoreProperties({ "y" }) public IgnoreObject obj2; } // [databind#1595] @JsonIgnoreProperties(value = {"name"}, allowSetters = true) @JsonPropertyOrder(alphabetic=true) static class Simple1595 { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } /* /**************************************************************** /* Unit tests /**************************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); // [databind#1217] public void testIgnoreOnProperty1217() throws Exception { TestIgnoreObject result = MAPPER.readValue( aposToQuotes("{'obj':{'x': 10, 'y': 20}, 'obj2':{'x': 10, 'y': 20}}"), TestIgnoreObject.class); assertEquals(20, result.obj.y); assertEquals(10, result.obj2.x); assertEquals(1, result.obj.x); assertEquals(2, result.obj2.y); TestIgnoreObject result1 = MAPPER.readValue( aposToQuotes("{'obj':{'x': 20, 'y': 30}, 'obj2':{'x': 20, 'y': 40}}"), TestIgnoreObject.class); assertEquals(1, result1.obj.x); assertEquals(30, result1.obj.y); assertEquals(20, result1.obj2.x); assertEquals(2, result1.obj2.y); } public void testIgnoreViaConfigOverride1217() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.configOverride(Point.class) .setIgnorals(JsonIgnoreProperties.Value.forIgnoredProperties("y")); Point p = mapper.readValue(aposToQuotes("{'x':1,'y':2}"), Point.class); // bind 'x', but ignore 'y' assertEquals(1, p.x); assertEquals(0, p.y); } // [databind#1595] public void testIgnoreGetterNotSetter1595() throws Exception { ObjectMapper mapper = new ObjectMapper(); Simple1595 config = new Simple1595(); config.setId(123); config.setName("jack"); String json = mapper.writeValueAsString(config); assertEquals(aposToQuotes("{'id':123}"), json); Simple1595 des = mapper.readValue(aposToQuotes("{'id':123,'name':'jack'}"), Simple1595.class); assertEquals("jack", des.getName()); } }
public void testIssue787() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); WarningLevel warnings = WarningLevel.DEFAULT; warnings.setOptionsForWarningLevel(options); String code = "" + "function some_function() {\n" + " var fn1;\n" + " var fn2;\n" + "\n" + " if (any_expression) {\n" + " fn2 = external_ref;\n" + " fn1 = function (content) {\n" + " return fn2();\n" + " }\n" + " }\n" + "\n" + " return {\n" + " method1: function () {\n" + " if (fn1) fn1();\n" + " return true;\n" + " },\n" + " method2: function () {\n" + " return false;\n" + " }\n" + " }\n" + "}"; String result = "" + "function some_function() {\n" + " var a, b;\n" + " any_expression && (b = external_ref, a = function() {\n" + " return b()\n" + " });\n" + " return{method1:function() {\n" + " a && a();\n" + " return !0\n" + " }, method2:function() {\n" + " return !1\n" + " }}\n" + "}\n" + ""; test(options, code, result); }
com.google.javascript.jscomp.IntegrationTest::testIssue787
test/com/google/javascript/jscomp/IntegrationTest.java
2,262
test/com/google/javascript/jscomp/IntegrationTest.java
testIssue787
/* * 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.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; 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; /** * Tests for {@link PassFactory}. * * @author [email protected] (Nick Santos) */ public class IntegrationTest extends IntegrationTestCase { 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() {};"; 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" + " function Bar() {}\n" + " Foo.prototype.a = function(a, b) {};\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 = {}; 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 testNameAnonymousFunctionsWithVarRemoval() { CompilerOptions options = createCompilerOptions(); options.setRemoveUnusedVariables(CompilerOptions.Reach.LOCAL_ONLY); options.setInlineVariables(true); String code = "var f = function longName() {}; var g = function() {};" + "function longerName() {} var i = longerName;"; test(options, code, "var f = function() {}; var g = function() {}; " + "var i = function() {};"); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.MAPPED; test(options, code, "var f = function longName() {}; var g = function $() {};" + "var i = function longerName(){};"); assertNotNull(lastCompiler.getResult().namedAnonFunctionMap); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED; test(options, code, "var f = function longName() {}; var g = function $g$() {};" + "var i = function longerName(){};"); 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: for(;true;) { break longLabel; }"; String expected = "a: for(;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 = true; 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 older versions of JS. " + "If you are targeting newer versions of JS, " + "set the appropriate language_in option. " + "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 testIssue724() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); String code = "isFunction = function(functionToCheck) {" + " var getType = {};" + " return functionToCheck && " + " getType.toString.apply(functionToCheck) === " + " '[object Function]';" + "};"; String result = "isFunction=function(a){var b={};" + "return a&&\"[object Function]\"===b.b.a(a)}"; test(options, code, result); } public void testIssue730() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); String code = "/** @constructor */function A() {this.foo = 0; Object.seal(this);}\n" + "/** @constructor */function B() {this.a = new A();}\n" + "B.prototype.dostuff = function() {this.a.foo++;alert('hi');}\n" + "new B().dostuff();\n"; test(options, code, "function a(){this.b=0;Object.seal(this)}" + "(new function(){this.a=new a}).a.b++;" + "alert(\"hi\")"); options.removeUnusedClassProperties = true; // This is still a problem when removeUnusedClassProperties are enabled. test(options, code, "function a(){Object.seal(this)}" + "(new function(){this.a=new a}).a.b++;" + "alert(\"hi\")"); } 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" + "}", // This should eventually get inlined completely. "function f(a) { a += 'x'; return a += 'y'; }"); } 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 testIssue772() throws Exception { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.checkTypes = true; test( options, "/** @const */ var a = {};" + "/** @const */ a.b = {};" + "/** @const */ a.b.c = {};" + "goog.scope(function() {" + " var b = a.b;" + " var c = b.c;" + " /** @typedef {string} */" + " c.MyType;" + " /** @param {c.MyType} x The variable. */" + " c.myFunc = function(x) {};" + "});", "/** @const */ var a = {};" + "/** @const */ a.b = {};" + "/** @const */ a.b.c = {};" + "a.b.c.MyType;" + "a.b.c.myFunc = function(x) {};"); } 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='1234567'.split('')"); options = createCompilerOptions(); options.foldConstants = true; options.computeFunctionSideEffects = false; options.removeUnusedVars = true; // If we do splits too early, it would add a side-effect 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 run-time 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); test(options, "/** @suppress{es5Strict} */\n" + "function f() { var arguments; }", "function f() {}"); } 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() {}"); } 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 testDependencySorting() throws Exception { CompilerOptions options = createCompilerOptions(); options.setDependencyOptions( new DependencyOptions() .setDependencySorting(true)); test( options, new String[] { "goog.require('x');", "goog.provide('x');", }, new String[] { "goog.provide('x');", "goog.require('x');", // For complicated reasons involving modules, // the compiler creates a synthetic source file. "", }); } 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); } public void testInlineProperties() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); level.setTypeBasedOptimizationOptions(options); String code = "" + "var ns = {};\n" + "/** @constructor */\n" + "ns.C = function () {this.someProperty = 1}\n" + "alert(new ns.C().someProperty + new ns.C().someProperty);\n"; assertTrue(options.inlineProperties); assertTrue(options.collapseProperties); // CollapseProperties used to prevent inlining this property. test(options, code, "alert(2);"); } public void testCheckConstants1() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); WarningLevel warnings = WarningLevel.QUIET; warnings.setOptionsForWarningLevel(options); String code = "" + "var foo; foo();\n" + "/** @const */\n" + "var x = 1; foo(); x = 2;\n"; test(options, code, code); } public void testCheckConstants2() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); WarningLevel warnings = WarningLevel.DEFAULT; warnings.setOptionsForWarningLevel(options); String code = "" + "var foo;\n" + "/** @const */\n" + "var x = 1; foo(); x = 2;\n"; test(options, code, ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testIssue787() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); WarningLevel warnings = WarningLevel.DEFAULT; warnings.setOptionsForWarningLevel(options); String code = "" + "function some_function() {\n" + " var fn1;\n" + " var fn2;\n" + "\n" + " if (any_expression) {\n" + " fn2 = external_ref;\n" + " fn1 = function (content) {\n" + " return fn2();\n" + " }\n" + " }\n" + "\n" + " return {\n" + " method1: function () {\n" + " if (fn1) fn1();\n" + " return true;\n" + " },\n" + " method2: function () {\n" + " return false;\n" + " }\n" + " }\n" + "}"; String result = "" + "function some_function() {\n" + " var a, b;\n" + " any_expression && (b = external_ref, a = function() {\n" + " return b()\n" + " });\n" + " return{method1:function() {\n" + " a && a();\n" + " return !0\n" + " }, method2:function() {\n" + " return !1\n" + " }}\n" + "}\n" + ""; test(options, code, result); } public void testManyAdds() {} // Defects4J: flaky method // public void testManyAdds() { // CompilerOptions options = createCompilerOptions(); // CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; // level.setOptionsForCompilationLevel(options); // WarningLevel warnings = WarningLevel.VERBOSE; // warnings.setOptionsForWarningLevel(options); // // int numAdds = 5000; // StringBuilder original = new StringBuilder("var x = 0"); // for (int i = 0; i < numAdds; i++) { // original.append(" + 1"); // } // original.append(";"); // test(options, original.toString(), "var x = " + numAdds + ";"); // } /** Creates a CompilerOptions object with google coding conventions. */ @Override protected 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 `testIssue787` for the issue `Closure-787`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-787 // // ## Issue-Title: // true/false are not always replaced for !0/!1 // // ## Issue-Description: // **What steps will reproduce the problem?** // // function some\_function() { // var fn1; // var fn2; // // if (any\_expression) { // fn2 = external\_ref; // fn1 = function (content) { // return fn2(); // } // } // // return { // method1: function () { // if (fn1) fn1(); // return true; // }, // method2: function () { // return false; // } // } // } // // **What is the expected output? What do you see instead?** // // We expect that true/false will be replaced for !0/!1, but it doesn't happend. // // function some\_function() { // var a, b; // any\_expression && (b = external\_ref, a = function () { // return b() // }); // return { // method1: function () { // a && a(); // return true // }, // method2: function () { // return false // } // } // }; // // **What version of the product are you using? On what operating system?** // // This is output for latest official build. // I also got the same output for 20120430, 20120305. But 20111117 is OK. // // **Please provide any additional information below.** // // Here is just one of example. I found too many non-replaced true/false in compiler output. Replacement non-replaced true/false to !1/!0 in conpiler output saves 1-2 kb for 850 kb js file. // // public void testIssue787() {
2,262
13
2,216
test/com/google/javascript/jscomp/IntegrationTest.java
test
```markdown ## Issue-ID: Closure-787 ## Issue-Title: true/false are not always replaced for !0/!1 ## Issue-Description: **What steps will reproduce the problem?** function some\_function() { var fn1; var fn2; if (any\_expression) { fn2 = external\_ref; fn1 = function (content) { return fn2(); } } return { method1: function () { if (fn1) fn1(); return true; }, method2: function () { return false; } } } **What is the expected output? What do you see instead?** We expect that true/false will be replaced for !0/!1, but it doesn't happend. function some\_function() { var a, b; any\_expression && (b = external\_ref, a = function () { return b() }); return { method1: function () { a && a(); return true }, method2: function () { return false } } }; **What version of the product are you using? On what operating system?** This is output for latest official build. I also got the same output for 20120430, 20120305. But 20111117 is OK. **Please provide any additional information below.** Here is just one of example. I found too many non-replaced true/false in compiler output. Replacement non-replaced true/false to !1/!0 in conpiler output saves 1-2 kb for 850 kb js file. ``` You are a professional Java test case writer, please create a test case named `testIssue787` for the issue `Closure-787`, utilizing the provided issue report information and the following function signature. ```java public void testIssue787() { ```
2,216
[ "com.google.javascript.jscomp.PeepholeOptimizationsPass" ]
cd636ac8677e221ec6a8dffe5bd314e9509094dc60927a3181cb25670e332bf9
public void testIssue787()
// You are a professional Java test case writer, please create a test case named `testIssue787` for the issue `Closure-787`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-787 // // ## Issue-Title: // true/false are not always replaced for !0/!1 // // ## Issue-Description: // **What steps will reproduce the problem?** // // function some\_function() { // var fn1; // var fn2; // // if (any\_expression) { // fn2 = external\_ref; // fn1 = function (content) { // return fn2(); // } // } // // return { // method1: function () { // if (fn1) fn1(); // return true; // }, // method2: function () { // return false; // } // } // } // // **What is the expected output? What do you see instead?** // // We expect that true/false will be replaced for !0/!1, but it doesn't happend. // // function some\_function() { // var a, b; // any\_expression && (b = external\_ref, a = function () { // return b() // }); // return { // method1: function () { // a && a(); // return true // }, // method2: function () { // return false // } // } // }; // // **What version of the product are you using? On what operating system?** // // This is output for latest official build. // I also got the same output for 20120430, 20120305. But 20111117 is OK. // // **Please provide any additional information below.** // // Here is just one of example. I found too many non-replaced true/false in compiler output. Replacement non-replaced true/false to !1/!0 in conpiler output saves 1-2 kb for 850 kb js file. // //
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.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; 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; /** * Tests for {@link PassFactory}. * * @author [email protected] (Nick Santos) */ public class IntegrationTest extends IntegrationTestCase { 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() {};"; 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" + " function Bar() {}\n" + " Foo.prototype.a = function(a, b) {};\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 = {}; 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 testNameAnonymousFunctionsWithVarRemoval() { CompilerOptions options = createCompilerOptions(); options.setRemoveUnusedVariables(CompilerOptions.Reach.LOCAL_ONLY); options.setInlineVariables(true); String code = "var f = function longName() {}; var g = function() {};" + "function longerName() {} var i = longerName;"; test(options, code, "var f = function() {}; var g = function() {}; " + "var i = function() {};"); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.MAPPED; test(options, code, "var f = function longName() {}; var g = function $() {};" + "var i = function longerName(){};"); assertNotNull(lastCompiler.getResult().namedAnonFunctionMap); options.anonymousFunctionNaming = AnonymousFunctionNamingPolicy.UNMAPPED; test(options, code, "var f = function longName() {}; var g = function $g$() {};" + "var i = function longerName(){};"); 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: for(;true;) { break longLabel; }"; String expected = "a: for(;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 = true; 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 older versions of JS. " + "If you are targeting newer versions of JS, " + "set the appropriate language_in option. " + "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 testIssue724() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); String code = "isFunction = function(functionToCheck) {" + " var getType = {};" + " return functionToCheck && " + " getType.toString.apply(functionToCheck) === " + " '[object Function]';" + "};"; String result = "isFunction=function(a){var b={};" + "return a&&\"[object Function]\"===b.b.a(a)}"; test(options, code, result); } public void testIssue730() { CompilerOptions options = createCompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); String code = "/** @constructor */function A() {this.foo = 0; Object.seal(this);}\n" + "/** @constructor */function B() {this.a = new A();}\n" + "B.prototype.dostuff = function() {this.a.foo++;alert('hi');}\n" + "new B().dostuff();\n"; test(options, code, "function a(){this.b=0;Object.seal(this)}" + "(new function(){this.a=new a}).a.b++;" + "alert(\"hi\")"); options.removeUnusedClassProperties = true; // This is still a problem when removeUnusedClassProperties are enabled. test(options, code, "function a(){Object.seal(this)}" + "(new function(){this.a=new a}).a.b++;" + "alert(\"hi\")"); } 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" + "}", // This should eventually get inlined completely. "function f(a) { a += 'x'; return a += 'y'; }"); } 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 testIssue772() throws Exception { CompilerOptions options = createCompilerOptions(); options.closurePass = true; options.checkTypes = true; test( options, "/** @const */ var a = {};" + "/** @const */ a.b = {};" + "/** @const */ a.b.c = {};" + "goog.scope(function() {" + " var b = a.b;" + " var c = b.c;" + " /** @typedef {string} */" + " c.MyType;" + " /** @param {c.MyType} x The variable. */" + " c.myFunc = function(x) {};" + "});", "/** @const */ var a = {};" + "/** @const */ a.b = {};" + "/** @const */ a.b.c = {};" + "a.b.c.MyType;" + "a.b.c.myFunc = function(x) {};"); } 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='1234567'.split('')"); options = createCompilerOptions(); options.foldConstants = true; options.computeFunctionSideEffects = false; options.removeUnusedVars = true; // If we do splits too early, it would add a side-effect 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 run-time 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); test(options, "/** @suppress{es5Strict} */\n" + "function f() { var arguments; }", "function f() {}"); } 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() {}"); } 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 testDependencySorting() throws Exception { CompilerOptions options = createCompilerOptions(); options.setDependencyOptions( new DependencyOptions() .setDependencySorting(true)); test( options, new String[] { "goog.require('x');", "goog.provide('x');", }, new String[] { "goog.provide('x');", "goog.require('x');", // For complicated reasons involving modules, // the compiler creates a synthetic source file. "", }); } 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); } public void testInlineProperties() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); level.setTypeBasedOptimizationOptions(options); String code = "" + "var ns = {};\n" + "/** @constructor */\n" + "ns.C = function () {this.someProperty = 1}\n" + "alert(new ns.C().someProperty + new ns.C().someProperty);\n"; assertTrue(options.inlineProperties); assertTrue(options.collapseProperties); // CollapseProperties used to prevent inlining this property. test(options, code, "alert(2);"); } public void testCheckConstants1() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); WarningLevel warnings = WarningLevel.QUIET; warnings.setOptionsForWarningLevel(options); String code = "" + "var foo; foo();\n" + "/** @const */\n" + "var x = 1; foo(); x = 2;\n"; test(options, code, code); } public void testCheckConstants2() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); WarningLevel warnings = WarningLevel.DEFAULT; warnings.setOptionsForWarningLevel(options); String code = "" + "var foo;\n" + "/** @const */\n" + "var x = 1; foo(); x = 2;\n"; test(options, code, ConstCheck.CONST_REASSIGNED_VALUE_ERROR); } public void testIssue787() { CompilerOptions options = createCompilerOptions(); CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; level.setOptionsForCompilationLevel(options); WarningLevel warnings = WarningLevel.DEFAULT; warnings.setOptionsForWarningLevel(options); String code = "" + "function some_function() {\n" + " var fn1;\n" + " var fn2;\n" + "\n" + " if (any_expression) {\n" + " fn2 = external_ref;\n" + " fn1 = function (content) {\n" + " return fn2();\n" + " }\n" + " }\n" + "\n" + " return {\n" + " method1: function () {\n" + " if (fn1) fn1();\n" + " return true;\n" + " },\n" + " method2: function () {\n" + " return false;\n" + " }\n" + " }\n" + "}"; String result = "" + "function some_function() {\n" + " var a, b;\n" + " any_expression && (b = external_ref, a = function() {\n" + " return b()\n" + " });\n" + " return{method1:function() {\n" + " a && a();\n" + " return !0\n" + " }, method2:function() {\n" + " return !1\n" + " }}\n" + "}\n" + ""; test(options, code, result); } public void testManyAdds() {} // Defects4J: flaky method // public void testManyAdds() { // CompilerOptions options = createCompilerOptions(); // CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS; // level.setOptionsForCompilationLevel(options); // WarningLevel warnings = WarningLevel.VERBOSE; // warnings.setOptionsForWarningLevel(options); // // int numAdds = 5000; // StringBuilder original = new StringBuilder("var x = 0"); // for (int i = 0; i < numAdds; i++) { // original.append(" + 1"); // } // original.append(";"); // test(options, original.toString(), "var x = " + numAdds + ";"); // } /** Creates a CompilerOptions object with google coding conventions. */ @Override protected CompilerOptions createCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new GoogleCodingConvention()); return options; } }
public void testSimpleNumbers() throws Exception { final StringBuilder sb = new StringBuilder(); MAPPER.acceptJsonFormatVisitor(Numbers.class, new JsonFormatVisitorWrapper.Base() { @Override public JsonObjectFormatVisitor expectObjectFormat(final JavaType type) { return new JsonObjectFormatVisitor.Base(getProvider()) { @Override public void optionalProperty(BeanProperty prop) throws JsonMappingException { sb.append("[optProp ").append(prop.getName()).append("("); JsonSerializer<Object> ser = null; if (prop instanceof BeanPropertyWriter) { BeanPropertyWriter bpw = (BeanPropertyWriter) prop; ser = bpw.getSerializer(); } final SerializerProvider prov = getProvider(); if (ser == null) { ser = prov.findValueSerializer(prop.getType(), prop); } ser.acceptJsonFormatVisitor(new JsonFormatVisitorWrapper.Base() { @Override public JsonNumberFormatVisitor expectNumberFormat( JavaType type) throws JsonMappingException { return new JsonNumberFormatVisitor() { @Override public void format(JsonValueFormat format) { sb.append("[numberFormat=").append(format).append("]"); } @Override public void enumTypes(Set<String> enums) { } @Override public void numberType(NumberType numberType) { sb.append("[numberType=").append(numberType).append("]"); } }; } @Override public JsonIntegerFormatVisitor expectIntegerFormat(JavaType type) throws JsonMappingException { return new JsonIntegerFormatVisitor() { @Override public void format(JsonValueFormat format) { sb.append("[integerFormat=").append(format).append("]"); } @Override public void enumTypes(Set<String> enums) { } @Override public void numberType(NumberType numberType) { sb.append("[numberType=").append(numberType).append("]"); } }; } }, prop.getType()); sb.append(")]"); } }; } }); assertEquals("[optProp dec([numberType=BIG_DECIMAL])][optProp bigInt([numberType=BIG_INTEGER])]", sb.toString()); }
com.fasterxml.jackson.databind.jsonschema.NewSchemaTest::testSimpleNumbers
src/test/java/com/fasterxml/jackson/databind/jsonschema/NewSchemaTest.java
205
src/test/java/com/fasterxml/jackson/databind/jsonschema/NewSchemaTest.java
testSimpleNumbers
package com.fasterxml.jackson.databind.jsonschema; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.jsonFormatVisitors.*; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; /** * Basic tests to exercise low-level support added for JSON Schema module and * other modules that use type introspection. */ public class NewSchemaTest extends BaseMapTest { enum TestEnum { A, B, C; @Override public String toString() { return "ToString:"+name(); } } enum TestEnumWithJsonValue { A, B, C; @JsonValue public String forSerialize() { return "value-"+name(); } } // silly little class to exercise basic traversal static class POJO { public List<POJO> children; public POJO[] childOrdering; public Map<String, java.util.Date> times; public Map<String,Integer> conversions; public EnumMap<TestEnum,Double> weights; } @JsonPropertyOrder({ "dec", "bigInt" }) static class Numbers { public BigDecimal dec; public BigInteger bigInt; } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); /* Silly little test for simply triggering traversal, without attempting to * verify what is being reported. Smoke test that should trigger problems * if basic POJO type/serializer traversal had issues. */ public void testBasicTraversal() throws Exception { MAPPER.acceptJsonFormatVisitor(POJO.class, new JsonFormatVisitorWrapper.Base()); } public void testSimpleEnum() throws Exception { final Set<String> values = new TreeSet<String>(); ObjectWriter w = MAPPER.writer(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); w.acceptJsonFormatVisitor(TestEnum.class, new JsonFormatVisitorWrapper.Base() { @Override public JsonStringFormatVisitor expectStringFormat(JavaType type) { return new JsonStringFormatVisitor() { @Override public void enumTypes(Set<String> enums) { values.addAll(enums); } @Override public void format(JsonValueFormat format) { } }; } }); assertEquals(3, values.size()); TreeSet<String> exp = new TreeSet<String>(Arrays.asList( "ToString:A", "ToString:B", "ToString:C" )); assertEquals(exp, values); } public void testEnumWithJsonValue() throws Exception { final Set<String> values = new TreeSet<String>(); MAPPER.acceptJsonFormatVisitor(TestEnumWithJsonValue.class, new JsonFormatVisitorWrapper.Base() { @Override public JsonStringFormatVisitor expectStringFormat(JavaType type) { return new JsonStringFormatVisitor() { @Override public void enumTypes(Set<String> enums) { values.addAll(enums); } @Override public void format(JsonValueFormat format) { } }; } }); assertEquals(3, values.size()); TreeSet<String> exp = new TreeSet<String>(Arrays.asList( "value-A", "value-B", "value-C" )); assertEquals(exp, values); } // [2.7]: Ensure JsonValueFormat serializes/deserializes as expected public void testJsonValueFormatHandling() throws Exception { // first: serialize using 'toString()', not name final String EXP = quote("host-name"); assertEquals(EXP, MAPPER.writeValueAsString(JsonValueFormat.HOST_NAME)); // and second, deserialize ok from that as well assertSame(JsonValueFormat.HOST_NAME, MAPPER.readValue(EXP, JsonValueFormat.class)); } // [databind#1045], regression wrt BigDecimal public void testSimpleNumbers() throws Exception { final StringBuilder sb = new StringBuilder(); MAPPER.acceptJsonFormatVisitor(Numbers.class, new JsonFormatVisitorWrapper.Base() { @Override public JsonObjectFormatVisitor expectObjectFormat(final JavaType type) { return new JsonObjectFormatVisitor.Base(getProvider()) { @Override public void optionalProperty(BeanProperty prop) throws JsonMappingException { sb.append("[optProp ").append(prop.getName()).append("("); JsonSerializer<Object> ser = null; if (prop instanceof BeanPropertyWriter) { BeanPropertyWriter bpw = (BeanPropertyWriter) prop; ser = bpw.getSerializer(); } final SerializerProvider prov = getProvider(); if (ser == null) { ser = prov.findValueSerializer(prop.getType(), prop); } ser.acceptJsonFormatVisitor(new JsonFormatVisitorWrapper.Base() { @Override public JsonNumberFormatVisitor expectNumberFormat( JavaType type) throws JsonMappingException { return new JsonNumberFormatVisitor() { @Override public void format(JsonValueFormat format) { sb.append("[numberFormat=").append(format).append("]"); } @Override public void enumTypes(Set<String> enums) { } @Override public void numberType(NumberType numberType) { sb.append("[numberType=").append(numberType).append("]"); } }; } @Override public JsonIntegerFormatVisitor expectIntegerFormat(JavaType type) throws JsonMappingException { return new JsonIntegerFormatVisitor() { @Override public void format(JsonValueFormat format) { sb.append("[integerFormat=").append(format).append("]"); } @Override public void enumTypes(Set<String> enums) { } @Override public void numberType(NumberType numberType) { sb.append("[numberType=").append(numberType).append("]"); } }; } }, prop.getType()); sb.append(")]"); } }; } }); assertEquals("[optProp dec([numberType=BIG_DECIMAL])][optProp bigInt([numberType=BIG_INTEGER])]", sb.toString()); } }
// You are a professional Java test case writer, please create a test case named `testSimpleNumbers` for the issue `JacksonDatabind-1045`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1045 // // ## Issue-Title: // Regression in 2.7.0-rc2, for schema/introspection for BigDecimal // // ## Issue-Description: // (found via Avro module, but surprisingly json schema module has not test to catch it) // // // Looks like schema type for `BigDecimal` is not correctly produced, due to an error in refactoring (made to simplify introspection for simple serializers): it is seen as `BigInteger` (and for Avro, for example, results in `long` getting written). // // // // public void testSimpleNumbers() throws Exception {
205
// [databind#1045], regression wrt BigDecimal
34
138
src/test/java/com/fasterxml/jackson/databind/jsonschema/NewSchemaTest.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1045 ## Issue-Title: Regression in 2.7.0-rc2, for schema/introspection for BigDecimal ## Issue-Description: (found via Avro module, but surprisingly json schema module has not test to catch it) Looks like schema type for `BigDecimal` is not correctly produced, due to an error in refactoring (made to simplify introspection for simple serializers): it is seen as `BigInteger` (and for Avro, for example, results in `long` getting written). ``` You are a professional Java test case writer, please create a test case named `testSimpleNumbers` for the issue `JacksonDatabind-1045`, utilizing the provided issue report information and the following function signature. ```java public void testSimpleNumbers() throws Exception { ```
138
[ "com.fasterxml.jackson.databind.ser.std.NumberSerializer" ]
cdc52201bdaf4ebc5354dfddebf515d262345fa23d644a0a4a58be51e3c2ed16
public void testSimpleNumbers() throws Exception
// You are a professional Java test case writer, please create a test case named `testSimpleNumbers` for the issue `JacksonDatabind-1045`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1045 // // ## Issue-Title: // Regression in 2.7.0-rc2, for schema/introspection for BigDecimal // // ## Issue-Description: // (found via Avro module, but surprisingly json schema module has not test to catch it) // // // Looks like schema type for `BigDecimal` is not correctly produced, due to an error in refactoring (made to simplify introspection for simple serializers): it is seen as `BigInteger` (and for Avro, for example, results in `long` getting written). // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.jsonschema; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.jsonFormatVisitors.*; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; /** * Basic tests to exercise low-level support added for JSON Schema module and * other modules that use type introspection. */ public class NewSchemaTest extends BaseMapTest { enum TestEnum { A, B, C; @Override public String toString() { return "ToString:"+name(); } } enum TestEnumWithJsonValue { A, B, C; @JsonValue public String forSerialize() { return "value-"+name(); } } // silly little class to exercise basic traversal static class POJO { public List<POJO> children; public POJO[] childOrdering; public Map<String, java.util.Date> times; public Map<String,Integer> conversions; public EnumMap<TestEnum,Double> weights; } @JsonPropertyOrder({ "dec", "bigInt" }) static class Numbers { public BigDecimal dec; public BigInteger bigInt; } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); /* Silly little test for simply triggering traversal, without attempting to * verify what is being reported. Smoke test that should trigger problems * if basic POJO type/serializer traversal had issues. */ public void testBasicTraversal() throws Exception { MAPPER.acceptJsonFormatVisitor(POJO.class, new JsonFormatVisitorWrapper.Base()); } public void testSimpleEnum() throws Exception { final Set<String> values = new TreeSet<String>(); ObjectWriter w = MAPPER.writer(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); w.acceptJsonFormatVisitor(TestEnum.class, new JsonFormatVisitorWrapper.Base() { @Override public JsonStringFormatVisitor expectStringFormat(JavaType type) { return new JsonStringFormatVisitor() { @Override public void enumTypes(Set<String> enums) { values.addAll(enums); } @Override public void format(JsonValueFormat format) { } }; } }); assertEquals(3, values.size()); TreeSet<String> exp = new TreeSet<String>(Arrays.asList( "ToString:A", "ToString:B", "ToString:C" )); assertEquals(exp, values); } public void testEnumWithJsonValue() throws Exception { final Set<String> values = new TreeSet<String>(); MAPPER.acceptJsonFormatVisitor(TestEnumWithJsonValue.class, new JsonFormatVisitorWrapper.Base() { @Override public JsonStringFormatVisitor expectStringFormat(JavaType type) { return new JsonStringFormatVisitor() { @Override public void enumTypes(Set<String> enums) { values.addAll(enums); } @Override public void format(JsonValueFormat format) { } }; } }); assertEquals(3, values.size()); TreeSet<String> exp = new TreeSet<String>(Arrays.asList( "value-A", "value-B", "value-C" )); assertEquals(exp, values); } // [2.7]: Ensure JsonValueFormat serializes/deserializes as expected public void testJsonValueFormatHandling() throws Exception { // first: serialize using 'toString()', not name final String EXP = quote("host-name"); assertEquals(EXP, MAPPER.writeValueAsString(JsonValueFormat.HOST_NAME)); // and second, deserialize ok from that as well assertSame(JsonValueFormat.HOST_NAME, MAPPER.readValue(EXP, JsonValueFormat.class)); } // [databind#1045], regression wrt BigDecimal public void testSimpleNumbers() throws Exception { final StringBuilder sb = new StringBuilder(); MAPPER.acceptJsonFormatVisitor(Numbers.class, new JsonFormatVisitorWrapper.Base() { @Override public JsonObjectFormatVisitor expectObjectFormat(final JavaType type) { return new JsonObjectFormatVisitor.Base(getProvider()) { @Override public void optionalProperty(BeanProperty prop) throws JsonMappingException { sb.append("[optProp ").append(prop.getName()).append("("); JsonSerializer<Object> ser = null; if (prop instanceof BeanPropertyWriter) { BeanPropertyWriter bpw = (BeanPropertyWriter) prop; ser = bpw.getSerializer(); } final SerializerProvider prov = getProvider(); if (ser == null) { ser = prov.findValueSerializer(prop.getType(), prop); } ser.acceptJsonFormatVisitor(new JsonFormatVisitorWrapper.Base() { @Override public JsonNumberFormatVisitor expectNumberFormat( JavaType type) throws JsonMappingException { return new JsonNumberFormatVisitor() { @Override public void format(JsonValueFormat format) { sb.append("[numberFormat=").append(format).append("]"); } @Override public void enumTypes(Set<String> enums) { } @Override public void numberType(NumberType numberType) { sb.append("[numberType=").append(numberType).append("]"); } }; } @Override public JsonIntegerFormatVisitor expectIntegerFormat(JavaType type) throws JsonMappingException { return new JsonIntegerFormatVisitor() { @Override public void format(JsonValueFormat format) { sb.append("[integerFormat=").append(format).append("]"); } @Override public void enumTypes(Set<String> enums) { } @Override public void numberType(NumberType numberType) { sb.append("[numberType=").append(numberType).append("]"); } }; } }, prop.getType()); sb.append(")]"); } }; } }); assertEquals("[optProp dec([numberType=BIG_DECIMAL])][optProp bigInt([numberType=BIG_INTEGER])]", sb.toString()); } }
public void testIssue821() { foldSame("var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;"); foldSame("var a = ((Math.random() ? 0 : 1) ||" + "(Math.random()>0.5? '1' : 2 )) + 3 + 4;"); }
com.google.javascript.jscomp.PeepholeFoldConstantsTest::testIssue821
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
583
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
testIssue821
/* * 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.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.javascript.rhino.Node; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link PeepholeFoldConstants} in isolation. Tests for * the interaction of multiple peephole passes are in * {@link PeepholeIntegrationTest}. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { private boolean late; // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { late = false; enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants(late)); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison1() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); fold("undefined == NaN", "false"); fold("NaN == undefined", "false"); fold("undefined == Infinity", "false"); fold("Infinity == undefined", "false"); fold("undefined == -Infinity", "false"); fold("-Infinity == undefined", "false"); fold("({}) == undefined", "false"); fold("undefined == ({})", "false"); fold("([]) == undefined", "false"); fold("undefined == ([])", "false"); fold("(/a/g) == undefined", "false"); fold("undefined == (/a/g)", "false"); fold("(function(){}) == undefined", "false"); fold("undefined == (function(){})", "false"); fold("undefined != NaN", "true"); fold("NaN != undefined", "true"); fold("undefined != Infinity", "true"); fold("Infinity != undefined", "true"); fold("undefined != -Infinity", "true"); fold("-Infinity != undefined", "true"); fold("({}) != undefined", "true"); fold("undefined != ({})", "true"); fold("([]) != undefined", "true"); fold("undefined != ([])", "true"); fold("(/a/g) != undefined", "true"); fold("undefined != (/a/g)", "true"); fold("(function(){}) != undefined", "true"); fold("undefined != (function(){})", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUndefinedComparison2() { fold("\"123\" !== void 0", "true"); fold("\"123\" === void 0", "false"); fold("void 0 !== \"123\"", "true"); fold("void 0 === \"123\"", "false"); } public void testUndefinedComparison3() { fold("\"123\" !== undefined", "true"); fold("\"123\" === undefined", "false"); fold("undefined !== \"123\"", "true"); fold("undefined === \"123\"", "false"); } public void testUndefinedComparison4() { fold("1 !== void 0", "true"); fold("1 === void 0", "false"); fold("null !== void 0", "true"); fold("null === void 0", "false"); fold("undefined !== void 0", "false"); fold("undefined === void 0", "true"); } public void testNullComparison1() { fold("null == undefined", "true"); fold("null == null", "true"); fold("null == void 0", "true"); fold("null == 0", "false"); fold("null == 1", "false"); fold("null == 'hi'", "false"); fold("null == true", "false"); fold("null == false", "false"); fold("null === undefined", "false"); fold("null === null", "true"); fold("null === void 0", "false"); foldSame("null == this"); foldSame("null == x"); fold("null != undefined", "false"); fold("null != null", "false"); fold("null != void 0", "false"); fold("null != 0", "true"); fold("null != 1", "true"); fold("null != 'hi'", "true"); fold("null != true", "true"); fold("null != false", "true"); fold("null !== undefined", "true"); fold("null !== void 0", "true"); fold("null !== null", "false"); foldSame("null != this"); foldSame("null != x"); fold("null < null", "false"); fold("null > null", "false"); fold("null >= null", "true"); fold("null <= null", "true"); foldSame("0 < null"); // foldable fold("true > null", "true"); foldSame("'hi' >= null"); // foldable fold("null <= null", "true"); foldSame("null < 0"); // foldable fold("null > true", "false"); foldSame("null >= 'hi'"); // foldable fold("null <= null", "true"); fold("null == null", "true"); fold("0 == null", "false"); fold("1 == null", "false"); fold("'hi' == null", "false"); fold("true == null", "false"); fold("false == null", "false"); fold("null === null", "true"); fold("void 0 === null", "false"); fold("null == NaN", "false"); fold("NaN == null", "false"); fold("null == Infinity", "false"); fold("Infinity == null", "false"); fold("null == -Infinity", "false"); fold("-Infinity == null", "false"); fold("({}) == null", "false"); fold("null == ({})", "false"); fold("([]) == null", "false"); fold("null == ([])", "false"); fold("(/a/g) == null", "false"); fold("null == (/a/g)", "false"); fold("(function(){}) == null", "false"); fold("null == (function(){})", "false"); fold("null != NaN", "true"); fold("NaN != null", "true"); fold("null != Infinity", "true"); fold("Infinity != null", "true"); fold("null != -Infinity", "true"); fold("-Infinity != null", "true"); fold("({}) != null", "true"); fold("null != ({})", "true"); fold("([]) != null", "true"); fold("null != ([])", "true"); fold("(/a/g) != null", "true"); fold("null != (/a/g)", "true"); fold("(function(){}) != null", "true"); fold("null != (function(){})", "true"); foldSame("({a:f()}) == null"); foldSame("null == ({a:f()})"); foldSame("([f()]) == null"); foldSame("null == ([f()])"); foldSame("this == null"); foldSame("x == null"); } public void testUnaryOps() { // These cases are handled by PeepholeRemoveDeadCode. foldSame("!foo()"); foldSame("~foo()"); foldSame("-foo()"); // These cases are handled here. fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=-0.0"); fold("a=-(0)", "a=-0.0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); foldSame("a=+foo()"); foldSame("a=+f"); fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable fold("a=+0", "a=0"); fold("a=+Infinity", "a=Infinity"); fold("a=+NaN", "a=NaN"); fold("a=+-7", "a=-7"); fold("a=+.5", "a=.5"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); foldSame("x = [foo()] && x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // unfoldable, because the right-side may be the result fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // folded, but not here. foldSame("a = x || false ? b : c"); foldSame("a = x && true ? b : c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); fold("1 && b()", "b()"); fold("a() && (1 && b())", "a() && b()"); // TODO(johnlenz): Consider folding the following to: // "(a(),1) && b(); fold("(a() && 1) && b()", "(a() && 1) && b()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = 1 ^ 1", "x = 0"); fold("x = 1 ^ 2", "x = 3"); fold("x = 3 ^ 1", "x = 2"); fold("x = 3 ^ 3", "x = 0"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1"); fold("x = 1.1 & 1", "x = 1"); fold("x = 1 & 3000000000", "x = 0"); fold("x = 3000000000 & 1", "x = 0"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1"); foldSame("x = 1 | 3E9"); fold("x = 1 | 3000000001", "x = -1294967295"); } public void testFoldBitwiseOp2() { fold("x = y & 1 & 1", "x = y & 1"); fold("x = y & 1 & 2", "x = y & 0"); fold("x = y & 3 & 1", "x = y & 1"); fold("x = 3 & y & 1", "x = y & 1"); fold("x = y & 3 & 3", "x = y & 3"); fold("x = 3 & y & 3", "x = y & 3"); fold("x = y | 1 | 1", "x = y | 1"); fold("x = y | 1 | 2", "x = y | 3"); fold("x = y | 3 | 1", "x = y | 3"); fold("x = 3 | y | 1", "x = y | 3"); fold("x = y | 3 | 3", "x = y | 3"); fold("x = 3 | y | 3", "x = y | 3"); fold("x = y ^ 1 ^ 1", "x = y ^ 0"); fold("x = y ^ 1 ^ 2", "x = y ^ 3"); fold("x = y ^ 3 ^ 1", "x = y ^ 2"); fold("x = 3 ^ y ^ 1", "x = y ^ 2"); fold("x = y ^ 3 ^ 3", "x = y ^ 0"); fold("x = 3 ^ y ^ 3", "x = y ^ 0"); fold("x = Infinity | NaN", "x=0"); fold("x = 12 | NaN", "x=12"); } public void testFoldingMixTypesLate() { late = true; fold("x = x + '2'", "x+='2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x-=2"); fold("x = x ^ '2'", "x^=2"); fold("x = '2' ^ x", "x^=2"); fold("x = '2' & x", "x&=2"); fold("x = '2' | x", "x|=2"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingMixTypesEarly() { late = false; foldSame("x = x + '2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x = x - 2"); fold("x = x ^ '2'", "x = x ^ 2"); fold("x = '2' ^ x", "x = 2 ^ x"); fold("x = '2' & x", "x = 2 & x"); fold("x = '2' | x", "x = 2 | x"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingAdd() { fold("x = null + true", "x=1"); foldSame("x = a + true"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can) } public void testIssue821() { foldSame("var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;"); foldSame("var a = ((Math.random() ? 0 : 1) ||" + "(Math.random()>0.5? '1' : 2 )) + 3 + 4;"); } public void testFoldConstructor() { fold("x = this[new String('a')]", "x = this['a']"); fold("x = ob[new String(12)]", "x = ob['12']"); fold("x = ob[new String(false)]", "x = ob['false']"); fold("x = ob[new String(null)]", "x = ob['null']"); fold("x = 'a' + new String('b')", "x = 'ab'"); fold("x = 'a' + new String(23)", "x = 'a23'"); fold("x = 2 + new String(1)", "x = '21'"); foldSame("x = ob[new String(a)]"); foldSame("x = new String('a')"); foldSame("x = (new String('a'))[3]"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); fold("x = 1 % 0", "x = 1 % 0"); } public void testFoldArithmetic2() { foldSame("x = y + 10 + 20"); foldSame("x = y / 2 / 4"); fold("x = y * 2.25 * 3", "x = y * 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5"); } public void testFoldArithmetic3() { fold("x = null * undefined", "x = NaN"); fold("x = null * 1", "x = 0"); fold("x = (null - 1) * 2", "x = -2"); fold("x = (null + 1) * 2", "x = 2"); } public void testFoldArithmeticInfinity() { fold("x=-Infinity-2", "x=-Infinity"); fold("x=Infinity-2", "x=Infinity"); fold("x=Infinity*5", "x=Infinity"); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = false == false", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = false === false", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldComparison3() { fold("x = !1 == !0", "x = false"); fold("x = !0 == !0", "x = true"); fold("x = !1 == !1", "x = true"); fold("x = !1 == null", "x = false"); fold("x = !1 == !0", "x = false"); fold("x = !0 == null", "x = false"); fold("!0 == !0", "true"); fold("!1 == null", "false"); fold("!1 == !0", "false"); fold("!0 == null", "false"); fold("x = !0 === !0", "x = true"); fold("x = !1 === !1", "x = true"); fold("x = !1 === null", "x = false"); fold("x = !1 === !0", "x = false"); fold("x = !0 === null", "x = false"); fold("!0 === !0", "true"); fold("!1 === null", "false"); fold("!1 === !0", "false"); fold("!0 === null", "false"); } public void testFoldGetElem() { fold("x = [,10][0]", "x = void 0"); fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); foldSame("x = [foo(), 0][1]"); fold("x = [0, foo()][1]", "x = foo()"); foldSame("x = [0, foo()][0]"); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldLeft() { foldSame("(+x - 1) + 2"); // not yet fold("(+x + 1) + 2", "+x + 3"); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Not handled yet fold("x = [,,1].length", "x = 3"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test Unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); fold("x = typeof function() {}", "x = 'function'"); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("!0 instanceof Object", "false"); fold("!0 instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); fold("(function() {}) instanceof Object", "true"); // An unknown value should never be folded. foldSame("x instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOpsLate() { late = true; fold("x=x+y", "x+=y"); foldSame("x=y+x"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); fold("x=x-y", "x-=y"); foldSame("x=y-x"); fold("x=x|y", "x|=y"); fold("x=y|x", "x|=y"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); // This is OK, really. fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2"); } public void testAssignOpsEarly() { late = false; foldSame("x=x+y"); foldSame("x=y+x"); foldSame("x=x*y"); foldSame("x=y*x"); foldSame("x.y=x.y+z"); foldSame("next().x = next().x + 1"); foldSame("x=x-y"); foldSame("x=y-x"); foldSame("x=x|y"); foldSame("x=y|x"); foldSame("x=x*y"); foldSame("x=y*x"); foldSame("x.y=x.y+z"); foldSame("next().x = next().x + 1"); // This is OK, really. fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2"); } public void testFoldAdd1() { fold("x=false+1","x=1"); fold("x=true+1","x=2"); fold("x=1+false","x=1"); fold("x=1+true","x=2"); } public void testFoldLiteralNames() { foldSame("NaN == NaN"); foldSame("Infinity == Infinity"); foldSame("Infinity == NaN"); fold("undefined == NaN", "false"); fold("undefined == Infinity", "false"); foldSame("Infinity >= Infinity"); foldSame("NaN >= NaN"); } public void testFoldLiteralsTypeMismatches() { fold("true == true", "true"); fold("true == false", "false"); fold("true == null", "false"); fold("false == null", "false"); // relational operators convert its operands fold("null <= null", "true"); // 0 = 0 fold("null >= null", "true"); fold("null > null", "false"); fold("null < null", "false"); fold("false >= null", "true"); // 0 = 0 fold("false <= null", "true"); fold("false > null", "false"); fold("false < null", "false"); fold("true >= null", "true"); // 1 > 0 fold("true <= null", "false"); fold("true > null", "true"); fold("true < null", "false"); fold("true >= false", "true"); // 1 > 0 fold("true <= false", "false"); fold("true > false", "true"); fold("true < false", "false"); } public void testFoldLeftChildConcat() { foldSame("x +5 + \"1\""); fold("x+\"5\" + \"1\"", "x + \"51\""); // fold("\"a\"+(c+\"b\")","\"a\"+c+\"b\""); fold("\"a\"+(\"b\"+c)","\"ab\"+c"); } public void testFoldLeftChildOp() { fold("x * Infinity * 2", "x * Infinity"); foldSame("x - Infinity - 2"); // want "x-Infinity" foldSame("x - 1 + Infinity"); foldSame("x - 2 + 1"); foldSame("x - 2 + 3"); foldSame("1 + x - 2 + 1"); foldSame("1 + x - 2 + 3"); foldSame("1 + x - 2 + 3 - 1"); foldSame("f(x)-0"); foldSame("x-0-0"); foldSame("x+2-2+2"); foldSame("x+2-2+2-2"); foldSame("x-2+2"); foldSame("x-2+2-2"); foldSame("x-2+2-2+2"); foldSame("1+x-0-NaN"); foldSame("1+f(x)-0-NaN"); foldSame("1+x-0+NaN"); foldSame("1+f(x)-0+NaN"); foldSame("1+x+NaN"); // unfoldable foldSame("x+2-2"); // unfoldable foldSame("x+2"); // nothing to do foldSame("x-2"); // nothing to do } public void testFoldSimpleArithmeticOp() { foldSame("x*NaN"); foldSame("NaN/y"); foldSame("f(x)-0"); foldSame("f(x)*1"); foldSame("1*f(x)"); foldSame("0+a+b"); foldSame("0-a-b"); foldSame("a+b-0"); foldSame("(1+x)*NaN"); foldSame("(1+f(x))*NaN"); // don't fold side-effects } public void testFoldLiteralsAsNumbers() { fold("x/'12'","x/12"); fold("x/('12'+'6')", "x/126"); fold("true*x", "1*x"); fold("x/false", "x/0"); // should we add an error check? :) } public void testNotFoldBackToTrueFalse() { late = false; fold("!0", "true"); fold("!1", "false"); fold("!3", "false"); late = true; foldSame("!0"); foldSame("!1"); fold("!3", "false"); foldSame("false"); foldSame("true"); } public void testFoldBangConstants() { fold("1 + !0", "2"); fold("1 + !1", "1"); fold("'a ' + !1", "'a false'"); fold("'a ' + !0", "'a true'"); } public void testFoldMixed() { fold("''+[1]", "'1'"); foldSame("false+[]"); // would like: "\"false\"" } public void testFoldVoid() { foldSame("void 0"); fold("void 1", "void 0"); fold("void x", "void 0"); fold("void x()", "void x()"); } public void testObjectLiteral() { test("(!{})", "false"); test("(!{a:1})", "false"); testSame("(!{a:foo()})"); testSame("(!{'a':foo()})"); } public void testArrayLiteral() { test("(![])", "false"); test("(![1])", "false"); test("(![a])", "false"); testSame("(![foo()])"); } public void testIssue601() { testSame("'\\v' == 'v'"); testSame("'v' == '\\v'"); testSame("'\\u000B' == '\\v'"); } public void testFoldObjectLiteralRef1() { // Leave extra side-effects in place testSame("var x = ({a:foo(),b:bar()}).a"); testSame("var x = ({a:1,b:bar()}).a"); testSame("function f() { return {b:foo(), a:2}.a; }"); // on the LHS the object act as a temporary leave it in place. testSame("({a:x}).a = 1"); test("({a:x}).a += 1", "({a:x}).a = x + 1"); testSame("({a:x}).a ++"); testSame("({a:x}).a --"); // functions can't reference the object through 'this'. testSame("({a:function(){return this}}).a"); testSame("({get a() {return this}}).a"); testSame("({set a(b) {return this}}).a"); // Leave unknown props alone, the might be on the prototype testSame("({}).a"); // setters by themselves don't provide a definition testSame("({}).a"); testSame("({set a(b) {}}).a"); // sets don't hide other definitions. test("({a:1,set a(b) {}}).a", "1"); // get is transformed to a call (gets don't have self referential names) test("({get a() {}}).a", "(function (){})()"); // sets don't hide other definitions. test("({get a() {},set a(b) {}}).a", "(function (){})()"); // a function remains a function not a call. test("var x = ({a:function(){return 1}}).a", "var x = function(){return 1}"); test("var x = ({a:1}).a", "var x = 1"); test("var x = ({a:1, a:2}).a", "var x = 2"); test("var x = ({a:1, a:foo()}).a", "var x = foo()"); test("var x = ({a:foo()}).a", "var x = foo()"); test("function f() { return {a:1, b:2}.a; }", "function f() { return 1; }"); // GETELEM is handled the same way. test("var x = ({'a':1})['a']", "var x = 1"); } public void testFoldObjectLiteralRef2() { late = false; test("({a:x}).a += 1", "({a:x}).a = x + 1"); late = true; testSame("({a:x}).a += 1"); } public void testIEString() { testSame("!+'\\v1'"); } public void testIssue522() { testSame("[][1] = 1;"); } private static final List<String> LITERAL_OPERANDS = ImmutableList.of( "null", "undefined", "void 0", "true", "false", "!0", "!1", "0", "1", "''", "'123'", "'abc'", "'def'", "NaN", "Infinity", // TODO(nicksantos): Add more literals "-Infinity" //"({})", // "[]" //"[0]", //"Object", //"(function() {})" ); public void testInvertibleOperators() { Map<String, String> inverses = ImmutableMap.<String, String>builder() .put("==", "!=") .put("===", "!==") .put("<=", ">") .put("<", ">=") .put(">=", "<") .put(">", "<=") .put("!=", "==") .put("!==", "===") .build(); Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">"); Set<String> equalitors = ImmutableSet.of("==", "==="); Set<String> uncomparables = ImmutableSet.of("undefined", "void 0"); List<String> operators = ImmutableList.copyOf(inverses.values()); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = 0; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); String inverse = inverses.get(op); // Test invertability. if (comparators.contains(op) && (uncomparables.contains(a) || uncomparables.contains(b))) { assertSameResults(join(a, op, b), "false"); assertSameResults(join(a, inverse, b), "false"); } else if (a.equals(b) && equalitors.contains(op)) { if (a.equals("NaN") || a.equals("Infinity") || a.equals("-Infinity")) { foldSame(join(a, op, b)); foldSame(join(a, inverse, b)); } else { assertSameResults(join(a, op, b), "true"); assertSameResults(join(a, inverse, b), "false"); } } else { assertNotSameResults(join(a, op, b), join(a, inverse, b)); } } } } } public void testCommutativeOperators() { late = true; List<String> operators = ImmutableList.of( "==", "!=", "===", "!==", "*", "|", "&", "^"); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = iOperandA; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); // Test commutativity. // TODO(nicksantos): Eventually, all cases should be collapsed. assertSameResultsOrUncollapsed(join(a, op, b), join(b, op, a)); } } } } public void testConvertToNumberNegativeInf() { foldSame("var x = 3 * (r ? Infinity : -Infinity);"); } private String join(String operandA, String op, String operandB) { return operandA + " " + op + " " + operandB; } private void assertSameResultsOrUncollapsed(String exprA, String exprB) { String resultA = process(exprA); String resultB = process(exprB); // TODO: why is nothing done with this? if (resultA.equals(print(exprA))) { foldSame(exprA); foldSame(exprB); } else { assertSameResults(exprA, exprB); } } private void assertSameResults(String exprA, String exprB) { assertEquals( "Expressions did not fold the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA), process(exprB)); } private void assertNotSameResults(String exprA, String exprB) { assertFalse( "Expressions folded the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA).equals(process(exprB))); } private String process(String js) { return printHelper(js, true); } private String print(String js) { return printHelper(js, false); } private String printHelper(String js, boolean runProcessor) { Compiler compiler = createCompiler(); CompilerOptions options = getOptions(); compiler.init( ImmutableList.<SourceFile>of(), ImmutableList.of(SourceFile.fromCode("testcode", js)), options); Node root = compiler.parseInputs(); assertTrue("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()) + "\nEXPR: " + js, root != null); Node externsRoot = root.getFirstChild(); Node mainRoot = externsRoot.getNext(); if (runProcessor) { getProcessor(compiler).process(externsRoot, mainRoot); } return compiler.toSource(mainRoot); } }
// You are a professional Java test case writer, please create a test case named `testIssue821` for the issue `Closure-821`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-821 // // ## Issue-Title: // Wrong code generated if mixing types in ternary operator // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Use Google Closure Compiler to compile this code: // // var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4; // // You can either simple or advanced. It doesn't matter // // // **What is the expected output? What do you see instead?** // // I'm seeing this as a result: // var a = (0.5 < Math.random() ? 1 : 2) + 7; // // This is obviously wrong as the '1' string literal got converted to a number, and 3+4 got combined into 7 while that's not ok as '1' + 3 + 4 = '134', not '17'. // // **What version of the product are you using? On what operating system?** // **Please provide any additional information below.** // // Seems like this issue happens only when you are mixing types together. If both 1 and 2 are string literals or if they are both numbers it won't happen. I was also a little surprised to see this happening in simple mode as it actually breaks the behavior. // // public void testIssue821() {
583
10
579
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
test
```markdown ## Issue-ID: Closure-821 ## Issue-Title: Wrong code generated if mixing types in ternary operator ## Issue-Description: **What steps will reproduce the problem?** 1. Use Google Closure Compiler to compile this code: var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4; You can either simple or advanced. It doesn't matter **What is the expected output? What do you see instead?** I'm seeing this as a result: var a = (0.5 < Math.random() ? 1 : 2) + 7; This is obviously wrong as the '1' string literal got converted to a number, and 3+4 got combined into 7 while that's not ok as '1' + 3 + 4 = '134', not '17'. **What version of the product are you using? On what operating system?** **Please provide any additional information below.** Seems like this issue happens only when you are mixing types together. If both 1 and 2 are string literals or if they are both numbers it won't happen. I was also a little surprised to see this happening in simple mode as it actually breaks the behavior. ``` You are a professional Java test case writer, please create a test case named `testIssue821` for the issue `Closure-821`, utilizing the provided issue report information and the following function signature. ```java public void testIssue821() { ```
579
[ "com.google.javascript.jscomp.NodeUtil" ]
cdd903b1f34b6ae0172ef7cb4b8f7642c2f520c66d48c9062a1c3fc70c30da8e
public void testIssue821()
// You are a professional Java test case writer, please create a test case named `testIssue821` for the issue `Closure-821`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-821 // // ## Issue-Title: // Wrong code generated if mixing types in ternary operator // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Use Google Closure Compiler to compile this code: // // var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4; // // You can either simple or advanced. It doesn't matter // // // **What is the expected output? What do you see instead?** // // I'm seeing this as a result: // var a = (0.5 < Math.random() ? 1 : 2) + 7; // // This is obviously wrong as the '1' string literal got converted to a number, and 3+4 got combined into 7 while that's not ok as '1' + 3 + 4 = '134', not '17'. // // **What version of the product are you using? On what operating system?** // **Please provide any additional information below.** // // Seems like this issue happens only when you are mixing types together. If both 1 and 2 are string literals or if they are both numbers it won't happen. I was also a little surprised to see this happening in simple mode as it actually breaks the behavior. // //
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.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.javascript.rhino.Node; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link PeepholeFoldConstants} in isolation. Tests for * the interaction of multiple peephole passes are in * {@link PeepholeIntegrationTest}. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { private boolean late; // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { late = false; enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants(late)); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison1() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); fold("undefined == NaN", "false"); fold("NaN == undefined", "false"); fold("undefined == Infinity", "false"); fold("Infinity == undefined", "false"); fold("undefined == -Infinity", "false"); fold("-Infinity == undefined", "false"); fold("({}) == undefined", "false"); fold("undefined == ({})", "false"); fold("([]) == undefined", "false"); fold("undefined == ([])", "false"); fold("(/a/g) == undefined", "false"); fold("undefined == (/a/g)", "false"); fold("(function(){}) == undefined", "false"); fold("undefined == (function(){})", "false"); fold("undefined != NaN", "true"); fold("NaN != undefined", "true"); fold("undefined != Infinity", "true"); fold("Infinity != undefined", "true"); fold("undefined != -Infinity", "true"); fold("-Infinity != undefined", "true"); fold("({}) != undefined", "true"); fold("undefined != ({})", "true"); fold("([]) != undefined", "true"); fold("undefined != ([])", "true"); fold("(/a/g) != undefined", "true"); fold("undefined != (/a/g)", "true"); fold("(function(){}) != undefined", "true"); fold("undefined != (function(){})", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUndefinedComparison2() { fold("\"123\" !== void 0", "true"); fold("\"123\" === void 0", "false"); fold("void 0 !== \"123\"", "true"); fold("void 0 === \"123\"", "false"); } public void testUndefinedComparison3() { fold("\"123\" !== undefined", "true"); fold("\"123\" === undefined", "false"); fold("undefined !== \"123\"", "true"); fold("undefined === \"123\"", "false"); } public void testUndefinedComparison4() { fold("1 !== void 0", "true"); fold("1 === void 0", "false"); fold("null !== void 0", "true"); fold("null === void 0", "false"); fold("undefined !== void 0", "false"); fold("undefined === void 0", "true"); } public void testNullComparison1() { fold("null == undefined", "true"); fold("null == null", "true"); fold("null == void 0", "true"); fold("null == 0", "false"); fold("null == 1", "false"); fold("null == 'hi'", "false"); fold("null == true", "false"); fold("null == false", "false"); fold("null === undefined", "false"); fold("null === null", "true"); fold("null === void 0", "false"); foldSame("null == this"); foldSame("null == x"); fold("null != undefined", "false"); fold("null != null", "false"); fold("null != void 0", "false"); fold("null != 0", "true"); fold("null != 1", "true"); fold("null != 'hi'", "true"); fold("null != true", "true"); fold("null != false", "true"); fold("null !== undefined", "true"); fold("null !== void 0", "true"); fold("null !== null", "false"); foldSame("null != this"); foldSame("null != x"); fold("null < null", "false"); fold("null > null", "false"); fold("null >= null", "true"); fold("null <= null", "true"); foldSame("0 < null"); // foldable fold("true > null", "true"); foldSame("'hi' >= null"); // foldable fold("null <= null", "true"); foldSame("null < 0"); // foldable fold("null > true", "false"); foldSame("null >= 'hi'"); // foldable fold("null <= null", "true"); fold("null == null", "true"); fold("0 == null", "false"); fold("1 == null", "false"); fold("'hi' == null", "false"); fold("true == null", "false"); fold("false == null", "false"); fold("null === null", "true"); fold("void 0 === null", "false"); fold("null == NaN", "false"); fold("NaN == null", "false"); fold("null == Infinity", "false"); fold("Infinity == null", "false"); fold("null == -Infinity", "false"); fold("-Infinity == null", "false"); fold("({}) == null", "false"); fold("null == ({})", "false"); fold("([]) == null", "false"); fold("null == ([])", "false"); fold("(/a/g) == null", "false"); fold("null == (/a/g)", "false"); fold("(function(){}) == null", "false"); fold("null == (function(){})", "false"); fold("null != NaN", "true"); fold("NaN != null", "true"); fold("null != Infinity", "true"); fold("Infinity != null", "true"); fold("null != -Infinity", "true"); fold("-Infinity != null", "true"); fold("({}) != null", "true"); fold("null != ({})", "true"); fold("([]) != null", "true"); fold("null != ([])", "true"); fold("(/a/g) != null", "true"); fold("null != (/a/g)", "true"); fold("(function(){}) != null", "true"); fold("null != (function(){})", "true"); foldSame("({a:f()}) == null"); foldSame("null == ({a:f()})"); foldSame("([f()]) == null"); foldSame("null == ([f()])"); foldSame("this == null"); foldSame("x == null"); } public void testUnaryOps() { // These cases are handled by PeepholeRemoveDeadCode. foldSame("!foo()"); foldSame("~foo()"); foldSame("-foo()"); // These cases are handled here. fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=-0.0"); fold("a=-(0)", "a=-0.0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); foldSame("a=+foo()"); foldSame("a=+f"); fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable fold("a=+0", "a=0"); fold("a=+Infinity", "a=Infinity"); fold("a=+NaN", "a=NaN"); fold("a=+-7", "a=-7"); fold("a=+.5", "a=.5"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); foldSame("x = [foo()] && x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // unfoldable, because the right-side may be the result fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // folded, but not here. foldSame("a = x || false ? b : c"); foldSame("a = x && true ? b : c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); fold("1 && b()", "b()"); fold("a() && (1 && b())", "a() && b()"); // TODO(johnlenz): Consider folding the following to: // "(a(),1) && b(); fold("(a() && 1) && b()", "(a() && 1) && b()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = 1 ^ 1", "x = 0"); fold("x = 1 ^ 2", "x = 3"); fold("x = 3 ^ 1", "x = 2"); fold("x = 3 ^ 3", "x = 0"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1"); fold("x = 1.1 & 1", "x = 1"); fold("x = 1 & 3000000000", "x = 0"); fold("x = 3000000000 & 1", "x = 0"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1"); foldSame("x = 1 | 3E9"); fold("x = 1 | 3000000001", "x = -1294967295"); } public void testFoldBitwiseOp2() { fold("x = y & 1 & 1", "x = y & 1"); fold("x = y & 1 & 2", "x = y & 0"); fold("x = y & 3 & 1", "x = y & 1"); fold("x = 3 & y & 1", "x = y & 1"); fold("x = y & 3 & 3", "x = y & 3"); fold("x = 3 & y & 3", "x = y & 3"); fold("x = y | 1 | 1", "x = y | 1"); fold("x = y | 1 | 2", "x = y | 3"); fold("x = y | 3 | 1", "x = y | 3"); fold("x = 3 | y | 1", "x = y | 3"); fold("x = y | 3 | 3", "x = y | 3"); fold("x = 3 | y | 3", "x = y | 3"); fold("x = y ^ 1 ^ 1", "x = y ^ 0"); fold("x = y ^ 1 ^ 2", "x = y ^ 3"); fold("x = y ^ 3 ^ 1", "x = y ^ 2"); fold("x = 3 ^ y ^ 1", "x = y ^ 2"); fold("x = y ^ 3 ^ 3", "x = y ^ 0"); fold("x = 3 ^ y ^ 3", "x = y ^ 0"); fold("x = Infinity | NaN", "x=0"); fold("x = 12 | NaN", "x=12"); } public void testFoldingMixTypesLate() { late = true; fold("x = x + '2'", "x+='2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x-=2"); fold("x = x ^ '2'", "x^=2"); fold("x = '2' ^ x", "x^=2"); fold("x = '2' & x", "x&=2"); fold("x = '2' | x", "x|=2"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingMixTypesEarly() { late = false; foldSame("x = x + '2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x = x - 2"); fold("x = x ^ '2'", "x = x ^ 2"); fold("x = '2' ^ x", "x = 2 ^ x"); fold("x = '2' & x", "x = 2 & x"); fold("x = '2' | x", "x = 2 | x"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingAdd() { fold("x = null + true", "x=1"); foldSame("x = a + true"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can) } public void testIssue821() { foldSame("var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;"); foldSame("var a = ((Math.random() ? 0 : 1) ||" + "(Math.random()>0.5? '1' : 2 )) + 3 + 4;"); } public void testFoldConstructor() { fold("x = this[new String('a')]", "x = this['a']"); fold("x = ob[new String(12)]", "x = ob['12']"); fold("x = ob[new String(false)]", "x = ob['false']"); fold("x = ob[new String(null)]", "x = ob['null']"); fold("x = 'a' + new String('b')", "x = 'ab'"); fold("x = 'a' + new String(23)", "x = 'a23'"); fold("x = 2 + new String(1)", "x = '21'"); foldSame("x = ob[new String(a)]"); foldSame("x = new String('a')"); foldSame("x = (new String('a'))[3]"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); fold("x = 1 % 0", "x = 1 % 0"); } public void testFoldArithmetic2() { foldSame("x = y + 10 + 20"); foldSame("x = y / 2 / 4"); fold("x = y * 2.25 * 3", "x = y * 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5"); } public void testFoldArithmetic3() { fold("x = null * undefined", "x = NaN"); fold("x = null * 1", "x = 0"); fold("x = (null - 1) * 2", "x = -2"); fold("x = (null + 1) * 2", "x = 2"); } public void testFoldArithmeticInfinity() { fold("x=-Infinity-2", "x=-Infinity"); fold("x=Infinity-2", "x=Infinity"); fold("x=Infinity*5", "x=Infinity"); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = false == false", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = false === false", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldComparison3() { fold("x = !1 == !0", "x = false"); fold("x = !0 == !0", "x = true"); fold("x = !1 == !1", "x = true"); fold("x = !1 == null", "x = false"); fold("x = !1 == !0", "x = false"); fold("x = !0 == null", "x = false"); fold("!0 == !0", "true"); fold("!1 == null", "false"); fold("!1 == !0", "false"); fold("!0 == null", "false"); fold("x = !0 === !0", "x = true"); fold("x = !1 === !1", "x = true"); fold("x = !1 === null", "x = false"); fold("x = !1 === !0", "x = false"); fold("x = !0 === null", "x = false"); fold("!0 === !0", "true"); fold("!1 === null", "false"); fold("!1 === !0", "false"); fold("!0 === null", "false"); } public void testFoldGetElem() { fold("x = [,10][0]", "x = void 0"); fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); foldSame("x = [foo(), 0][1]"); fold("x = [0, foo()][1]", "x = foo()"); foldSame("x = [0, foo()][0]"); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldLeft() { foldSame("(+x - 1) + 2"); // not yet fold("(+x + 1) + 2", "+x + 3"); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Not handled yet fold("x = [,,1].length", "x = 3"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test Unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); fold("x = typeof function() {}", "x = 'function'"); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("!0 instanceof Object", "false"); fold("!0 instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); fold("(function() {}) instanceof Object", "true"); // An unknown value should never be folded. foldSame("x instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOpsLate() { late = true; fold("x=x+y", "x+=y"); foldSame("x=y+x"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); fold("x=x-y", "x-=y"); foldSame("x=y-x"); fold("x=x|y", "x|=y"); fold("x=y|x", "x|=y"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); // This is OK, really. fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2"); } public void testAssignOpsEarly() { late = false; foldSame("x=x+y"); foldSame("x=y+x"); foldSame("x=x*y"); foldSame("x=y*x"); foldSame("x.y=x.y+z"); foldSame("next().x = next().x + 1"); foldSame("x=x-y"); foldSame("x=y-x"); foldSame("x=x|y"); foldSame("x=y|x"); foldSame("x=x*y"); foldSame("x=y*x"); foldSame("x.y=x.y+z"); foldSame("next().x = next().x + 1"); // This is OK, really. fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2"); } public void testFoldAdd1() { fold("x=false+1","x=1"); fold("x=true+1","x=2"); fold("x=1+false","x=1"); fold("x=1+true","x=2"); } public void testFoldLiteralNames() { foldSame("NaN == NaN"); foldSame("Infinity == Infinity"); foldSame("Infinity == NaN"); fold("undefined == NaN", "false"); fold("undefined == Infinity", "false"); foldSame("Infinity >= Infinity"); foldSame("NaN >= NaN"); } public void testFoldLiteralsTypeMismatches() { fold("true == true", "true"); fold("true == false", "false"); fold("true == null", "false"); fold("false == null", "false"); // relational operators convert its operands fold("null <= null", "true"); // 0 = 0 fold("null >= null", "true"); fold("null > null", "false"); fold("null < null", "false"); fold("false >= null", "true"); // 0 = 0 fold("false <= null", "true"); fold("false > null", "false"); fold("false < null", "false"); fold("true >= null", "true"); // 1 > 0 fold("true <= null", "false"); fold("true > null", "true"); fold("true < null", "false"); fold("true >= false", "true"); // 1 > 0 fold("true <= false", "false"); fold("true > false", "true"); fold("true < false", "false"); } public void testFoldLeftChildConcat() { foldSame("x +5 + \"1\""); fold("x+\"5\" + \"1\"", "x + \"51\""); // fold("\"a\"+(c+\"b\")","\"a\"+c+\"b\""); fold("\"a\"+(\"b\"+c)","\"ab\"+c"); } public void testFoldLeftChildOp() { fold("x * Infinity * 2", "x * Infinity"); foldSame("x - Infinity - 2"); // want "x-Infinity" foldSame("x - 1 + Infinity"); foldSame("x - 2 + 1"); foldSame("x - 2 + 3"); foldSame("1 + x - 2 + 1"); foldSame("1 + x - 2 + 3"); foldSame("1 + x - 2 + 3 - 1"); foldSame("f(x)-0"); foldSame("x-0-0"); foldSame("x+2-2+2"); foldSame("x+2-2+2-2"); foldSame("x-2+2"); foldSame("x-2+2-2"); foldSame("x-2+2-2+2"); foldSame("1+x-0-NaN"); foldSame("1+f(x)-0-NaN"); foldSame("1+x-0+NaN"); foldSame("1+f(x)-0+NaN"); foldSame("1+x+NaN"); // unfoldable foldSame("x+2-2"); // unfoldable foldSame("x+2"); // nothing to do foldSame("x-2"); // nothing to do } public void testFoldSimpleArithmeticOp() { foldSame("x*NaN"); foldSame("NaN/y"); foldSame("f(x)-0"); foldSame("f(x)*1"); foldSame("1*f(x)"); foldSame("0+a+b"); foldSame("0-a-b"); foldSame("a+b-0"); foldSame("(1+x)*NaN"); foldSame("(1+f(x))*NaN"); // don't fold side-effects } public void testFoldLiteralsAsNumbers() { fold("x/'12'","x/12"); fold("x/('12'+'6')", "x/126"); fold("true*x", "1*x"); fold("x/false", "x/0"); // should we add an error check? :) } public void testNotFoldBackToTrueFalse() { late = false; fold("!0", "true"); fold("!1", "false"); fold("!3", "false"); late = true; foldSame("!0"); foldSame("!1"); fold("!3", "false"); foldSame("false"); foldSame("true"); } public void testFoldBangConstants() { fold("1 + !0", "2"); fold("1 + !1", "1"); fold("'a ' + !1", "'a false'"); fold("'a ' + !0", "'a true'"); } public void testFoldMixed() { fold("''+[1]", "'1'"); foldSame("false+[]"); // would like: "\"false\"" } public void testFoldVoid() { foldSame("void 0"); fold("void 1", "void 0"); fold("void x", "void 0"); fold("void x()", "void x()"); } public void testObjectLiteral() { test("(!{})", "false"); test("(!{a:1})", "false"); testSame("(!{a:foo()})"); testSame("(!{'a':foo()})"); } public void testArrayLiteral() { test("(![])", "false"); test("(![1])", "false"); test("(![a])", "false"); testSame("(![foo()])"); } public void testIssue601() { testSame("'\\v' == 'v'"); testSame("'v' == '\\v'"); testSame("'\\u000B' == '\\v'"); } public void testFoldObjectLiteralRef1() { // Leave extra side-effects in place testSame("var x = ({a:foo(),b:bar()}).a"); testSame("var x = ({a:1,b:bar()}).a"); testSame("function f() { return {b:foo(), a:2}.a; }"); // on the LHS the object act as a temporary leave it in place. testSame("({a:x}).a = 1"); test("({a:x}).a += 1", "({a:x}).a = x + 1"); testSame("({a:x}).a ++"); testSame("({a:x}).a --"); // functions can't reference the object through 'this'. testSame("({a:function(){return this}}).a"); testSame("({get a() {return this}}).a"); testSame("({set a(b) {return this}}).a"); // Leave unknown props alone, the might be on the prototype testSame("({}).a"); // setters by themselves don't provide a definition testSame("({}).a"); testSame("({set a(b) {}}).a"); // sets don't hide other definitions. test("({a:1,set a(b) {}}).a", "1"); // get is transformed to a call (gets don't have self referential names) test("({get a() {}}).a", "(function (){})()"); // sets don't hide other definitions. test("({get a() {},set a(b) {}}).a", "(function (){})()"); // a function remains a function not a call. test("var x = ({a:function(){return 1}}).a", "var x = function(){return 1}"); test("var x = ({a:1}).a", "var x = 1"); test("var x = ({a:1, a:2}).a", "var x = 2"); test("var x = ({a:1, a:foo()}).a", "var x = foo()"); test("var x = ({a:foo()}).a", "var x = foo()"); test("function f() { return {a:1, b:2}.a; }", "function f() { return 1; }"); // GETELEM is handled the same way. test("var x = ({'a':1})['a']", "var x = 1"); } public void testFoldObjectLiteralRef2() { late = false; test("({a:x}).a += 1", "({a:x}).a = x + 1"); late = true; testSame("({a:x}).a += 1"); } public void testIEString() { testSame("!+'\\v1'"); } public void testIssue522() { testSame("[][1] = 1;"); } private static final List<String> LITERAL_OPERANDS = ImmutableList.of( "null", "undefined", "void 0", "true", "false", "!0", "!1", "0", "1", "''", "'123'", "'abc'", "'def'", "NaN", "Infinity", // TODO(nicksantos): Add more literals "-Infinity" //"({})", // "[]" //"[0]", //"Object", //"(function() {})" ); public void testInvertibleOperators() { Map<String, String> inverses = ImmutableMap.<String, String>builder() .put("==", "!=") .put("===", "!==") .put("<=", ">") .put("<", ">=") .put(">=", "<") .put(">", "<=") .put("!=", "==") .put("!==", "===") .build(); Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">"); Set<String> equalitors = ImmutableSet.of("==", "==="); Set<String> uncomparables = ImmutableSet.of("undefined", "void 0"); List<String> operators = ImmutableList.copyOf(inverses.values()); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = 0; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); String inverse = inverses.get(op); // Test invertability. if (comparators.contains(op) && (uncomparables.contains(a) || uncomparables.contains(b))) { assertSameResults(join(a, op, b), "false"); assertSameResults(join(a, inverse, b), "false"); } else if (a.equals(b) && equalitors.contains(op)) { if (a.equals("NaN") || a.equals("Infinity") || a.equals("-Infinity")) { foldSame(join(a, op, b)); foldSame(join(a, inverse, b)); } else { assertSameResults(join(a, op, b), "true"); assertSameResults(join(a, inverse, b), "false"); } } else { assertNotSameResults(join(a, op, b), join(a, inverse, b)); } } } } } public void testCommutativeOperators() { late = true; List<String> operators = ImmutableList.of( "==", "!=", "===", "!==", "*", "|", "&", "^"); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = iOperandA; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); // Test commutativity. // TODO(nicksantos): Eventually, all cases should be collapsed. assertSameResultsOrUncollapsed(join(a, op, b), join(b, op, a)); } } } } public void testConvertToNumberNegativeInf() { foldSame("var x = 3 * (r ? Infinity : -Infinity);"); } private String join(String operandA, String op, String operandB) { return operandA + " " + op + " " + operandB; } private void assertSameResultsOrUncollapsed(String exprA, String exprB) { String resultA = process(exprA); String resultB = process(exprB); // TODO: why is nothing done with this? if (resultA.equals(print(exprA))) { foldSame(exprA); foldSame(exprB); } else { assertSameResults(exprA, exprB); } } private void assertSameResults(String exprA, String exprB) { assertEquals( "Expressions did not fold the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA), process(exprB)); } private void assertNotSameResults(String exprA, String exprB) { assertFalse( "Expressions folded the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA).equals(process(exprB))); } private String process(String js) { return printHelper(js, true); } private String print(String js) { return printHelper(js, false); } private String printHelper(String js, boolean runProcessor) { Compiler compiler = createCompiler(); CompilerOptions options = getOptions(); compiler.init( ImmutableList.<SourceFile>of(), ImmutableList.of(SourceFile.fromCode("testcode", js)), options); Node root = compiler.parseInputs(); assertTrue("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()) + "\nEXPR: " + js, root != null); Node externsRoot = root.getFirstChild(); Node mainRoot = externsRoot.getNext(); if (runProcessor) { getProcessor(compiler).process(externsRoot, mainRoot); } return compiler.toSource(mainRoot); } }
@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()); }
org.jsoup.nodes.ElementTest::testElementSiblingIndexSameContent
src/test/java/org/jsoup/nodes/ElementTest.java
157
src/test/java/org/jsoup/nodes/ElementTest.java
testElementSiblingIndexSameContent
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.Map; /** * 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 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 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"); 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 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 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 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, 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<Node>(); 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<String>(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 testHashAndEquals() { 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, e1); assertEquals(e0, e4); assertEquals(e0, e5); assertFalse(e0.equals(e2)); assertFalse(e0.equals(e3)); assertFalse(e0.equals(e6)); assertFalse(e0.equals(e7)); assertEquals(e0.hashCode(), e1.hashCode()); assertEquals(e0.hashCode(), e4.hashCode()); assertEquals(e0.hashCode(), e5.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } }
// You are a professional Java test case writer, please create a test case named `testElementSiblingIndexSameContent` for the issue `Jsoup-554`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-554 // // ## Issue-Title: // Unexpected behavior in elementSiblingIndex // // ## Issue-Description: // The documentation for elementSiblingIndex states "Get the list index of this element in its element sibling list. I.e. if this is the first element sibling, returns 0". // // // This would imply that if // // // // ``` // n=myElem.elementSiblingIndex(); // // ``` // // then // // // // ``` // myElem.parent().children().get(n)==myElem. // // ``` // // However, this is not how elementSiblingIndex behaves. What is guaranteed is that // // // // ``` // myElem.parent().children().get(n).equals(myElem). // // ``` // // For example, if both row 2 and row 5 of a table are // // // // ``` // <tr><td>Cell1</td><td>Cell2</td></tr> // // ``` // // then the Element object associated with both rows will have the same `elementSiblingIndex()`. // // // // @Test public void testElementSiblingIndexSameContent() {
157
43
151
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-554 ## Issue-Title: Unexpected behavior in elementSiblingIndex ## Issue-Description: The documentation for elementSiblingIndex states "Get the list index of this element in its element sibling list. I.e. if this is the first element sibling, returns 0". This would imply that if ``` n=myElem.elementSiblingIndex(); ``` then ``` myElem.parent().children().get(n)==myElem. ``` However, this is not how elementSiblingIndex behaves. What is guaranteed is that ``` myElem.parent().children().get(n).equals(myElem). ``` For example, if both row 2 and row 5 of a table are ``` <tr><td>Cell1</td><td>Cell2</td></tr> ``` then the Element object associated with both rows will have the same `elementSiblingIndex()`. ``` You are a professional Java test case writer, please create a test case named `testElementSiblingIndexSameContent` for the issue `Jsoup-554`, utilizing the provided issue report information and the following function signature. ```java @Test public void testElementSiblingIndexSameContent() { ```
151
[ "org.jsoup.nodes.Element" ]
cf74c190d338428dbedb4c78d95ca9f4bcdf1984bee267d61ca62f31c9d2c312
@Test public void testElementSiblingIndexSameContent()
// You are a professional Java test case writer, please create a test case named `testElementSiblingIndexSameContent` for the issue `Jsoup-554`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-554 // // ## Issue-Title: // Unexpected behavior in elementSiblingIndex // // ## Issue-Description: // The documentation for elementSiblingIndex states "Get the list index of this element in its element sibling list. I.e. if this is the first element sibling, returns 0". // // // This would imply that if // // // // ``` // n=myElem.elementSiblingIndex(); // // ``` // // then // // // // ``` // myElem.parent().children().get(n)==myElem. // // ``` // // However, this is not how elementSiblingIndex behaves. What is guaranteed is that // // // // ``` // myElem.parent().children().get(n).equals(myElem). // // ``` // // For example, if both row 2 and row 5 of a table are // // // // ``` // <tr><td>Cell1</td><td>Cell2</td></tr> // // ``` // // then the Element object associated with both rows will have the same `elementSiblingIndex()`. // // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.Map; /** * 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 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 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"); 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 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 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 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, 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<Node>(); 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<String>(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 testHashAndEquals() { 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, e1); assertEquals(e0, e4); assertEquals(e0, e5); assertFalse(e0.equals(e2)); assertFalse(e0.equals(e3)); assertFalse(e0.equals(e6)); assertFalse(e0.equals(e7)); assertEquals(e0.hashCode(), e1.hashCode()); assertEquals(e0.hashCode(), e4.hashCode()); assertEquals(e0.hashCode(), e5.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } }
public void testIssue522() { testSame("[][1] = 1;"); }
com.google.javascript.jscomp.PeepholeFoldConstantsTest::testIssue522
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
927
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
testIssue522
/* * 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.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.javascript.rhino.Node; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link PeepholeFoldConstants} in isolation. Tests for * the interaction of multiple peephole passes are in * {@link PeepholeIntegrationTest}. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison1() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUndefinedComparison2() { fold("\"123\" !== void 0", "true"); fold("\"123\" === void 0", "false"); fold("void 0 !== \"123\"", "true"); fold("void 0 === \"123\"", "false"); } public void testUndefinedComparison3() { fold("\"123\" !== undefined", "true"); fold("\"123\" === undefined", "false"); fold("undefined !== \"123\"", "true"); fold("undefined === \"123\"", "false"); } public void testUndefinedComparison4() { fold("1 !== void 0", "true"); fold("1 === void 0", "false"); fold("null !== void 0", "true"); fold("null === void 0", "false"); fold("undefined !== void 0", "false"); fold("undefined === void 0", "true"); } public void testUnaryOps() { // These cases are handled by PeepholeRemoveDeadCode. foldSame("!foo()"); foldSame("~foo()"); foldSame("-foo()"); // These cases are handled here. fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); foldSame("a=+foo()"); foldSame("a=+f"); fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable fold("a=+0", "a=0"); fold("a=+Infinity", "a=Infinity"); fold("a=+NaN", "a=NaN"); fold("a=+-7", "a=-7"); fold("a=+.5", "a=.5"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); foldSame("x = [foo()] && x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // unfoldable, because the right-side may be the result fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // folded, but not here. foldSame("a = x || false ? b : c"); foldSame("a = x && true ? b : c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); fold("1 && b()", "b()"); fold("a() && (1 && b())", "a() && b()"); // TODO(johnlenz): Consider folding the following to: // "(a(),1) && b(); fold("(a() && 1) && b()", "(a() && 1) && b()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = 1 ^ 1", "x = 0"); fold("x = 1 ^ 2", "x = 3"); fold("x = 3 ^ 1", "x = 2"); fold("x = 3 ^ 3", "x = 0"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1"); fold("x = 1.1 & 1", "x = 1"); fold("x = 1 & 3000000000", "x = 0"); fold("x = 3000000000 & 1", "x = 0"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1"); foldSame("x = 1 | 3E9"); fold("x = 1 | 3000000001", "x = -1294967295"); } public void testFoldBitwiseOp2() { fold("x = y & 1 & 1", "x = y & 1"); fold("x = y & 1 & 2", "x = y & 0"); fold("x = y & 3 & 1", "x = y & 1"); fold("x = 3 & y & 1", "x = y & 1"); fold("x = y & 3 & 3", "x = y & 3"); fold("x = 3 & y & 3", "x = y & 3"); fold("x = y | 1 | 1", "x = y | 1"); fold("x = y | 1 | 2", "x = y | 3"); fold("x = y | 3 | 1", "x = y | 3"); fold("x = 3 | y | 1", "x = y | 3"); fold("x = y | 3 | 3", "x = y | 3"); fold("x = 3 | y | 3", "x = y | 3"); fold("x = y ^ 1 ^ 1", "x = y ^ 0"); fold("x = y ^ 1 ^ 2", "x = y ^ 3"); fold("x = y ^ 3 ^ 1", "x = y ^ 2"); fold("x = 3 ^ y ^ 1", "x = y ^ 2"); fold("x = y ^ 3 ^ 3", "x = y ^ 0"); fold("x = 3 ^ y ^ 3", "x = y ^ 0"); fold("x = Infinity | NaN", "x=0"); fold("x = 12 | NaN", "x=12"); } public void testFoldingMixTypes() { fold("x = x + '2'", "x+='2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x-=2"); fold("x = x ^ '2'", "x^=2"); fold("x = '2' ^ x", "x^=2"); fold("x = '2' & x", "x&=2"); fold("x = '2' | x", "x|=2"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingAdd() { fold("x = null + true", "x=1"); foldSame("x = a + true"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can) } public void testFoldConstructor() { fold("x = this[new String('a')]", "x = this['a']"); fold("x = ob[new String(12)]", "x = ob['12']"); fold("x = ob[new String(false)]", "x = ob['false']"); fold("x = ob[new String(null)]", "x = ob['null']"); foldSame("x = ob[new String(a)]"); foldSame("x = new String('a')"); foldSame("x = (new String('a'))[3]"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); fold("x = 1 % 0", "x = 1 % 0"); } public void testFoldArithmetic2() { foldSame("x = y + 10 + 20"); foldSame("x = y / 2 / 4"); fold("x = y * 2.25 * 3", "x = y * 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5"); } public void testFoldArithmetic3() { fold("x = null * undefined", "x = NaN"); fold("x = null * 1", "x = 0"); fold("x = (null - 1) * 2", "x = -2"); fold("x = (null + 1) * 2", "x = 2"); } public void testFoldArithmeticInfinity() { fold("x=-Infinity-2", "x=-Infinity"); fold("x=Infinity-2", "x=Infinity"); fold("x=Infinity*5", "x=Infinity"); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = false == false", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = false === false", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldComparison3() { fold("x = !1 == !0", "x = false"); fold("x = !0 == !0", "x = true"); fold("x = !1 == !1", "x = true"); fold("x = !1 == null", "x = false"); fold("x = !1 == !0", "x = false"); fold("x = !0 == null", "x = false"); fold("!0 == !0", "true"); fold("!1 == null", "false"); fold("!1 == !0", "false"); fold("!0 == null", "false"); fold("x = !0 === !0", "x = true"); fold("x = !1 === !1", "x = true"); fold("x = !1 === null", "x = false"); fold("x = !1 === !0", "x = false"); fold("x = !0 === null", "x = false"); fold("!0 === !0", "true"); fold("!1 === null", "false"); fold("!1 === !0", "false"); fold("!0 === null", "false"); } public void testFoldGetElem() { fold("x = [,10][0]", "x = void 0"); fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldLeft() { foldSame("(+x - 1) + 2"); // not yet fold("(+x + 1) + 2", "+x + 3"); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Not handled yet fold("x = [,,1].length", "x = 3"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); fold("x = typeof function() {}", "x = 'function'"); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("!0 instanceof Object", "false"); fold("!0 instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); fold("(function() {}) instanceof Object", "true"); // An unknown value should never be folded. foldSame("x instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOps() { fold("x=x+y", "x+=y"); foldSame("x=y+x"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); fold("x=x-y", "x-=y"); foldSame("x=y-x"); fold("x=x|y", "x|=y"); fold("x=y|x", "x|=y"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); } public void testFoldAdd1() { fold("x=false+1","x=1"); fold("x=true+1","x=2"); fold("x=1+false","x=1"); fold("x=1+true","x=2"); } public void testFoldLiteralNames() { foldSame("NaN == NaN"); foldSame("Infinity == Infinity"); foldSame("Infinity == NaN"); fold("undefined == NaN", "false"); fold("undefined == Infinity", "false"); foldSame("Infinity >= Infinity"); foldSame("NaN >= NaN"); } public void testFoldLiteralsTypeMismatches() { fold("true == true", "true"); fold("true == false", "false"); fold("true == null", "false"); fold("false == null", "false"); // relational operators convert its operands fold("null <= null", "true"); // 0 = 0 fold("null >= null", "true"); fold("null > null", "false"); fold("null < null", "false"); fold("false >= null", "true"); // 0 = 0 fold("false <= null", "true"); fold("false > null", "false"); fold("false < null", "false"); fold("true >= null", "true"); // 1 > 0 fold("true <= null", "false"); fold("true > null", "true"); fold("true < null", "false"); fold("true >= false", "true"); // 1 > 0 fold("true <= false", "false"); fold("true > false", "true"); fold("true < false", "false"); } public void testFoldLeftChildConcat() { foldSame("x +5 + \"1\""); fold("x+\"5\" + \"1\"", "x + \"51\""); // fold("\"a\"+(c+\"b\")","\"a\"+c+\"b\""); fold("\"a\"+(\"b\"+c)","\"ab\"+c"); } public void testFoldLeftChildOp() { fold("x * Infinity * 2", "x * Infinity"); foldSame("x - Infinity - 2"); // want "x-Infinity" foldSame("x - 1 + Infinity"); foldSame("x - 2 + 1"); foldSame("x - 2 + 3"); foldSame("1 + x - 2 + 1"); foldSame("1 + x - 2 + 3"); foldSame("1 + x - 2 + 3 - 1"); foldSame("f(x)-0"); foldSame("x-0-0"); foldSame("x+2-2+2"); foldSame("x+2-2+2-2"); foldSame("x-2+2"); foldSame("x-2+2-2"); foldSame("x-2+2-2+2"); foldSame("1+x-0-NaN"); foldSame("1+f(x)-0-NaN"); foldSame("1+x-0+NaN"); foldSame("1+f(x)-0+NaN"); foldSame("1+x+NaN"); // unfoldable foldSame("x+2-2"); // unfoldable foldSame("x+2"); // nothing to do foldSame("x-2"); // nothing to do } public void testFoldSimpleArithmeticOp() { foldSame("x*NaN"); foldSame("NaN/y"); foldSame("f(x)-0"); foldSame("f(x)*1"); foldSame("1*f(x)"); foldSame("0+a+b"); foldSame("0-a-b"); foldSame("a+b-0"); foldSame("(1+x)*NaN"); foldSame("(1+f(x))*NaN"); // don't fold side-effects } public void testFoldLiteralsAsNumbers() { fold("x/'12'","x/12"); fold("x/('12'+'6')", "x/126"); fold("true*x", "1*x"); fold("x/false", "x/0"); // should we add an error check? :) } public void testNotFoldBackToTrueFalse() { foldSame("!0"); foldSame("!1"); fold("!3", "false"); } public void testFoldBangConstants() { fold("1 + !0", "2"); fold("1 + !1", "1"); fold("'a ' + !1", "'a false'"); fold("'a ' + !0", "'a true'"); } public void testFoldMixed() { fold("''+[1]", "'1'"); foldSame("false+[]"); // would like: "\"false\"" } public void testFoldVoid() { foldSame("void 0"); fold("void 1", "void 0"); fold("void x", "void 0"); fold("void x()", "void x()"); } public void testObjectLiteral() { test("(!{})", "false"); test("(!{a:1})", "false"); testSame("(!{a:foo()})"); testSame("(!{'a':foo()})"); } public void testArrayLiteral() { test("(![])", "false"); test("(![1])", "false"); test("(![a])", "false"); testSame("(![foo()])"); } public void testFoldObjectLiteralRef() { // Leave extra side-effects in place testSame("var x = ({a:foo(),b:bar()}).a"); testSame("var x = ({a:1,b:bar()}).a"); testSame("function f() { return {b:foo(), a:2}.a; }"); // on the LHS the object act as a temporary leave it in place. testSame("({a:x}).a = 1"); testSame("({a:x}).a += 1"); testSame("({a:x}).a ++"); testSame("({a:x}).a --"); // functions can't reference the object through 'this'. testSame("({a:function(){return this}}).a"); testSame("({get a() {return this}}).a"); testSame("({set a(b) {return this}}).a"); // Leave unknown props alone, the might be on the prototype testSame("({}).a"); // setters by themselves don't provide a definition testSame("({}).a"); testSame("({set a(b) {}}).a"); // sets don't hide other definitions. test("({a:1,set a(b) {}}).a", "1"); // get is transformed to a call (gets don't have self referential names) test("({get a() {}}).a", "(function (){})()"); // sets don't hide other definitions. test("({get a() {},set a(b) {}}).a", "(function (){})()"); // a function remains a function not a call. test("var x = ({a:function(){return 1}}).a", "var x = function(){return 1}"); test("var x = ({a:1}).a", "var x = 1"); test("var x = ({a:1, a:2}).a", "var x = 2"); test("var x = ({a:1, a:foo()}).a", "var x = foo()"); test("var x = ({a:foo()}).a", "var x = foo()"); test("function f() { return {a:1, b:2}.a; }", "function f() { return 1; }"); // GETELEM is handled the same way. test("var x = ({'a':1})['a']", "var x = 1"); } public void testIEString() { testSame("!+'\\v1'"); } public void testIssue522() { testSame("[][1] = 1;"); } private static final List<String> LITERAL_OPERANDS = ImmutableList.of( "null", "undefined", "void 0", "true", "false", "!0", "!1", "0", "1", "''", "'123'", "'abc'", "'def'", "NaN", "Infinity" // TODO(nicksantos): Add more literals // "-Infinity", //"({})", // "[]" //"[0]", //"Object", //"(function() {})" ); public void testInvertibleOperators() { Map<String, String> inverses = ImmutableMap.<String, String>builder() .put("==", "!=") .put("===", "!==") .put("<=", ">") .put("<", ">=") .put(">=", "<") .put(">", "<=") .put("!=", "==") .put("!==", "===") .build(); Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">"); Set<String> equalitors = ImmutableSet.of("==", "==="); Set<String> uncomparables = ImmutableSet.of("undefined", "void 0"); List<String> operators = ImmutableList.copyOf(inverses.values()); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = 0; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); String inverse = inverses.get(op); // Test invertability. if (comparators.contains(op) && (uncomparables.contains(a) || uncomparables.contains(b))) { assertSameResults(join(a, op, b), "false"); assertSameResults(join(a, inverse, b), "false"); } else if (a.equals(b) && equalitors.contains(op)) { if (a.equals("NaN") || a.equals("Infinity")) { foldSame(join(a, op, b)); foldSame(join(a, inverse, b)); } else { assertSameResults(join(a, op, b), "true"); assertSameResults(join(a, inverse, b), "false"); } } else { assertNotSameResults(join(a, op, b), join(a, inverse, b)); } } } } } public void testCommutativeOperators() { List<String> operators = ImmutableList.of( "==", "!=", "===", "!==", "*", "|", "&", "^"); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = iOperandA; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); // Test commutativity. // TODO(nicksantos): Eventually, all cases should be collapsed. assertSameResultsOrUncollapsed(join(a, op, b), join(b, op, a)); } } } } private String join(String operandA, String op, String operandB) { return operandA + " " + op + " " + operandB; } private void assertSameResultsOrUncollapsed(String exprA, String exprB) { String resultA = process(exprA); String resultB = process(exprB); // TODO: why is nothing done with this? if (resultA.equals(print(exprA))) { foldSame(exprA); foldSame(exprB); } else { assertSameResults(exprA, exprB); } } private void assertSameResults(String exprA, String exprB) { assertEquals( "Expressions did not fold the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA), process(exprB)); } private void assertNotSameResults(String exprA, String exprB) { assertFalse( "Expressions folded the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA).equals(process(exprB))); } private String process(String js) { return printHelper(js, true); } private String print(String js) { return printHelper(js, false); } private String printHelper(String js, boolean runProcessor) { Compiler compiler = createCompiler(); CompilerOptions options = getOptions(); compiler.init( new JSSourceFile[] {}, new JSSourceFile[] { JSSourceFile.fromCode("testcode", js) }, options); Node root = compiler.parseInputs(); assertTrue("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()) + "\nEXPR: " + js, root != null); Node externsRoot = root.getFirstChild(); Node mainRoot = externsRoot.getNext(); if (runProcessor) { getProcessor(compiler).process(externsRoot, mainRoot); } return compiler.toSource(mainRoot); } }
// You are a professional Java test case writer, please create a test case named `testIssue522` for the issue `Closure-522`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-522 // // ## Issue-Title: // peephole constants folding pass is trying to fold [][11] as if it were a property lookup instead of a property assignment // // ## Issue-Description: // **What steps will reproduce the problem?** // 1.Try on line CC with Advance // 2.On the following 2-line code // **3.** // **What is the expected output? What do you see instead?** // // ==ClosureCompiler== // // @output\_file\_name default.js // // @compilation\_level ADVANCED\_OPTIMIZATIONS // // ==/ClosureCompiler== // // // var Mdt=[]; // Mdt[11] = ['22','19','19','16','21','18','16','20','17','17','21','17']; // // The error: // JSC\_INDEX\_OUT\_OF\_BOUNDS\_ERROR: Array index out of bounds: NUMBER 11.0 // 2 [sourcename: Input\_0] : number at line 2 character 4 // // // **What version of the product are you using? On what operating system?** // The online version on 201.07.27 // // public void testIssue522() {
927
161
925
test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java
test
```markdown ## Issue-ID: Closure-522 ## Issue-Title: peephole constants folding pass is trying to fold [][11] as if it were a property lookup instead of a property assignment ## Issue-Description: **What steps will reproduce the problem?** 1.Try on line CC with Advance 2.On the following 2-line code **3.** **What is the expected output? What do you see instead?** // ==ClosureCompiler== // @output\_file\_name default.js // @compilation\_level ADVANCED\_OPTIMIZATIONS // ==/ClosureCompiler== var Mdt=[]; Mdt[11] = ['22','19','19','16','21','18','16','20','17','17','21','17']; The error: JSC\_INDEX\_OUT\_OF\_BOUNDS\_ERROR: Array index out of bounds: NUMBER 11.0 2 [sourcename: Input\_0] : number at line 2 character 4 **What version of the product are you using? On what operating system?** The online version on 201.07.27 ``` You are a professional Java test case writer, please create a test case named `testIssue522` for the issue `Closure-522`, utilizing the provided issue report information and the following function signature. ```java public void testIssue522() { ```
925
[ "com.google.javascript.jscomp.PeepholeFoldConstants" ]
cf79b0f45567d0dac31983a3d73d79de28eeed7bc9506f2c4e30f301489dd678
public void testIssue522()
// You are a professional Java test case writer, please create a test case named `testIssue522` for the issue `Closure-522`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-522 // // ## Issue-Title: // peephole constants folding pass is trying to fold [][11] as if it were a property lookup instead of a property assignment // // ## Issue-Description: // **What steps will reproduce the problem?** // 1.Try on line CC with Advance // 2.On the following 2-line code // **3.** // **What is the expected output? What do you see instead?** // // ==ClosureCompiler== // // @output\_file\_name default.js // // @compilation\_level ADVANCED\_OPTIMIZATIONS // // ==/ClosureCompiler== // // // var Mdt=[]; // Mdt[11] = ['22','19','19','16','21','18','16','20','17','17','21','17']; // // The error: // JSC\_INDEX\_OUT\_OF\_BOUNDS\_ERROR: Array index out of bounds: NUMBER 11.0 // 2 [sourcename: Input\_0] : number at line 2 character 4 // // // **What version of the product are you using? On what operating system?** // The online version on 201.07.27 // //
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.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.javascript.rhino.Node; import java.util.List; import java.util.Map; import java.util.Set; /** * Tests for {@link PeepholeFoldConstants} in isolation. Tests for * the interaction of multiple peephole passes are in * {@link PeepholeIntegrationTest}. */ public class PeepholeFoldConstantsTest extends CompilerTestCase { // TODO(user): Remove this when we no longer need to do string comparison. private PeepholeFoldConstantsTest(boolean compareAsTree) { super("", compareAsTree); } public PeepholeFoldConstantsTest() { super(""); } @Override public void setUp() { enableLineNumberCheck(true); } @Override public CompilerPass getProcessor(final Compiler compiler) { CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler, new PeepholeFoldConstants()); return peepholePass; } @Override protected int getNumRepetitions() { // Reduce this to 2 if we get better expression evaluators. return 2; } private void foldSame(String js) { testSame(js); } private void fold(String js, String expected) { test(js, expected); } private void fold(String js, String expected, DiagnosticType warning) { test(js, expected, warning); } // TODO(user): This is same as fold() except it uses string comparison. Any // test that needs tell us where a folding is constructing an invalid AST. private void assertResultString(String js, String expected) { PeepholeFoldConstantsTest scTest = new PeepholeFoldConstantsTest(false); scTest.test(js, expected); } public void testUndefinedComparison1() { fold("undefined == undefined", "true"); fold("undefined == null", "true"); fold("undefined == void 0", "true"); fold("undefined == 0", "false"); fold("undefined == 1", "false"); fold("undefined == 'hi'", "false"); fold("undefined == true", "false"); fold("undefined == false", "false"); fold("undefined === undefined", "true"); fold("undefined === null", "false"); fold("undefined === void 0", "true"); foldSame("undefined == this"); foldSame("undefined == x"); fold("undefined != undefined", "false"); fold("undefined != null", "false"); fold("undefined != void 0", "false"); fold("undefined != 0", "true"); fold("undefined != 1", "true"); fold("undefined != 'hi'", "true"); fold("undefined != true", "true"); fold("undefined != false", "true"); fold("undefined !== undefined", "false"); fold("undefined !== void 0", "false"); fold("undefined !== null", "true"); foldSame("undefined != this"); foldSame("undefined != x"); fold("undefined < undefined", "false"); fold("undefined > undefined", "false"); fold("undefined >= undefined", "false"); fold("undefined <= undefined", "false"); fold("0 < undefined", "false"); fold("true > undefined", "false"); fold("'hi' >= undefined", "false"); fold("null <= undefined", "false"); fold("undefined < 0", "false"); fold("undefined > true", "false"); fold("undefined >= 'hi'", "false"); fold("undefined <= null", "false"); fold("null == undefined", "true"); fold("0 == undefined", "false"); fold("1 == undefined", "false"); fold("'hi' == undefined", "false"); fold("true == undefined", "false"); fold("false == undefined", "false"); fold("null === undefined", "false"); fold("void 0 === undefined", "true"); foldSame("this == undefined"); foldSame("x == undefined"); } public void testUndefinedComparison2() { fold("\"123\" !== void 0", "true"); fold("\"123\" === void 0", "false"); fold("void 0 !== \"123\"", "true"); fold("void 0 === \"123\"", "false"); } public void testUndefinedComparison3() { fold("\"123\" !== undefined", "true"); fold("\"123\" === undefined", "false"); fold("undefined !== \"123\"", "true"); fold("undefined === \"123\"", "false"); } public void testUndefinedComparison4() { fold("1 !== void 0", "true"); fold("1 === void 0", "false"); fold("null !== void 0", "true"); fold("null === void 0", "false"); fold("undefined !== void 0", "false"); fold("undefined === void 0", "true"); } public void testUnaryOps() { // These cases are handled by PeepholeRemoveDeadCode. foldSame("!foo()"); foldSame("~foo()"); foldSame("-foo()"); // These cases are handled here. fold("a=!true", "a=false"); fold("a=!10", "a=false"); fold("a=!false", "a=true"); fold("a=!foo()", "a=!foo()"); fold("a=-0", "a=0"); fold("a=-Infinity", "a=-Infinity"); fold("a=-NaN", "a=NaN"); fold("a=-foo()", "a=-foo()"); fold("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); foldSame("a=+foo()"); foldSame("a=+f"); fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable fold("a=+0", "a=0"); fold("a=+Infinity", "a=Infinity"); fold("a=+NaN", "a=NaN"); fold("a=+-7", "a=-7"); fold("a=+.5", "a=.5"); fold("a=~0x100000000", "a=~0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~-0x100000000", "a=~-0x100000000", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("a=~.5", "~.5", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testUnaryOpsStringCompare() { // Negatives are folded into a single number node. assertResultString("a=-1", "a=-1"); assertResultString("a=~0", "a=-1"); assertResultString("a=~1", "a=-2"); assertResultString("a=~101", "a=-102"); } public void testFoldLogicalOp() { fold("x = true && x", "x = x"); foldSame("x = [foo()] && x"); fold("x = false && x", "x = false"); fold("x = true || x", "x = true"); fold("x = false || x", "x = x"); fold("x = 0 && x", "x = 0"); fold("x = 3 || x", "x = 3"); fold("x = false || 0", "x = 0"); // unfoldable, because the right-side may be the result fold("a = x && true", "a=x&&true"); fold("a = x && false", "a=x&&false"); fold("a = x || 3", "a=x||3"); fold("a = x || false", "a=x||false"); fold("a = b ? c : x || false", "a=b?c:x||false"); fold("a = b ? x || false : c", "a=b?x||false:c"); fold("a = b ? c : x && true", "a=b?c:x&&true"); fold("a = b ? x && true : c", "a=b?x&&true:c"); // folded, but not here. foldSame("a = x || false ? b : c"); foldSame("a = x && true ? b : c"); fold("x = foo() || true || bar()", "x = foo()||true"); fold("x = foo() || false || bar()", "x = foo()||bar()"); fold("x = foo() || true && bar()", "x = foo()||bar()"); fold("x = foo() || false && bar()", "x = foo()||false"); fold("x = foo() && false && bar()", "x = foo()&&false"); fold("x = foo() && true && bar()", "x = foo()&&bar()"); fold("x = foo() && false || bar()", "x = foo()&&false||bar()"); fold("1 && b()", "b()"); fold("a() && (1 && b())", "a() && b()"); // TODO(johnlenz): Consider folding the following to: // "(a(),1) && b(); fold("(a() && 1) && b()", "(a() && 1) && b()"); // Really not foldable, because it would change the type of the // expression if foo() returns something equivalent, but not // identical, to true. Cf. FoldConstants.tryFoldAndOr(). foldSame("x = foo() && true || bar()"); foldSame("foo() && true || bar()"); } public void testFoldBitwiseOp() { fold("x = 1 & 1", "x = 1"); fold("x = 1 & 2", "x = 0"); fold("x = 3 & 1", "x = 1"); fold("x = 3 & 3", "x = 3"); fold("x = 1 | 1", "x = 1"); fold("x = 1 | 2", "x = 3"); fold("x = 3 | 1", "x = 3"); fold("x = 3 | 3", "x = 3"); fold("x = 1 ^ 1", "x = 0"); fold("x = 1 ^ 2", "x = 3"); fold("x = 3 ^ 1", "x = 2"); fold("x = 3 ^ 3", "x = 0"); fold("x = -1 & 0", "x = 0"); fold("x = 0 & -1", "x = 0"); fold("x = 1 & 4", "x = 0"); fold("x = 2 & 3", "x = 2"); // make sure we fold only when we are supposed to -- not when doing so would // lose information or when it is performed on nonsensical arguments. fold("x = 1 & 1.1", "x = 1"); fold("x = 1.1 & 1", "x = 1"); fold("x = 1 & 3000000000", "x = 0"); fold("x = 3000000000 & 1", "x = 0"); // Try some cases with | as well fold("x = 1 | 4", "x = 5"); fold("x = 1 | 3", "x = 3"); fold("x = 1 | 1.1", "x = 1"); foldSame("x = 1 | 3E9"); fold("x = 1 | 3000000001", "x = -1294967295"); } public void testFoldBitwiseOp2() { fold("x = y & 1 & 1", "x = y & 1"); fold("x = y & 1 & 2", "x = y & 0"); fold("x = y & 3 & 1", "x = y & 1"); fold("x = 3 & y & 1", "x = y & 1"); fold("x = y & 3 & 3", "x = y & 3"); fold("x = 3 & y & 3", "x = y & 3"); fold("x = y | 1 | 1", "x = y | 1"); fold("x = y | 1 | 2", "x = y | 3"); fold("x = y | 3 | 1", "x = y | 3"); fold("x = 3 | y | 1", "x = y | 3"); fold("x = y | 3 | 3", "x = y | 3"); fold("x = 3 | y | 3", "x = y | 3"); fold("x = y ^ 1 ^ 1", "x = y ^ 0"); fold("x = y ^ 1 ^ 2", "x = y ^ 3"); fold("x = y ^ 3 ^ 1", "x = y ^ 2"); fold("x = 3 ^ y ^ 1", "x = y ^ 2"); fold("x = y ^ 3 ^ 3", "x = y ^ 0"); fold("x = 3 ^ y ^ 3", "x = y ^ 0"); fold("x = Infinity | NaN", "x=0"); fold("x = 12 | NaN", "x=12"); } public void testFoldingMixTypes() { fold("x = x + '2'", "x+='2'"); fold("x = +x + +'2'", "x = +x + 2"); fold("x = x - '2'", "x-=2"); fold("x = x ^ '2'", "x^=2"); fold("x = '2' ^ x", "x^=2"); fold("x = '2' & x", "x&=2"); fold("x = '2' | x", "x|=2"); fold("x = '2' | y", "x=2|y"); fold("x = y | '2'", "x=y|2"); fold("x = y | (a && '2')", "x=y|(a&&2)"); fold("x = y | (a,'2')", "x=y|(a,2)"); fold("x = y | (a?'1':'2')", "x=y|(a?1:2)"); fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)"); } public void testFoldingAdd() { fold("x = null + true", "x=1"); foldSame("x = a + true"); } public void testFoldBitwiseOpStringCompare() { assertResultString("x = -1 | 0", "x=-1"); // EXPR_RESULT case is in in PeepholeIntegrationTest } public void testFoldBitShifts() { fold("x = 1 << 0", "x = 1"); fold("x = -1 << 0", "x = -1"); fold("x = 1 << 1", "x = 2"); fold("x = 3 << 1", "x = 6"); fold("x = 1 << 8", "x = 256"); fold("x = 1 >> 0", "x = 1"); fold("x = -1 >> 0", "x = -1"); fold("x = 1 >> 1", "x = 0"); fold("x = 2 >> 1", "x = 1"); fold("x = 5 >> 1", "x = 2"); fold("x = 127 >> 3", "x = 15"); fold("x = 3 >> 1", "x = 1"); fold("x = 3 >> 2", "x = 0"); fold("x = 10 >> 1", "x = 5"); fold("x = 10 >> 2", "x = 2"); fold("x = 10 >> 5", "x = 0"); fold("x = 10 >>> 1", "x = 5"); fold("x = 10 >>> 2", "x = 2"); fold("x = 10 >>> 5", "x = 0"); fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe fold("3000000000 << 1", "3000000000<<1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 << 32", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1 << -1", "1<<32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("3000000000 >> 1", "3000000000>>1", PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE); fold("1 >> 32", "1>>32", PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS); fold("1.5 << 0", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 << .5", "1.5<<0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >>> 0", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >>> .5", "1.5>>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1.5 >> 0", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); fold("1 >> .5", "1.5>>0", PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND); } public void testFoldBitShiftsStringCompare() { // Negative numbers. assertResultString("x = -1 << 1", "x=-2"); assertResultString("x = -1 << 8", "x=-256"); assertResultString("x = -1 >> 1", "x=-1"); assertResultString("x = -2 >> 1", "x=-1"); assertResultString("x = -1 >> 0", "x=-1"); } public void testStringAdd() { fold("x = 'a' + \"bc\"", "x = \"abc\""); fold("x = 'a' + 5", "x = \"a5\""); fold("x = 5 + 'a'", "x = \"5a\""); fold("x = 'a' + ''", "x = \"a\""); fold("x = \"a\" + foo()", "x = \"a\"+foo()"); fold("x = foo() + 'a' + 'b'", "x = foo()+\"ab\""); fold("x = (foo() + 'a') + 'b'", "x = foo()+\"ab\""); // believe it! fold("x = foo() + 'a' + 'b' + 'cd' + bar()", "x = foo()+\"abcd\"+bar()"); fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold! fold("x = foo() + 'a' + 2", "x = foo()+\"a2\""); fold("x = '' + null", "x = \"null\""); fold("x = true + '' + false", "x = \"truefalse\""); fold("x = '' + []", "x = ''"); // cannot fold (but nice if we can) } public void testFoldConstructor() { fold("x = this[new String('a')]", "x = this['a']"); fold("x = ob[new String(12)]", "x = ob['12']"); fold("x = ob[new String(false)]", "x = ob['false']"); fold("x = ob[new String(null)]", "x = ob['null']"); foldSame("x = ob[new String(a)]"); foldSame("x = new String('a')"); foldSame("x = (new String('a'))[3]"); } public void testFoldArithmetic() { fold("x = 10 + 20", "x = 30"); fold("x = 2 / 4", "x = 0.5"); fold("x = 2.25 * 3", "x = 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = 1 / 0", "x = 1 / 0"); fold("x = 3 % 2", "x = 1"); fold("x = 3 % -2", "x = 1"); fold("x = -1 % 3", "x = -1"); fold("x = 1 % 0", "x = 1 % 0"); } public void testFoldArithmetic2() { foldSame("x = y + 10 + 20"); foldSame("x = y / 2 / 4"); fold("x = y * 2.25 * 3", "x = y * 6.75"); fold("z = x * y", "z = x * y"); fold("x = y * 5", "x = y * 5"); fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 864E5"); } public void testFoldArithmetic3() { fold("x = null * undefined", "x = NaN"); fold("x = null * 1", "x = 0"); fold("x = (null - 1) * 2", "x = -2"); fold("x = (null + 1) * 2", "x = 2"); } public void testFoldArithmeticInfinity() { fold("x=-Infinity-2", "x=-Infinity"); fold("x=Infinity-2", "x=Infinity"); fold("x=Infinity*5", "x=Infinity"); } public void testFoldArithmeticStringComp() { // Negative Numbers. assertResultString("x = 10 - 20", "x=-10"); } public void testFoldComparison() { fold("x = 0 == 0", "x = true"); fold("x = 1 == 2", "x = false"); fold("x = 'abc' == 'def'", "x = false"); fold("x = 'abc' == 'abc'", "x = true"); fold("x = \"\" == ''", "x = true"); fold("x = foo() == bar()", "x = foo()==bar()"); fold("x = 1 != 0", "x = true"); fold("x = 'abc' != 'def'", "x = true"); fold("x = 'a' != 'a'", "x = false"); fold("x = 1 < 20", "x = true"); fold("x = 3 < 3", "x = false"); fold("x = 10 > 1.0", "x = true"); fold("x = 10 > 10.25", "x = false"); fold("x = y == y", "x = y==y"); fold("x = y < y", "x = false"); fold("x = y > y", "x = false"); fold("x = 1 <= 1", "x = true"); fold("x = 1 <= 0", "x = false"); fold("x = 0 >= 0", "x = true"); fold("x = -1 >= 9", "x = false"); fold("x = true == true", "x = true"); fold("x = false == false", "x = true"); fold("x = false == null", "x = false"); fold("x = false == true", "x = false"); fold("x = true == null", "x = false"); fold("0 == 0", "true"); fold("1 == 2", "false"); fold("'abc' == 'def'", "false"); fold("'abc' == 'abc'", "true"); fold("\"\" == ''", "true"); foldSame("foo() == bar()"); fold("1 != 0", "true"); fold("'abc' != 'def'", "true"); fold("'a' != 'a'", "false"); fold("1 < 20", "true"); fold("3 < 3", "false"); fold("10 > 1.0", "true"); fold("10 > 10.25", "false"); foldSame("x == x"); fold("x < x", "false"); fold("x > x", "false"); fold("1 <= 1", "true"); fold("1 <= 0", "false"); fold("0 >= 0", "true"); fold("-1 >= 9", "false"); fold("true == true", "true"); fold("false == null", "false"); fold("false == true", "false"); fold("true == null", "false"); } // ===, !== comparison tests public void testFoldComparison2() { fold("x = 0 === 0", "x = true"); fold("x = 1 === 2", "x = false"); fold("x = 'abc' === 'def'", "x = false"); fold("x = 'abc' === 'abc'", "x = true"); fold("x = \"\" === ''", "x = true"); fold("x = foo() === bar()", "x = foo()===bar()"); fold("x = 1 !== 0", "x = true"); fold("x = 'abc' !== 'def'", "x = true"); fold("x = 'a' !== 'a'", "x = false"); fold("x = y === y", "x = y===y"); fold("x = true === true", "x = true"); fold("x = false === false", "x = true"); fold("x = false === null", "x = false"); fold("x = false === true", "x = false"); fold("x = true === null", "x = false"); fold("0 === 0", "true"); fold("1 === 2", "false"); fold("'abc' === 'def'", "false"); fold("'abc' === 'abc'", "true"); fold("\"\" === ''", "true"); foldSame("foo() === bar()"); // TODO(johnlenz): It would be nice to handle these cases as well. foldSame("1 === '1'"); foldSame("1 === true"); foldSame("1 !== '1'"); foldSame("1 !== true"); fold("1 !== 0", "true"); fold("'abc' !== 'def'", "true"); fold("'a' !== 'a'", "false"); foldSame("x === x"); fold("true === true", "true"); fold("false === null", "false"); fold("false === true", "false"); fold("true === null", "false"); } public void testFoldComparison3() { fold("x = !1 == !0", "x = false"); fold("x = !0 == !0", "x = true"); fold("x = !1 == !1", "x = true"); fold("x = !1 == null", "x = false"); fold("x = !1 == !0", "x = false"); fold("x = !0 == null", "x = false"); fold("!0 == !0", "true"); fold("!1 == null", "false"); fold("!1 == !0", "false"); fold("!0 == null", "false"); fold("x = !0 === !0", "x = true"); fold("x = !1 === !1", "x = true"); fold("x = !1 === null", "x = false"); fold("x = !1 === !0", "x = false"); fold("x = !0 === null", "x = false"); fold("!0 === !0", "true"); fold("!1 === null", "false"); fold("!1 === !0", "false"); fold("!0 === null", "false"); } public void testFoldGetElem() { fold("x = [,10][0]", "x = void 0"); fold("x = [10, 20][0]", "x = 10"); fold("x = [10, 20][1]", "x = 20"); fold("x = [10, 20][0.5]", "", PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR); fold("x = [10, 20][-1]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); fold("x = [10, 20][2]", "", PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR); } public void testFoldComplex() { fold("x = (3 / 1.0) + (1 * 2)", "x = 5"); fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true"); fold("x = 'abc' + 5 + 10", "x = \"abc510\""); } public void testFoldLeft() { foldSame("(+x - 1) + 2"); // not yet fold("(+x + 1) + 2", "+x + 3"); } public void testFoldArrayLength() { // Can fold fold("x = [].length", "x = 0"); fold("x = [1,2,3].length", "x = 3"); fold("x = [a,b].length", "x = 2"); // Not handled yet fold("x = [,,1].length", "x = 3"); // Cannot fold fold("x = [foo(), 0].length", "x = [foo(),0].length"); fold("x = y.length", "x = y.length"); } public void testFoldStringLength() { // Can fold basic strings. fold("x = ''.length", "x = 0"); fold("x = '123'.length", "x = 3"); // Test unicode escapes are accounted for. fold("x = '123\u01dc'.length", "x = 4"); } public void testFoldTypeof() { fold("x = typeof 1", "x = \"number\""); fold("x = typeof 'foo'", "x = \"string\""); fold("x = typeof true", "x = \"boolean\""); fold("x = typeof false", "x = \"boolean\""); fold("x = typeof null", "x = \"object\""); fold("x = typeof undefined", "x = \"undefined\""); fold("x = typeof void 0", "x = \"undefined\""); fold("x = typeof []", "x = \"object\""); fold("x = typeof [1]", "x = \"object\""); fold("x = typeof [1,[]]", "x = \"object\""); fold("x = typeof {}", "x = \"object\""); fold("x = typeof function() {}", "x = 'function'"); foldSame("x = typeof[1,[foo()]]"); foldSame("x = typeof{bathwater:baby()}"); } public void testFoldInstanceOf() { // Non object types are never instances of anything. fold("64 instanceof Object", "false"); fold("64 instanceof Number", "false"); fold("'' instanceof Object", "false"); fold("'' instanceof String", "false"); fold("true instanceof Object", "false"); fold("true instanceof Boolean", "false"); fold("!0 instanceof Object", "false"); fold("!0 instanceof Boolean", "false"); fold("false instanceof Object", "false"); fold("null instanceof Object", "false"); fold("undefined instanceof Object", "false"); fold("NaN instanceof Object", "false"); fold("Infinity instanceof Object", "false"); // Array and object literals are known to be objects. fold("[] instanceof Object", "true"); fold("({}) instanceof Object", "true"); // These cases is foldable, but no handled currently. foldSame("new Foo() instanceof Object"); // These would require type information to fold. foldSame("[] instanceof Foo"); foldSame("({}) instanceof Foo"); fold("(function() {}) instanceof Object", "true"); // An unknown value should never be folded. foldSame("x instanceof Foo"); } public void testDivision() { // Make sure the 1/3 does not expand to 0.333333 fold("print(1/3)", "print(1/3)"); // Decimal form is preferable to fraction form when strings are the // same length. fold("print(1/2)", "print(0.5)"); } public void testAssignOps() { fold("x=x+y", "x+=y"); foldSame("x=y+x"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); fold("x=x-y", "x-=y"); foldSame("x=y-x"); fold("x=x|y", "x|=y"); fold("x=y|x", "x|=y"); fold("x=x*y", "x*=y"); fold("x=y*x", "x*=y"); fold("x.y=x.y+z", "x.y+=z"); foldSame("next().x = next().x + 1"); } public void testFoldAdd1() { fold("x=false+1","x=1"); fold("x=true+1","x=2"); fold("x=1+false","x=1"); fold("x=1+true","x=2"); } public void testFoldLiteralNames() { foldSame("NaN == NaN"); foldSame("Infinity == Infinity"); foldSame("Infinity == NaN"); fold("undefined == NaN", "false"); fold("undefined == Infinity", "false"); foldSame("Infinity >= Infinity"); foldSame("NaN >= NaN"); } public void testFoldLiteralsTypeMismatches() { fold("true == true", "true"); fold("true == false", "false"); fold("true == null", "false"); fold("false == null", "false"); // relational operators convert its operands fold("null <= null", "true"); // 0 = 0 fold("null >= null", "true"); fold("null > null", "false"); fold("null < null", "false"); fold("false >= null", "true"); // 0 = 0 fold("false <= null", "true"); fold("false > null", "false"); fold("false < null", "false"); fold("true >= null", "true"); // 1 > 0 fold("true <= null", "false"); fold("true > null", "true"); fold("true < null", "false"); fold("true >= false", "true"); // 1 > 0 fold("true <= false", "false"); fold("true > false", "true"); fold("true < false", "false"); } public void testFoldLeftChildConcat() { foldSame("x +5 + \"1\""); fold("x+\"5\" + \"1\"", "x + \"51\""); // fold("\"a\"+(c+\"b\")","\"a\"+c+\"b\""); fold("\"a\"+(\"b\"+c)","\"ab\"+c"); } public void testFoldLeftChildOp() { fold("x * Infinity * 2", "x * Infinity"); foldSame("x - Infinity - 2"); // want "x-Infinity" foldSame("x - 1 + Infinity"); foldSame("x - 2 + 1"); foldSame("x - 2 + 3"); foldSame("1 + x - 2 + 1"); foldSame("1 + x - 2 + 3"); foldSame("1 + x - 2 + 3 - 1"); foldSame("f(x)-0"); foldSame("x-0-0"); foldSame("x+2-2+2"); foldSame("x+2-2+2-2"); foldSame("x-2+2"); foldSame("x-2+2-2"); foldSame("x-2+2-2+2"); foldSame("1+x-0-NaN"); foldSame("1+f(x)-0-NaN"); foldSame("1+x-0+NaN"); foldSame("1+f(x)-0+NaN"); foldSame("1+x+NaN"); // unfoldable foldSame("x+2-2"); // unfoldable foldSame("x+2"); // nothing to do foldSame("x-2"); // nothing to do } public void testFoldSimpleArithmeticOp() { foldSame("x*NaN"); foldSame("NaN/y"); foldSame("f(x)-0"); foldSame("f(x)*1"); foldSame("1*f(x)"); foldSame("0+a+b"); foldSame("0-a-b"); foldSame("a+b-0"); foldSame("(1+x)*NaN"); foldSame("(1+f(x))*NaN"); // don't fold side-effects } public void testFoldLiteralsAsNumbers() { fold("x/'12'","x/12"); fold("x/('12'+'6')", "x/126"); fold("true*x", "1*x"); fold("x/false", "x/0"); // should we add an error check? :) } public void testNotFoldBackToTrueFalse() { foldSame("!0"); foldSame("!1"); fold("!3", "false"); } public void testFoldBangConstants() { fold("1 + !0", "2"); fold("1 + !1", "1"); fold("'a ' + !1", "'a false'"); fold("'a ' + !0", "'a true'"); } public void testFoldMixed() { fold("''+[1]", "'1'"); foldSame("false+[]"); // would like: "\"false\"" } public void testFoldVoid() { foldSame("void 0"); fold("void 1", "void 0"); fold("void x", "void 0"); fold("void x()", "void x()"); } public void testObjectLiteral() { test("(!{})", "false"); test("(!{a:1})", "false"); testSame("(!{a:foo()})"); testSame("(!{'a':foo()})"); } public void testArrayLiteral() { test("(![])", "false"); test("(![1])", "false"); test("(![a])", "false"); testSame("(![foo()])"); } public void testFoldObjectLiteralRef() { // Leave extra side-effects in place testSame("var x = ({a:foo(),b:bar()}).a"); testSame("var x = ({a:1,b:bar()}).a"); testSame("function f() { return {b:foo(), a:2}.a; }"); // on the LHS the object act as a temporary leave it in place. testSame("({a:x}).a = 1"); testSame("({a:x}).a += 1"); testSame("({a:x}).a ++"); testSame("({a:x}).a --"); // functions can't reference the object through 'this'. testSame("({a:function(){return this}}).a"); testSame("({get a() {return this}}).a"); testSame("({set a(b) {return this}}).a"); // Leave unknown props alone, the might be on the prototype testSame("({}).a"); // setters by themselves don't provide a definition testSame("({}).a"); testSame("({set a(b) {}}).a"); // sets don't hide other definitions. test("({a:1,set a(b) {}}).a", "1"); // get is transformed to a call (gets don't have self referential names) test("({get a() {}}).a", "(function (){})()"); // sets don't hide other definitions. test("({get a() {},set a(b) {}}).a", "(function (){})()"); // a function remains a function not a call. test("var x = ({a:function(){return 1}}).a", "var x = function(){return 1}"); test("var x = ({a:1}).a", "var x = 1"); test("var x = ({a:1, a:2}).a", "var x = 2"); test("var x = ({a:1, a:foo()}).a", "var x = foo()"); test("var x = ({a:foo()}).a", "var x = foo()"); test("function f() { return {a:1, b:2}.a; }", "function f() { return 1; }"); // GETELEM is handled the same way. test("var x = ({'a':1})['a']", "var x = 1"); } public void testIEString() { testSame("!+'\\v1'"); } public void testIssue522() { testSame("[][1] = 1;"); } private static final List<String> LITERAL_OPERANDS = ImmutableList.of( "null", "undefined", "void 0", "true", "false", "!0", "!1", "0", "1", "''", "'123'", "'abc'", "'def'", "NaN", "Infinity" // TODO(nicksantos): Add more literals // "-Infinity", //"({})", // "[]" //"[0]", //"Object", //"(function() {})" ); public void testInvertibleOperators() { Map<String, String> inverses = ImmutableMap.<String, String>builder() .put("==", "!=") .put("===", "!==") .put("<=", ">") .put("<", ">=") .put(">=", "<") .put(">", "<=") .put("!=", "==") .put("!==", "===") .build(); Set<String> comparators = ImmutableSet.of("<=", "<", ">=", ">"); Set<String> equalitors = ImmutableSet.of("==", "==="); Set<String> uncomparables = ImmutableSet.of("undefined", "void 0"); List<String> operators = ImmutableList.copyOf(inverses.values()); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = 0; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); String inverse = inverses.get(op); // Test invertability. if (comparators.contains(op) && (uncomparables.contains(a) || uncomparables.contains(b))) { assertSameResults(join(a, op, b), "false"); assertSameResults(join(a, inverse, b), "false"); } else if (a.equals(b) && equalitors.contains(op)) { if (a.equals("NaN") || a.equals("Infinity")) { foldSame(join(a, op, b)); foldSame(join(a, inverse, b)); } else { assertSameResults(join(a, op, b), "true"); assertSameResults(join(a, inverse, b), "false"); } } else { assertNotSameResults(join(a, op, b), join(a, inverse, b)); } } } } } public void testCommutativeOperators() { List<String> operators = ImmutableList.of( "==", "!=", "===", "!==", "*", "|", "&", "^"); for (int iOperandA = 0; iOperandA < LITERAL_OPERANDS.size(); iOperandA++) { for (int iOperandB = iOperandA; iOperandB < LITERAL_OPERANDS.size(); iOperandB++) { for (int iOp = 0; iOp < operators.size(); iOp++) { String a = LITERAL_OPERANDS.get(iOperandA); String b = LITERAL_OPERANDS.get(iOperandB); String op = operators.get(iOp); // Test commutativity. // TODO(nicksantos): Eventually, all cases should be collapsed. assertSameResultsOrUncollapsed(join(a, op, b), join(b, op, a)); } } } } private String join(String operandA, String op, String operandB) { return operandA + " " + op + " " + operandB; } private void assertSameResultsOrUncollapsed(String exprA, String exprB) { String resultA = process(exprA); String resultB = process(exprB); // TODO: why is nothing done with this? if (resultA.equals(print(exprA))) { foldSame(exprA); foldSame(exprB); } else { assertSameResults(exprA, exprB); } } private void assertSameResults(String exprA, String exprB) { assertEquals( "Expressions did not fold the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA), process(exprB)); } private void assertNotSameResults(String exprA, String exprB) { assertFalse( "Expressions folded the same\nexprA: " + exprA + "\nexprB: " + exprB, process(exprA).equals(process(exprB))); } private String process(String js) { return printHelper(js, true); } private String print(String js) { return printHelper(js, false); } private String printHelper(String js, boolean runProcessor) { Compiler compiler = createCompiler(); CompilerOptions options = getOptions(); compiler.init( new JSSourceFile[] {}, new JSSourceFile[] { JSSourceFile.fromCode("testcode", js) }, options); Node root = compiler.parseInputs(); assertTrue("Unexpected parse error(s): " + Joiner.on("\n").join(compiler.getErrors()) + "\nEXPR: " + js, root != null); Node externsRoot = root.getFirstChild(); Node mainRoot = externsRoot.getNext(); if (runProcessor) { getProcessor(compiler).process(externsRoot, mainRoot); } return compiler.toSource(mainRoot); } }
public void testIssue423() { test( "(function($) {\n" + " $.fn.multicheck = function(options) {\n" + " initialize.call(this, options);\n" + " };\n" + "\n" + " function initialize(options) {\n" + " options.checkboxes = $(this).siblings(':checkbox');\n" + " preload_check_all.call(this);\n" + " }\n" + "\n" + " function preload_check_all() {\n" + " $(this).data('checkboxes');\n" + " }\n" + "})(jQuery)", "(function($){" + " $.fn.multicheck=function(options$$1){" + " {" + " options$$1.checkboxes=$(this).siblings(\":checkbox\");" + " {" + " $(this).data(\"checkboxes\")" + " }" + " }" + " }" + "})(jQuery)"); }
com.google.javascript.jscomp.InlineFunctionsTest::testIssue423
test/com/google/javascript/jscomp/InlineFunctionsTest.java
1,692
test/com/google/javascript/jscomp/InlineFunctionsTest.java
testIssue423
/* * Copyright 2008 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; /** * Inline function tests. * @author [email protected] (john lenz) */ public class InlineFunctionsTest extends CompilerTestCase { boolean allowGlobalFunctionInlining = true; boolean allowBlockInlining = true; final boolean allowExpressionDecomposition = true; final boolean allowFunctionExpressionInlining = true; final boolean allowLocalFunctionInlining = true; public InlineFunctionsTest() { this.enableNormalize(); this.enableMarkNoSideEffects(); } @Override protected void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(true); allowGlobalFunctionInlining = true; allowBlockInlining = true; } @Override protected CompilerPass getProcessor(Compiler compiler) { compiler.resetUniqueNameId(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), allowGlobalFunctionInlining, allowLocalFunctionInlining, allowBlockInlining); } /** * Returns the number of times the pass should be run before results are * verified. */ @Override protected int getNumRepetitions() { // Some inlining can only be done in mutliple passes. return 3; } public void testInlineEmptyFunction1() { // Empty function, no params. test("function foo(){}" + "foo();", "void 0;"); } public void testInlineEmptyFunction2() { // Empty function, params with no side-effects. test("function foo(){}" + "foo(1, new Date, function(){});", "void 0;"); } public void testInlineEmptyFunction3() { // Empty function, multiple references. test("function foo(){}" + "foo();foo();foo();", "void 0;void 0;void 0"); } public void testInlineEmptyFunction4() { // Empty function, params with side-effects forces block inlining. test("function foo(){}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();}"); } public void testInlineEmptyFunction5() { // Empty function, call params with side-effects in expression can not // be inlined. allowBlockInlining = false; testSame("function foo(){}" + "foo(x());"); } public void testInlineFunctions1() { // As simple a test as we can get. test("function foo(){ return 4 }" + "foo();", "4"); } public void testInlineFunctions2() { // inline simple constants // NOTE: CD is not inlined. test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;CD=function(x){return x+5};x=CD(3);y=4;z=6" ); } public void testInlineFunctions3() { // inline simple constants test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "var CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;x=3+5;y=4;z=6"); } public void testInlineFunctions4() { // don't inline if there are multiple definitions (need DFA for that). test("var t; var AB = function() { return 4 }; " + "function BC() { return 6; }" + "CD = 0;" + "CD = function(x) { return x + 5 }; x = CD(3); y = AB(); z = BC();", "var t;CD=0;CD=function(x){return x+5};x=CD(3);y=4;z=6"); } public void testInlineFunctions5() { // inline additions test("var FOO_FN=function(x,y) { return \"de\" + x + \"nu\" + y };" + "var a = FOO_FN(\"ez\", \"ts\")", "var a=\"de\"+\"ez\"+\"nu\"+\"ts\""); } public void testInlineFunctions6() { // more complex inlines test("function BAR_FN(x, y, z) { return z(foo(x + y)) }" + "alert(BAR_FN(1, 2, baz))", "alert(baz(foo(1+2)))"); } public void testInlineFunctions7() { // inlines appearing multiple times test("function FN(x,y,z){return x+x+y}" + "var b=FN(1,2,3)", "var b=1+1+2"); } public void testInlineFunctions8() { // check correct parenthesization test("function MUL(x,y){return x*y}function ADD(x,y){return x+y}" + "var a=1+MUL(2,3);var b=2*ADD(3,4)", "var a=1+2*3;var b=2*(3+4)"); } public void testInlineFunctions9() { // don't inline if the input parameter is modified. test("function INC(x){return x++}" + "var y=INC(i)", "var y;{var x$$inline_1=i;" + "y=x$$inline_1++}"); } public void testInlineFunctions10() { test("function INC(x){return x++}" + "var y=INC(i);y=INC(i)", "var y;" + "{var x$$inline_1=i;" + "y=x$$inline_1++}" + "{var x$$inline_4=i;" + "y=x$$inline_4++}"); } public void testInlineFunctions11() { test("function f(x){return x}" + "var y=f(i)", "var y=i"); } public void testInlineFunctions12() { // don't inline if the input parameter has side-effects. allowBlockInlining = false; test("function f(x){return x}" + "var y=f(i)", "var y=i"); testSame("function f(x){return x}" + "var y=f(i++)"); } public void testInlineFunctions13() { // inline as block if the input parameter has side-effects. test("function f(x){return x}" + "var y=f(i++)", "var y;{var x$$inline_1=i++;y=x$$inline_1}"); } public void testInlineFunctions14() { // don't remove functions that are referenced on other ways test("function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=FOO(1);y=BAR(2)", "function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=1;y=2"); } public void testInlineFunctions15a() { // closure factories: do inline into global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "var d=c+function(a){return a+1}"); } public void testInlineFunctions15b() { // closure factories: don't inline closure with locals. test("function foo(){var x;return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "function foo(){var x;return function(a){return a+1}}" + "var d=c+foo()"); } public void testInlineFunctions15c() { // closure factories: don't inline into non-global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function foo(){return function(a){return a+1}}" + "function _x(){ var d=c+foo() }"); } public void testInlineFunctions16() { // watch out for closures that are deeper in the function testSame("function foo(b){return window.bar(function(){c(b)})}" + "var d=foo(e)"); } public void testInlineFunctions17() { // don't inline recursive functions testSame("function foo(x){return x*x+foo(3)}var bar=foo(4)"); } public void testInlineFunctions18() { // TRICKY ... test nested inlines allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d=c+e"); } public void testInlineFunctions19() { // TRICKY ... test nested inlines // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d;{d=c+e}"); } public void testInlineFunctions20() { // Make sure both orderings work allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e));", "var d=c"); } public void testInlineFunctions21() { // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e))", "var d;{d=c}"); } public void testInlineFunctions22() { // Another tricky case ... test nested compiler inlines test("function plex(a){if(a) return 0;else return 1;}" + "function foo(a, b){return bar(a+b)}" + "function bar(d){return plex(d)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_plex_2:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_plex_2}" + "else{" + "d=1;break JSCompiler_inline_label_plex_2}d=void 0}}"); } public void testInlineFunctions23() { // Test both orderings again test("function complex(a){if(a) return 0;else return 1;}" + "function bar(d){return complex(d)}" + "function foo(a, b){return bar(a+b)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_complex_2:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_complex_2" + "}else{" + "d=1;break JSCompiler_inline_label_complex_2" + "}d=void 0}}"); } public void testInlineFunctions24() { // Don't inline functions with 'arguments' or 'this' testSame("function foo(x){return this}foo(1)"); } public void testInlineFunctions25() { testSame("function foo(){return arguments[0]}foo()"); } public void testInlineFunctions26() { // Don't inline external functions testSame("function _foo(x){return x}_foo(1)"); } public void testInlineFunctions27() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: 1, z: foo(2)};", "var window={};" + "{" + " var JSCompiler_inline_result$$0;" + " window.bar++;" + " JSCompiler_inline_result$$0 = 3;" + "}" + "var x = {y: 1, z: JSCompiler_inline_result$$0};"); } public void testInlineFunctions28() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: alert(), z: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$0 = alert();" + "{" + " var JSCompiler_inline_result$$1;" + " window.bar++;" + " JSCompiler_inline_result$$1 = 3;}" + "var x = {" + " y: JSCompiler_temp_const$$0," + " z: JSCompiler_inline_result$$1" + "};"); } public void testInlineFunctions29() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {a: alert(), b: alert2(), c: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$1 = alert();" + "var JSCompiler_temp_const$$0 = alert2();" + "{" + " var JSCompiler_inline_result$$2;" + " window.bar++;" + " JSCompiler_inline_result$$2 = 3;}" + "var x = {" + " a: JSCompiler_temp_const$$1," + " b: JSCompiler_temp_const$$0," + " c: JSCompiler_inline_result$$2" + "};"); } public void testInlineFunctions30() { // As simple a test as we can get. testSame("function foo(){ return eval() }" + "foo();"); } public void testMixedModeInlining1() { // Base line tests, direct inlining test("function foo(){return 1}" + "foo();", "1;"); } public void testMixedModeInlining2() { // Base line tests, block inlining. Block inlining is needed by // possible-side-effect parameter. test("function foo(){return 1}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining3() { // Inline using both modes. test("function foo(){return 1}" + "foo();foo(x());", "1;{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining4() { // Inline using both modes. Alternating. Second call of each type has // side-effect-less parameter, this is thrown away. test("function foo(){return 1}" + "foo();foo(x());" + "foo(1);foo(1,x());", "1;{var JSCompiler_inline_anon_param_0=x();1}" + "1;{var JSCompiler_inline_anon_param_4=x();1}"); } public void testMixedModeInliningCosting1() { // Inline using both modes. Costing estimates. // Base line. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3)", "1+2+1+2+4+5+6+7+8+9+1+2+3+4+5;" + "2+3+2+3+4+5+6+7+8+9+1+2+3+4+5"); } public void testMixedModeInliningCosting2() { // Don't inline here because the function definition can not be eliminated. // TODO(johnlenz): Should we add constant removing to the unit test? testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3,x())"); } public void testMixedModeInliningCosting3() { // Do inline here because the function definition can be eliminated. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+10}" + "foo(1,2);" + "foo(2,3,x())", "1+2+1+2+4+5+6+7+8+9+1+2+3+10;" + "{var JSCompiler_inline_anon_param_4=x();" + "2+3+2+3+4+5+6+7+8+9+1+2+3+10}"); } public void testMixedModeInliningCosting4() { // Threshold test. testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+101}" + "foo(1,2);" + "foo(2,3,x())"); } public void testNoInlineIfParametersModified1() { // Assignment test("function f(x){return x=1}f(undefined)", "{var x$$inline_1=undefined;" + "x$$inline_1=1}"); } public void testNoInlineIfParametersModified2() { test("function f(x){return (x)=1;}f(2)", "{var x$$inline_1=2;" + "x$$inline_1=1}"); } public void testNoInlineIfParametersModified3() { // Assignment variant. test("function f(x){return x*=2}f(2)", "{var x$$inline_1=2;" + "x$$inline_1*=2}"); } public void testNoInlineIfParametersModified4() { // Assignment in if. test("function f(x){return x?(x=2):0}f(2)", "{var x$$inline_1=2;" + "x$$inline_1?(" + "x$$inline_1=2):0}"); } public void testNoInlineIfParametersModified5() { // Assignment in if, multiple params test("function f(x,y){return x?(y=2):0}f(2,undefined)", "{var y$$inline_3=undefined;2?(" + "y$$inline_3=2):0}"); } public void testNoInlineIfParametersModified6() { test("function f(x,y){return x?(y=2):0}f(2)", "{var y$$inline_3=void 0;2?(" + "y$$inline_3=2):0}"); } public void testNoInlineIfParametersModified7() { // Increment test("function f(a){return++a<++a}f(1)", "{var a$$inline_1=1;" + "++a$$inline_1<" + "++a$$inline_1}"); } public void testNoInlineIfParametersModified8() { // OK, object parameter modified. test("function f(a){return a.x=2}f(o)", "o.x=2"); } public void testNoInlineIfParametersModified9() { // OK, array parameter modified. test("function f(a){return a[2]=2}f(o)", "o[2]=2"); } public void testInlineNeverPartialSubtitution1() { test("function f(z){return x.y.z;}f(1)", "x.y.z"); } public void testInlineNeverPartialSubtitution2() { test("function f(z){return x.y[z];}f(a)", "x.y[a]"); } public void testInlineNeverMutateConstants() { test("function f(x){return x=1}f(undefined)", "{var x$$inline_1=undefined;" + "x$$inline_1=1}"); } public void testInlineNeverOverrideNewValues() { test("function f(a){return++a<++a}f(1)", "{var a$$inline_1=1;" + "++a$$inline_1<++a$$inline_1}"); } public void testInlineMutableArgsReferencedOnce() { test("function foo(x){return x;}foo([])", "[]"); } public void testNoInlineMutableArgs1() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo([])"); } public void testNoInlineMutableArgs2() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(new Date)"); } public void testNoInlineMutableArgs3() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(true&&new Date)"); } public void testNoInlineMutableArgs4() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo({})"); } public void testInlineBlockMutableArgs1() { test("function foo(x){x+x}foo([])", "{var x$$inline_1=[];" + "x$$inline_1+x$$inline_1}"); } public void testInlineBlockMutableArgs2() { test("function foo(x){x+x}foo(new Date)", "{var x$$inline_1=new Date;" + "x$$inline_1+x$$inline_1}"); } public void testInlineBlockMutableArgs3() { test("function foo(x){x+x}foo(true&&new Date)", "{var x$$inline_1=true&&new Date;" + "x$$inline_1+x$$inline_1}"); } public void testInlineBlockMutableArgs4() { test("function foo(x){x+x}foo({})", "{var x$$inline_1={};" + "x$$inline_1+x$$inline_1}"); } public void testShadowVariables1() { // The Normalize pass now guarantees that that globals are never shadowed // by locals. // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is assigned a new name. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){var a=foo(4)}" + "bar();", "var a=0;" + "{var a$$inline_1=3+4}"); } public void testShadowVariables2() { // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is inlined as its uses global "a", and does introduce any new // globals. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){a=foo(4)}" + "bar()", "var a=0;" + "{a=3+4}"); } public void testShadowVariables3() { // "foo" is inlined into exported "_bar", aliasing foo's "a". test("var a=0;" + "function foo(){var a=2;return 3+a}" + "function _bar(){a=foo()}", "var a=0;" + "function _bar(){{var a$$inline_1=2;" + "a=3+a$$inline_1}}"); } public void testShadowVariables4() { // "foo" is inlined. // block access to global "a". test("var a=0;" + "function foo(){return 3+a}" + "function _bar(a){a=foo(4)+a}", "var a=0;function _bar(a$$1){" + "a$$1=" + "3+a+a$$1}"); } public void testShadowVariables5() { // Can't yet inline mulitple statements functions into expressions // (though some are possible using the COMMA operator). allowBlockInlining = false; testSame("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)+a}"); } public void testShadowVariables6() { test("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)}", "var a=0;function _bar(a$$2){{" + "var a$$inline_1=4;" + "a$$2=3+a$$inline_1}}"); } public void testShadowVariables7() { test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables8() { // this should be inlined test("var a=0;" + "function foo(){return 3}" + "function _bar(){var a=foo()}", "var a=0;" + "function _bar(){var a=3}"); } public void testShadowVariables9() { // this should be inlined too [even if the global is not declared] test("function foo(){return 3}" + "function _bar(){var a=foo()}", "function _bar(){var a=3}"); } public void testShadowVariables10() { // callee var must be renamed. test("var a;function foo(){return a}" + "function _bar(){var a=foo()}", "var a;function _bar(){var a$$1=a}"); } public void testShadowVariables11() { // The call has a local variable // which collides with the function being inlined test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var a=foo();alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+a;" + "alert(a$$1)}" ); } public void testShadowVariables12() { // 2 globals colliding test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var a=foo(),b;alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+b," + "b$$1;" + "alert(a$$1)}"); } public void testShadowVariables13() { // The only change is to remove the collision test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c)}"); } public void testShadowVariables14() { // There is a colision even though it is not read. test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var c=foo(),b;alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+b," + "b$$1;alert(c)}"); } public void testShadowVariables15() { // Both parent and child reference a global test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c+a)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c+a)}"); } public void testShadowVariables16() { // Inline functions defined as a child of the CALL node. test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables17() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$1=2;var x=a+a}"); } public void testShadowVariables18() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){var a=3;return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$2=2;var x;" + "{var a$$inline_1=3;x=a+a}}"); } public void testCostBasedInlining1() { testSame( "function foo(a){return a}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInlining2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){return a}" + "var b=foo;" + "function _t1(){return foo(1)}", "function foo(a){return a}" + "var b=foo;" + "function _t1(){return 1}"); } public void testCostBasedInlining3() { // Two calls, function not removed. test( "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return 1+2}" + "function _t2(){return 2+3}"); } public void testCostBasedInlining4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){return a+b+a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){return a+b+a+b}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2}" + "function _t2(){return 2+3+2+3}"); } public void testCostBasedInlining6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2+1+2+1+2+4+5+6+7+8+9+1+2+3+4+5}" + "function _t2(){return 2+3+2+3+2+3+2+3+4+5+6+7+8+9+1+2+3+4+5}"); } public void testCostBasedInlining7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){" + " return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5+6}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining8() { // Verify mutiple references in the same statement: // Here "f" is not known to be removable, as it is a used as parameter // and is not known to be side-effect free. The first call to f() can // not be inlined on the first pass (as the call to f() as a parameter // prevents this). However, the call to f() would be inlinable, if it // is small enough to be inlined without removing the function declaration. // but it is not in this first test. allowBlockInlining = false; testSame("function f(a){return 1 + a + a;}" + "var a = f(f(1));"); } public void testCostBasedInlining9() { // Here both direct and block inlining is used. The call to f as a // parameter is inlined directly, which the call to f with f as a parameter // is inlined using block inlining. test("function f(a){return 1 + a + a;}" + "var a = f(f(1));", "var a;" + "{var a$$inline_1=1+1+1;" + "a=1+a$$inline_1+a$$inline_1}"); } public void testCostBasedInlining10() { // But it is small enough here, and on the second iteration, the remaining // call to f() is inlined, as there is no longer a possible side-effect-ing // parameter. allowBlockInlining = false; test("function f(a){return a + a;}" + "var a = f(f(1));", "var a= 1+1+(1+1);"); } public void testCostBasedInlining11() { // With block inlining test("function f(a){return a + a;}" + "var a = f(f(1))", "var a;" + "{var a$$inline_1=1+1;" + "a=a$$inline_1+a$$inline_1}"); } public void testCostBasedInlining12() { test("function f(a){return 1 + a + a;}" + "var a = f(1) + f(2);", "var a=1+1+1+(1+2+2)"); } public void testCostBasedInliningComplex1() { testSame( "function foo(a){a()}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInliningComplex2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){a()}" + "var b=foo;" + "function _t1(){foo(x)}", "function foo(a){a()}" + "var b=foo;" + "function _t1(){{x()}}"); } public void testCostBasedInliningComplex3() { // Two calls, function not removed. test( "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){{1+2}}" + "function _t2(){{2+3}}"); } public void testCostBasedInliningComplex4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){a+b+a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){a+b+a+b}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2}}" + "function _t2(){{2+3+2+3}}"); } public void testCostBasedInliningComplex6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2+1+2+1+2+4+5+6+7+8+9+1}}" + "function _t2(){{2+3+2+3+2+3+2+3+4+5+6+7+8+9+1}}"); } public void testCostBasedInliningComplex7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex8() { // Verify mutiple references in the same statement. testSame("function _f(a){1+a+a}" + "a=_f(1)+_f(1)"); } public void testCostBasedInliningComplex9() { test("function f(a){1 + a + a;}" + "f(1);f(2);", "{1+1+1}{1+2+2}"); } public void testDoubleInlining1() { allowBlockInlining = false; test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "getWindow(x)"); } public void testDoubleInlining2() { test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "{getWindow(x)}"); } public void testNoInlineOfNonGlobalFunction1() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction2() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction3() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction4() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineMaskedFunction() { // Normalization makes this test of marginal value. // The unreferenced function is removed. test("var g=function(){return 0};" + "function _f(g){return g()}", "function _f(g$$1){return g$$1()}"); } public void testNoInlineNonFunction() { testSame("var g=3;function _f(){return g()}"); } public void testInlineCall() { test("function f(g) { return g.h(); } f('x');", "\"x\".h()"); } public void testInlineFunctionWithArgsMismatch1() { test("function f(g) { return g; } f();", "void 0"); } public void testInlineFunctionWithArgsMismatch2() { test("function f() { return 0; } f(1);", "0"); } public void testInlineFunctionWithArgsMismatch3() { test("function f(one, two, three) { return one + two + three; } f(1);", "1+void 0+void 0"); } public void testInlineFunctionWithArgsMismatch4() { test("function f(one, two, three) { return one + two + three; }" + "f(1,2,3,4,5);", "1+2+3"); } public void testArgumentsWithSideEffectsNeverInlined1() { allowBlockInlining = false; testSame("function f(){return 0} f(new goo());"); } public void testArgumentsWithSideEffectsNeverInlined2() { allowBlockInlining = false; testSame("function f(g,h){return h+g}f(g(),h());"); } public void testOneSideEffectCallDoesNotRuinOthers() { allowBlockInlining = false; test("function f(){return 0}f(new goo());f()", "function f(){return 0}f(new goo());0"); } public void testComplexInlineNoResultNoParamCall1() { test("function f(){a()}f()", "{a()}"); } public void testComplexInlineNoResultNoParamCall2() { test("function f(){if (true){return;}else;} f();", "{JSCompiler_inline_label_f_0:{" + "if(true)break JSCompiler_inline_label_f_0;else;}}"); } public void testComplexInlineNoResultNoParamCall3() { // We now allow vars in the global space. // Don't inline into vars into global scope. // testSame("function f(){a();b();var z=1+1}f()"); // But do inline into functions test("function f(){a();b();var z=1+1}function _foo(){f()}", "function _foo(){{a();b();var z$$inline_1=1+1}}"); } public void testComplexInlineNoResultWithParamCall1() { test("function f(x){a(x)}f(1)", "{a(1)}"); } public void testComplexInlineNoResultWithParamCall2() { test("function f(x,y){a(x)}var b=1;f(1,b)", "var b=1;{a(1)}"); } public void testComplexInlineNoResultWithParamCall3() { test("function f(x,y){if (x) y(); return true;}var b=1;f(1,b)", "var b=1;{if(1)b();true}"); } public void testComplexInline1() { test("function f(){if (true){return;}else;} z=f();", "{JSCompiler_inline_label_f_0:" + "{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInline2() { test("function f(){if (true){return;}else return;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else{z=void 0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline3() { test("function f(){if (true){return 1;}else return 0;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=1;" + "break JSCompiler_inline_label_f_0}else{z=0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline4() { test("function f(x){a(x)} z = f(1)", "{a(1);z=void 0}"); } public void testComplexInline5() { test("function f(x,y){a(x)}var b=1;z=f(1,b)", "var b=1;{a(1);z=void 0}"); } public void testComplexInline6() { test("function f(x,y){if (x) y(); return true;}var b=1;z=f(1,b)", "var b=1;{if(1)b();z=true}"); } public void testComplexInline7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;z=f(1,b)", "var b=1;{JSCompiler_inline_label_f_4:{if(1){z=b();" + "break JSCompiler_inline_label_f_4}else{z=true;" + "break JSCompiler_inline_label_f_4}z=void 0}}"); } public void testComplexInline8() { test("function f(x){a(x)}var z=f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars1() { test("function f(){if (true){return;}else;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInlineVars2() { test("function f(){if (true){return;}else return;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0" + "}else{" + "z=void 0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars3() { test("function f(){if (true){return 1;}else return 0;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{if(true){" + "z=1;break JSCompiler_inline_label_f_0" + "}else{" + "z=0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars4() { test("function f(x){a(x)}var z = f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars5() { test("function f(x,y){a(x)}var b=1;var z=f(1,b)", "var b=1;var z;{a(1);z=void 0}"); } public void testComplexInlineVars6() { test("function f(x,y){if (x) y(); return true;}var b=1;var z=f(1,b)", "var b=1;var z;{if(1)b();z=true}"); } public void testComplexInlineVars7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;var z=f(1,b)", "var b=1;var z;" + "{JSCompiler_inline_label_f_4:{if(1){z=b();" + "break JSCompiler_inline_label_f_4" + "}else{" + "z=true;break JSCompiler_inline_label_f_4}z=void 0}}"); } public void testComplexInlineVars8() { test("function f(x){a(x)}var x;var z=f(1)", "var x;var z;{a(1);z=void 0}"); } public void testComplexInlineVars9() { test("function f(x){a(x)}var x;var z=f(1);var y", "var x;var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars10() { test("function f(x){a(x)}var x=blah();var z=f(1);var y=blah();", "var x=blah();var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineVars11() { test("function f(x){a(x)}var x=blah();var z=f(1);var y;", "var x=blah();var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars12() { test("function f(x){a(x)}var x;var z=f(1);var y=blah();", "var x;var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineInExpresssions1() { test("function f(){a()}var z=f()", "var z;{a();z=void 0}"); } public void testComplexInlineInExpresssions2() { test("function f(){a()}c=z=f()", "{var JSCompiler_inline_result$$0;a();}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions3() { test("function f(){a()}c=z=f()", "{var JSCompiler_inline_result$$0;a();}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions4() { test("function f(){a()}if(z=f());", "{var JSCompiler_inline_result$$0;a();}" + "if(z=JSCompiler_inline_result$$0);"); } public void testComplexInlineInExpresssions5() { test("function f(){a()}if(z.y=f());", "var JSCompiler_temp_const$$0=z;" + "{var JSCompiler_inline_result$$1;a()}" + "if(JSCompiler_temp_const$$0.y=JSCompiler_inline_result$$1);"); } public void testComplexNoInline1() { testSame("function f(){a()}while(z=f())continue"); } public void testComplexNoInline2() { testSame("function f(){a()}do;while(z=f())"); } public void testComplexSample() { String result = "" + "{{" + "var styleSheet$$inline_9=null;" + "if(goog$userAgent$IE)" + "styleSheet$$inline_9=0;" + "else " + "var head$$inline_10=0;" + "{" + "var element$$inline_11=" + "styleSheet$$inline_9;" + "var stylesString$$inline_12=a;" + "if(goog$userAgent$IE)" + "element$$inline_11.cssText=" + "stylesString$$inline_12;" + "else " + "{" + "var propToSet$$inline_13=" + "\"innerText\";" + "element$$inline_11[" + "propToSet$$inline_13]=" + "stylesString$$inline_12" + "}" + "}" + "styleSheet$$inline_9" + "}}"; test("var foo = function(stylesString, opt_element) { " + "var styleSheet = null;" + "if (goog$userAgent$IE)" + "styleSheet = 0;" + "else " + "var head = 0;" + "" + "goo$zoo(styleSheet, stylesString);" + "return styleSheet;" + " };\n " + "var goo$zoo = function(element, stylesString) {" + "if (goog$userAgent$IE)" + "element.cssText = stylesString;" + "else {" + "var propToSet = 'innerText';" + "element[propToSet] = stylesString;" + "}" + "};" + "(function(){foo(a,b);})();", result); } public void testComplexSampleNoInline() { // This is the result we would expect if we could handle "foo = function" String result = "foo=function(stylesString,opt_element){" + "var styleSheet=null;" + "if(goog$userAgent$IE){" + "styleSheet=0" + "}else{" + "var head=0" + "}" + "{var JSCompiler_inline_element_0=styleSheet;" + "var JSCompiler_inline_stylesString_1=stylesString;" + "if(goog$userAgent$IE){" + "JSCompiler_inline_element_0.cssText=" + "JSCompiler_inline_stylesString_1" + "}else{" + "var propToSet=goog$userAgent$WEBKIT?\"innerText\":\"innerHTML\";" + "JSCompiler_inline_element_0[propToSet]=" + "JSCompiler_inline_stylesString_1" + "}}" + "return styleSheet" + "}"; testSame( "foo=function(stylesString,opt_element){" + "var styleSheet=null;" + "if(goog$userAgent$IE)" + "styleSheet=0;" + "else " + "var head=0;" + "" + "goo$zoo(styleSheet,stylesString);" + "return styleSheet" + "};" + "goo$zoo=function(element,stylesString){" + "if(goog$userAgent$IE)" + "element.cssText=stylesString;" + "else{" + "var propToSet=goog$userAgent$WEBKIT?\"innerText\":\"innerHTML\";" + "element[propToSet]=stylesString" + "}" + "}"); } // Test redefinition of parameter name. public void testComplexNoVarSub() { test( "function foo(x){" + "var x;" + "y=x" + "}" + "foo(1)", "{y=1}" ); } public void testComplexFunctionWithFunctionDefinition1() { test("function f(){call(function(){return})}f()", "{call(function(){return})}"); } public void testComplexFunctionWithFunctionDefinition2() { // Don't inline if local names might need to be captured. testSame("function f(a){call(function(){return})}f()"); } public void testComplexFunctionWithFunctionDefinition3() { // Don't inline if local names might need to be captured. testSame("function f(){var a; call(function(){return})}f()"); } public void testDecomposePlusEquals() { test("function f(){a=1;return 1} var x = 1; x += f()", "var x = 1;" + "var JSCompiler_temp_const$$0 = x;" + "{var JSCompiler_inline_result$$1; a=1;" + " JSCompiler_inline_result$$1=1}" + "x = JSCompiler_temp_const$$0 + JSCompiler_inline_result$$1;"); } public void testDecomposeFunctionExpressionInCall() { test( "(function(map){descriptions_=map})(\n" + "function(){\n" + "var ret={};\n" + "ret[ONE]='a';\n" + "ret[TWO]='b';\n" + "return ret\n" + "}()\n" + ");", "{" + "var JSCompiler_inline_result$$0;" + "var ret$$inline_2={};\n" + "ret$$inline_2[ONE]='a';\n" + "ret$$inline_2[TWO]='b';\n" + "JSCompiler_inline_result$$0 = ret$$inline_2;\n" + "}" + "{" + "descriptions_=JSCompiler_inline_result$$0;" + "}" ); } public void testInlineConstructor1() { test("function f() {} function _g() {f.call(this)}", "function _g() {void 0}"); } public void testInlineConstructor2() { test("function f() {} f.prototype.a = 0; function _g() {f.call(this)}", "function f() {} f.prototype.a = 0; function _g() {void 0}"); } public void testInlineConstructor3() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {{x.call(this)}}"); } public void testInlineConstructor4() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t = f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t; {x.call(this); t = void 0}}"); } public void testFunctionExpressionInlining1() { test("(function(){})()", "void 0"); } public void testFunctionExpressionInlining2() { test("(function(){foo()})()", "{foo()}"); } public void testFunctionExpressionInlining3() { test("var a = (function(){return foo()})()", "var a = foo()"); } public void testFunctionExpressionInlining4() { test("var a; a = 1 + (function(){return foo()})()", "var a; a = 1 + foo()"); } public void testFunctionExpressionCallInlining1() { test("(function(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining2() { test("(function(){foo(this)}).call(this)", "{foo(this)}"); } public void testFunctionExpressionCallInlining3() { test("var a = (function(){return foo(this)}).call(this)", "var a = foo(this)"); } public void testFunctionExpressionCallInlining4() { test("var a; a = 1 + (function(){return foo(this)}).call(this)", "var a; a = 1 + foo(this)"); } public void testFunctionExpressionCallInlining5() { test("a:(function(){return foo()})()", "a:foo()"); } public void testFunctionExpressionCallInlining6() { test("a:(function(){return foo()}).call(this)", "a:foo()"); } public void testFunctionExpressionCallInlining7() { test("a:(function(){})()", "a:void 0"); } public void testFunctionExpressionCallInlining8() { test("a:(function(){}).call(this)", "a:void 0"); } public void testFunctionExpressionCallInlining9() { // ... with unused recursive name. test("(function foo(){})()", "void 0"); } public void testFunctionExpressionCallInlining10() { // ... with unused recursive name. test("(function foo(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining11a() { // Inline functions that return inner functions. test("((function(){return function(){foo()}})())();", "{foo()}"); } public void testFunctionExpressionCallInlining11b() { // Can't inline functions that return inner functions and have local names. testSame("((function(){var a; return function(){foo()}})())();"); } public void testFunctionExpressionCallInlining11c() { // Can't inline functions that return inner functions into non-global scope. testSame("function _x() {" + "((function(){return function(){foo()}})())();" + "}"); } public void testFunctionExpressionCallInlining12() { // Can't inline functions that recurse. testSame("(function foo(){foo()})()"); } public void testFunctionExpressionOmega() { // ... with unused recursive name. test("(function (f){f(f)})(function(f){f(f)})", "{var f$$inline_1=function(f$$1){f$$1(f$$1)};" + "{{f$$inline_1(f$$inline_1)}}}"); } public void testLocalFunctionInlining1() { test("function _f(){ function g() {} g() }", "function _f(){ void 0 }"); } public void testLocalFunctionInlining2() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining3() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining4() { test("function _f(){ function g() {return 1} return g() }", "function _f(){ return 1 }"); } public void testLocalFunctionInlining5() { testSame("function _f(){ function g() {this;} g() }"); } public void testLocalFunctionInlining6() { testSame("function _f(){ function g() {this;} return g; }"); } public void testLocalFunctionInliningOnly1() { this.allowGlobalFunctionInlining = true; test("function f(){} f()", "void 0;"); this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); } public void testLocalFunctionInliningOnly2() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("function f(){ function g() {return 1} return g() }; f();", "function f(){ return 1 }; f();"); } public void testLocalFunctionInliningOnly3() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ function g() {return 1} return g() })();", "(function(){ return 1 })();"); } public void testLocalFunctionInliningOnly4() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ return (function() {return 1})() })();", "(function(){ return 1 })();"); } // http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator public void testFunctionExpressionYCombinator() { testSame( "var factorial = ((function(M) {\n" + " return ((function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " })\n" + " (function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " }));\n" + " })\n" + " (function(f) {\n" + " return function(n) {\n" + " if (n === 0)\n" + " return 1;\n" + " else\n" + " return n * f(n - 1);\n" + " };\n" + " }));\n" + "\n" + "factorial(5)\n"); } public void testRenamePropertyFunction() { testSame("function JSCompiler_renameProperty(x) {return x} " + "JSCompiler_renameProperty('foo')"); } public void testReplacePropertyFunction() { // baseline: an alias doesn't prevents declaration removal, but not // inlining. test("function f(x) {return x} " + "foo(window, f); f(1)", "function f(x) {return x} " + "foo(window, f); 1"); // a reference passed to JSCompiler_ObjectPropertyString prevents inlining // as well. testSame("function f(x) {return x} " + "new JSCompiler_ObjectPropertyString(window, f); f(1)"); } public void testIssue423() { test( "(function($) {\n" + " $.fn.multicheck = function(options) {\n" + " initialize.call(this, options);\n" + " };\n" + "\n" + " function initialize(options) {\n" + " options.checkboxes = $(this).siblings(':checkbox');\n" + " preload_check_all.call(this);\n" + " }\n" + "\n" + " function preload_check_all() {\n" + " $(this).data('checkboxes');\n" + " }\n" + "})(jQuery)", "(function($){" + " $.fn.multicheck=function(options$$1){" + " {" + " options$$1.checkboxes=$(this).siblings(\":checkbox\");" + " {" + " $(this).data(\"checkboxes\")" + " }" + " }" + " }" + "})(jQuery)"); } // Inline a single reference function into deeper modules public void testCrossModuleInlining1() { test(createModuleChain( // m1 "function foo(){return f(1)+g(2)+h(3);}", // m2 "foo()" ), new String[] { // m1 "", // m2 "f(1)+g(2)+h(3);" } ); } // Inline a single reference function into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining2() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}" ), new String[] { // m1 "f();", // m2 "" } ); } // Inline a multi-reference functions into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining3() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}", // m3 "foo()" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}", // m3 "foo()" ), new String[] { // m1 "f();", // m2 "", // m3 "f();" } ); } }
// You are a professional Java test case writer, please create a test case named `testIssue423` for the issue `Closure-423`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-423 // // ## Issue-Title: // Closure Compiler failed to translate all instances of a function name // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the attached jQuery Multicheck plugin using SIMPLE optimization. // // **What is the expected output? What do you see instead?** // You expect that the function preload\_check\_all() gets its name translated appropriately. In fact, the Closure Compiler breaks the code by changing the function declaration but NOT changing the call to the function on line 76. // // public void testIssue423() {
1,692
159
1,666
test/com/google/javascript/jscomp/InlineFunctionsTest.java
test
```markdown ## Issue-ID: Closure-423 ## Issue-Title: Closure Compiler failed to translate all instances of a function name ## Issue-Description: **What steps will reproduce the problem?** 1. Compile the attached jQuery Multicheck plugin using SIMPLE optimization. **What is the expected output? What do you see instead?** You expect that the function preload\_check\_all() gets its name translated appropriately. In fact, the Closure Compiler breaks the code by changing the function declaration but NOT changing the call to the function on line 76. ``` You are a professional Java test case writer, please create a test case named `testIssue423` for the issue `Closure-423`, utilizing the provided issue report information and the following function signature. ```java public void testIssue423() { ```
1,666
[ "com.google.javascript.jscomp.InlineFunctions" ]
cf809dc1411772c0d5424cd13a09a2db1e0b32307a91a5bc4bc947cfe7c83dac
public void testIssue423()
// You are a professional Java test case writer, please create a test case named `testIssue423` for the issue `Closure-423`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-423 // // ## Issue-Title: // Closure Compiler failed to translate all instances of a function name // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Compile the attached jQuery Multicheck plugin using SIMPLE optimization. // // **What is the expected output? What do you see instead?** // You expect that the function preload\_check\_all() gets its name translated appropriately. In fact, the Closure Compiler breaks the code by changing the function declaration but NOT changing the call to the function on line 76. // //
Closure
/* * Copyright 2008 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; /** * Inline function tests. * @author [email protected] (john lenz) */ public class InlineFunctionsTest extends CompilerTestCase { boolean allowGlobalFunctionInlining = true; boolean allowBlockInlining = true; final boolean allowExpressionDecomposition = true; final boolean allowFunctionExpressionInlining = true; final boolean allowLocalFunctionInlining = true; public InlineFunctionsTest() { this.enableNormalize(); this.enableMarkNoSideEffects(); } @Override protected void setUp() throws Exception { super.setUp(); super.enableLineNumberCheck(true); allowGlobalFunctionInlining = true; allowBlockInlining = true; } @Override protected CompilerPass getProcessor(Compiler compiler) { compiler.resetUniqueNameId(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), allowGlobalFunctionInlining, allowLocalFunctionInlining, allowBlockInlining); } /** * Returns the number of times the pass should be run before results are * verified. */ @Override protected int getNumRepetitions() { // Some inlining can only be done in mutliple passes. return 3; } public void testInlineEmptyFunction1() { // Empty function, no params. test("function foo(){}" + "foo();", "void 0;"); } public void testInlineEmptyFunction2() { // Empty function, params with no side-effects. test("function foo(){}" + "foo(1, new Date, function(){});", "void 0;"); } public void testInlineEmptyFunction3() { // Empty function, multiple references. test("function foo(){}" + "foo();foo();foo();", "void 0;void 0;void 0"); } public void testInlineEmptyFunction4() { // Empty function, params with side-effects forces block inlining. test("function foo(){}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();}"); } public void testInlineEmptyFunction5() { // Empty function, call params with side-effects in expression can not // be inlined. allowBlockInlining = false; testSame("function foo(){}" + "foo(x());"); } public void testInlineFunctions1() { // As simple a test as we can get. test("function foo(){ return 4 }" + "foo();", "4"); } public void testInlineFunctions2() { // inline simple constants // NOTE: CD is not inlined. test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;CD=function(x){return x+5};x=CD(3);y=4;z=6" ); } public void testInlineFunctions3() { // inline simple constants test("var t;var AB=function(){return 4};" + "function BC(){return 6;}" + "var CD=function(x){return x + 5};x=CD(3);y=AB();z=BC();", "var t;x=3+5;y=4;z=6"); } public void testInlineFunctions4() { // don't inline if there are multiple definitions (need DFA for that). test("var t; var AB = function() { return 4 }; " + "function BC() { return 6; }" + "CD = 0;" + "CD = function(x) { return x + 5 }; x = CD(3); y = AB(); z = BC();", "var t;CD=0;CD=function(x){return x+5};x=CD(3);y=4;z=6"); } public void testInlineFunctions5() { // inline additions test("var FOO_FN=function(x,y) { return \"de\" + x + \"nu\" + y };" + "var a = FOO_FN(\"ez\", \"ts\")", "var a=\"de\"+\"ez\"+\"nu\"+\"ts\""); } public void testInlineFunctions6() { // more complex inlines test("function BAR_FN(x, y, z) { return z(foo(x + y)) }" + "alert(BAR_FN(1, 2, baz))", "alert(baz(foo(1+2)))"); } public void testInlineFunctions7() { // inlines appearing multiple times test("function FN(x,y,z){return x+x+y}" + "var b=FN(1,2,3)", "var b=1+1+2"); } public void testInlineFunctions8() { // check correct parenthesization test("function MUL(x,y){return x*y}function ADD(x,y){return x+y}" + "var a=1+MUL(2,3);var b=2*ADD(3,4)", "var a=1+2*3;var b=2*(3+4)"); } public void testInlineFunctions9() { // don't inline if the input parameter is modified. test("function INC(x){return x++}" + "var y=INC(i)", "var y;{var x$$inline_1=i;" + "y=x$$inline_1++}"); } public void testInlineFunctions10() { test("function INC(x){return x++}" + "var y=INC(i);y=INC(i)", "var y;" + "{var x$$inline_1=i;" + "y=x$$inline_1++}" + "{var x$$inline_4=i;" + "y=x$$inline_4++}"); } public void testInlineFunctions11() { test("function f(x){return x}" + "var y=f(i)", "var y=i"); } public void testInlineFunctions12() { // don't inline if the input parameter has side-effects. allowBlockInlining = false; test("function f(x){return x}" + "var y=f(i)", "var y=i"); testSame("function f(x){return x}" + "var y=f(i++)"); } public void testInlineFunctions13() { // inline as block if the input parameter has side-effects. test("function f(x){return x}" + "var y=f(i++)", "var y;{var x$$inline_1=i++;y=x$$inline_1}"); } public void testInlineFunctions14() { // don't remove functions that are referenced on other ways test("function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=FOO(1);y=BAR(2)", "function FOO(x){return x}var BAR=function(y){return y}" + ";b=FOO;a(BAR);x=1;y=2"); } public void testInlineFunctions15a() { // closure factories: do inline into global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "var d=c+function(a){return a+1}"); } public void testInlineFunctions15b() { // closure factories: don't inline closure with locals. test("function foo(){var x;return function(a){return a+1}}" + "var b=function(){return c};" + "var d=b()+foo()", "function foo(){var x;return function(a){return a+1}}" + "var d=c+foo()"); } public void testInlineFunctions15c() { // closure factories: don't inline into non-global scope. test("function foo(){return function(a){return a+1}}" + "var b=function(){return c};" + "function _x(){ var d=b()+foo() }", "function foo(){return function(a){return a+1}}" + "function _x(){ var d=c+foo() }"); } public void testInlineFunctions16() { // watch out for closures that are deeper in the function testSame("function foo(b){return window.bar(function(){c(b)})}" + "var d=foo(e)"); } public void testInlineFunctions17() { // don't inline recursive functions testSame("function foo(x){return x*x+foo(3)}var bar=foo(4)"); } public void testInlineFunctions18() { // TRICKY ... test nested inlines allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d=c+e"); } public void testInlineFunctions19() { // TRICKY ... test nested inlines // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=foo(bar(1),e)", "var d;{d=c+e}"); } public void testInlineFunctions20() { // Make sure both orderings work allowBlockInlining = false; test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e));", "var d=c"); } public void testInlineFunctions21() { // with block inlining possible test("function foo(a, b){return a+b}" + "function bar(d){return c}" + "var d=bar(foo(1,e))", "var d;{d=c}"); } public void testInlineFunctions22() { // Another tricky case ... test nested compiler inlines test("function plex(a){if(a) return 0;else return 1;}" + "function foo(a, b){return bar(a+b)}" + "function bar(d){return plex(d)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_plex_2:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_plex_2}" + "else{" + "d=1;break JSCompiler_inline_label_plex_2}d=void 0}}"); } public void testInlineFunctions23() { // Test both orderings again test("function complex(a){if(a) return 0;else return 1;}" + "function bar(d){return complex(d)}" + "function foo(a, b){return bar(a+b)}" + "var d=foo(1,2)", "var d;{JSCompiler_inline_label_complex_2:{" + "if(1+2){" + "d=0;break JSCompiler_inline_label_complex_2" + "}else{" + "d=1;break JSCompiler_inline_label_complex_2" + "}d=void 0}}"); } public void testInlineFunctions24() { // Don't inline functions with 'arguments' or 'this' testSame("function foo(x){return this}foo(1)"); } public void testInlineFunctions25() { testSame("function foo(){return arguments[0]}foo()"); } public void testInlineFunctions26() { // Don't inline external functions testSame("function _foo(x){return x}_foo(1)"); } public void testInlineFunctions27() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: 1, z: foo(2)};", "var window={};" + "{" + " var JSCompiler_inline_result$$0;" + " window.bar++;" + " JSCompiler_inline_result$$0 = 3;" + "}" + "var x = {y: 1, z: JSCompiler_inline_result$$0};"); } public void testInlineFunctions28() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {y: alert(), z: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$0 = alert();" + "{" + " var JSCompiler_inline_result$$1;" + " window.bar++;" + " JSCompiler_inline_result$$1 = 3;}" + "var x = {" + " y: JSCompiler_temp_const$$0," + " z: JSCompiler_inline_result$$1" + "};"); } public void testInlineFunctions29() { test("var window = {}; function foo(){window.bar++; return 3;}" + "var x = {a: alert(), b: alert2(), c: foo(2)};", "var window = {};" + "var JSCompiler_temp_const$$1 = alert();" + "var JSCompiler_temp_const$$0 = alert2();" + "{" + " var JSCompiler_inline_result$$2;" + " window.bar++;" + " JSCompiler_inline_result$$2 = 3;}" + "var x = {" + " a: JSCompiler_temp_const$$1," + " b: JSCompiler_temp_const$$0," + " c: JSCompiler_inline_result$$2" + "};"); } public void testInlineFunctions30() { // As simple a test as we can get. testSame("function foo(){ return eval() }" + "foo();"); } public void testMixedModeInlining1() { // Base line tests, direct inlining test("function foo(){return 1}" + "foo();", "1;"); } public void testMixedModeInlining2() { // Base line tests, block inlining. Block inlining is needed by // possible-side-effect parameter. test("function foo(){return 1}" + "foo(x());", "{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining3() { // Inline using both modes. test("function foo(){return 1}" + "foo();foo(x());", "1;{var JSCompiler_inline_anon_param_0=x();1}"); } public void testMixedModeInlining4() { // Inline using both modes. Alternating. Second call of each type has // side-effect-less parameter, this is thrown away. test("function foo(){return 1}" + "foo();foo(x());" + "foo(1);foo(1,x());", "1;{var JSCompiler_inline_anon_param_0=x();1}" + "1;{var JSCompiler_inline_anon_param_4=x();1}"); } public void testMixedModeInliningCosting1() { // Inline using both modes. Costing estimates. // Base line. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3)", "1+2+1+2+4+5+6+7+8+9+1+2+3+4+5;" + "2+3+2+3+4+5+6+7+8+9+1+2+3+4+5"); } public void testMixedModeInliningCosting2() { // Don't inline here because the function definition can not be eliminated. // TODO(johnlenz): Should we add constant removing to the unit test? testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "foo(1,2);" + "foo(2,3,x())"); } public void testMixedModeInliningCosting3() { // Do inline here because the function definition can be eliminated. test( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+10}" + "foo(1,2);" + "foo(2,3,x())", "1+2+1+2+4+5+6+7+8+9+1+2+3+10;" + "{var JSCompiler_inline_anon_param_4=x();" + "2+3+2+3+4+5+6+7+8+9+1+2+3+10}"); } public void testMixedModeInliningCosting4() { // Threshold test. testSame( "function foo(a,b){return a+b+a+b+4+5+6+7+8+9+1+2+3+4+101}" + "foo(1,2);" + "foo(2,3,x())"); } public void testNoInlineIfParametersModified1() { // Assignment test("function f(x){return x=1}f(undefined)", "{var x$$inline_1=undefined;" + "x$$inline_1=1}"); } public void testNoInlineIfParametersModified2() { test("function f(x){return (x)=1;}f(2)", "{var x$$inline_1=2;" + "x$$inline_1=1}"); } public void testNoInlineIfParametersModified3() { // Assignment variant. test("function f(x){return x*=2}f(2)", "{var x$$inline_1=2;" + "x$$inline_1*=2}"); } public void testNoInlineIfParametersModified4() { // Assignment in if. test("function f(x){return x?(x=2):0}f(2)", "{var x$$inline_1=2;" + "x$$inline_1?(" + "x$$inline_1=2):0}"); } public void testNoInlineIfParametersModified5() { // Assignment in if, multiple params test("function f(x,y){return x?(y=2):0}f(2,undefined)", "{var y$$inline_3=undefined;2?(" + "y$$inline_3=2):0}"); } public void testNoInlineIfParametersModified6() { test("function f(x,y){return x?(y=2):0}f(2)", "{var y$$inline_3=void 0;2?(" + "y$$inline_3=2):0}"); } public void testNoInlineIfParametersModified7() { // Increment test("function f(a){return++a<++a}f(1)", "{var a$$inline_1=1;" + "++a$$inline_1<" + "++a$$inline_1}"); } public void testNoInlineIfParametersModified8() { // OK, object parameter modified. test("function f(a){return a.x=2}f(o)", "o.x=2"); } public void testNoInlineIfParametersModified9() { // OK, array parameter modified. test("function f(a){return a[2]=2}f(o)", "o[2]=2"); } public void testInlineNeverPartialSubtitution1() { test("function f(z){return x.y.z;}f(1)", "x.y.z"); } public void testInlineNeverPartialSubtitution2() { test("function f(z){return x.y[z];}f(a)", "x.y[a]"); } public void testInlineNeverMutateConstants() { test("function f(x){return x=1}f(undefined)", "{var x$$inline_1=undefined;" + "x$$inline_1=1}"); } public void testInlineNeverOverrideNewValues() { test("function f(a){return++a<++a}f(1)", "{var a$$inline_1=1;" + "++a$$inline_1<++a$$inline_1}"); } public void testInlineMutableArgsReferencedOnce() { test("function foo(x){return x;}foo([])", "[]"); } public void testNoInlineMutableArgs1() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo([])"); } public void testNoInlineMutableArgs2() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(new Date)"); } public void testNoInlineMutableArgs3() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo(true&&new Date)"); } public void testNoInlineMutableArgs4() { allowBlockInlining = false; testSame("function foo(x){return x+x} foo({})"); } public void testInlineBlockMutableArgs1() { test("function foo(x){x+x}foo([])", "{var x$$inline_1=[];" + "x$$inline_1+x$$inline_1}"); } public void testInlineBlockMutableArgs2() { test("function foo(x){x+x}foo(new Date)", "{var x$$inline_1=new Date;" + "x$$inline_1+x$$inline_1}"); } public void testInlineBlockMutableArgs3() { test("function foo(x){x+x}foo(true&&new Date)", "{var x$$inline_1=true&&new Date;" + "x$$inline_1+x$$inline_1}"); } public void testInlineBlockMutableArgs4() { test("function foo(x){x+x}foo({})", "{var x$$inline_1={};" + "x$$inline_1+x$$inline_1}"); } public void testShadowVariables1() { // The Normalize pass now guarantees that that globals are never shadowed // by locals. // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is assigned a new name. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){var a=foo(4)}" + "bar();", "var a=0;" + "{var a$$inline_1=3+4}"); } public void testShadowVariables2() { // "foo" is inlined here as its parameter "a" doesn't conflict. // "bar" is inlined as its uses global "a", and does introduce any new // globals. test("var a=0;" + "function foo(a){return 3+a}" + "function bar(){a=foo(4)}" + "bar()", "var a=0;" + "{a=3+4}"); } public void testShadowVariables3() { // "foo" is inlined into exported "_bar", aliasing foo's "a". test("var a=0;" + "function foo(){var a=2;return 3+a}" + "function _bar(){a=foo()}", "var a=0;" + "function _bar(){{var a$$inline_1=2;" + "a=3+a$$inline_1}}"); } public void testShadowVariables4() { // "foo" is inlined. // block access to global "a". test("var a=0;" + "function foo(){return 3+a}" + "function _bar(a){a=foo(4)+a}", "var a=0;function _bar(a$$1){" + "a$$1=" + "3+a+a$$1}"); } public void testShadowVariables5() { // Can't yet inline mulitple statements functions into expressions // (though some are possible using the COMMA operator). allowBlockInlining = false; testSame("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)+a}"); } public void testShadowVariables6() { test("var a=0;" + "function foo(){var a=4;return 3+a}" + "function _bar(a){a=foo(4)}", "var a=0;function _bar(a$$2){{" + "var a$$inline_1=4;" + "a$$2=3+a$$inline_1}}"); } public void testShadowVariables7() { test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables8() { // this should be inlined test("var a=0;" + "function foo(){return 3}" + "function _bar(){var a=foo()}", "var a=0;" + "function _bar(){var a=3}"); } public void testShadowVariables9() { // this should be inlined too [even if the global is not declared] test("function foo(){return 3}" + "function _bar(){var a=foo()}", "function _bar(){var a=3}"); } public void testShadowVariables10() { // callee var must be renamed. test("var a;function foo(){return a}" + "function _bar(){var a=foo()}", "var a;function _bar(){var a$$1=a}"); } public void testShadowVariables11() { // The call has a local variable // which collides with the function being inlined test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var a=foo();alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+a;" + "alert(a$$1)}" ); } public void testShadowVariables12() { // 2 globals colliding test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var a=foo(),b;alert(a)}", "var a=0;var b=1;" + "function _bar(){var a$$1=a+b," + "b$$1;" + "alert(a$$1)}"); } public void testShadowVariables13() { // The only change is to remove the collision test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c)}"); } public void testShadowVariables14() { // There is a colision even though it is not read. test("var a=0;var b=1;" + "function foo(){return a+b}" + "function _bar(){var c=foo(),b;alert(c)}", "var a=0;var b=1;" + "function _bar(){var c=a+b," + "b$$1;alert(c)}"); } public void testShadowVariables15() { // Both parent and child reference a global test("var a=0;var b=1;" + "function foo(){return a+a}" + "function _bar(){var c=foo();alert(c+a)}", "var a=0;var b=1;" + "function _bar(){var c=a+a;alert(c+a)}"); } public void testShadowVariables16() { // Inline functions defined as a child of the CALL node. test("var a=3;" + "function foo(){return a}" + "(function(){var a=5;(function(){foo()})()})()", "var a=3;" + "{var a$$inline_1=5;{a}}" ); } public void testShadowVariables17() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$1=2;var x=a+a}"); } public void testShadowVariables18() { test("var a=0;" + "function bar(){return a+a}" + "function foo(){var a=3;return bar()}" + "function _goo(){var a=2;var x=foo();}", "var a=0;" + "function _goo(){var a$$2=2;var x;" + "{var a$$inline_1=3;x=a+a}}"); } public void testCostBasedInlining1() { testSame( "function foo(a){return a}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInlining2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){return a}" + "var b=foo;" + "function _t1(){return foo(1)}", "function foo(a){return a}" + "var b=foo;" + "function _t1(){return 1}"); } public void testCostBasedInlining3() { // Two calls, function not removed. test( "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function foo(a,b){return a+b}" + "var b=foo;" + "function _t1(){return 1+2}" + "function _t2(){return 2+3}"); } public void testCostBasedInlining4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){return a+b+a+b}" + "var b=foo;" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){return a+b+a+b}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2}" + "function _t2(){return 2+3+2+3}"); } public void testCostBasedInlining6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}", "function _t1(){return 1+2+1+2+1+2+1+2+4+5+6+7+8+9+1+2+3+4+5}" + "function _t2(){return 2+3+2+3+2+3+2+3+4+5+6+7+8+9+1+2+3+4+5}"); } public void testCostBasedInlining7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){" + " return a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2+3+4+5+6}" + "function _t1(){return foo(1,2)}" + "function _t2(){return foo(2,3)}"); } public void testCostBasedInlining8() { // Verify mutiple references in the same statement: // Here "f" is not known to be removable, as it is a used as parameter // and is not known to be side-effect free. The first call to f() can // not be inlined on the first pass (as the call to f() as a parameter // prevents this). However, the call to f() would be inlinable, if it // is small enough to be inlined without removing the function declaration. // but it is not in this first test. allowBlockInlining = false; testSame("function f(a){return 1 + a + a;}" + "var a = f(f(1));"); } public void testCostBasedInlining9() { // Here both direct and block inlining is used. The call to f as a // parameter is inlined directly, which the call to f with f as a parameter // is inlined using block inlining. test("function f(a){return 1 + a + a;}" + "var a = f(f(1));", "var a;" + "{var a$$inline_1=1+1+1;" + "a=1+a$$inline_1+a$$inline_1}"); } public void testCostBasedInlining10() { // But it is small enough here, and on the second iteration, the remaining // call to f() is inlined, as there is no longer a possible side-effect-ing // parameter. allowBlockInlining = false; test("function f(a){return a + a;}" + "var a = f(f(1));", "var a= 1+1+(1+1);"); } public void testCostBasedInlining11() { // With block inlining test("function f(a){return a + a;}" + "var a = f(f(1))", "var a;" + "{var a$$inline_1=1+1;" + "a=a$$inline_1+a$$inline_1}"); } public void testCostBasedInlining12() { test("function f(a){return 1 + a + a;}" + "var a = f(1) + f(2);", "var a=1+1+1+(1+2+2)"); } public void testCostBasedInliningComplex1() { testSame( "function foo(a){a()}" + "foo=new Function(\"return 1\");" + "foo(1)"); } public void testCostBasedInliningComplex2() { // Baseline complexity tests. // Single call, function not removed. test( "function foo(a){a()}" + "var b=foo;" + "function _t1(){foo(x)}", "function foo(a){a()}" + "var b=foo;" + "function _t1(){{x()}}"); } public void testCostBasedInliningComplex3() { // Two calls, function not removed. test( "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function foo(a,b){a+b}" + "var b=foo;" + "function _t1(){{1+2}}" + "function _t2(){{2+3}}"); } public void testCostBasedInliningComplex4() { // Two calls, function not removed. // Here there isn't enough savings to justify inlining. testSame( "function foo(a,b){a+b+a+b}" + "var b=foo;" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex5() { // Here there is enough savings to justify inlining. test( "function foo(a,b){a+b+a+b}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2}}" + "function _t2(){{2+3+2+3}}"); } public void testCostBasedInliningComplex6() { // Here we have a threshold test. // Do inline here: test( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}", "function _t1(){{1+2+1+2+1+2+1+2+4+5+6+7+8+9+1}}" + "function _t2(){{2+3+2+3+2+3+2+3+4+5+6+7+8+9+1}}"); } public void testCostBasedInliningComplex7() { // Don't inline here (not enough savings): testSame( "function foo(a,b){a+b+a+b+a+b+a+b+4+5+6+7+8+9+1+2}" + "function _t1(){foo(1,2)}" + "function _t2(){foo(2,3)}"); } public void testCostBasedInliningComplex8() { // Verify mutiple references in the same statement. testSame("function _f(a){1+a+a}" + "a=_f(1)+_f(1)"); } public void testCostBasedInliningComplex9() { test("function f(a){1 + a + a;}" + "f(1);f(2);", "{1+1+1}{1+2+2}"); } public void testDoubleInlining1() { allowBlockInlining = false; test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "getWindow(x)"); } public void testDoubleInlining2() { test("var foo = function(a) { return getWindow(a); };" + "var bar = function(b) { return b; };" + "foo(bar(x));", "{getWindow(x)}"); } public void testNoInlineOfNonGlobalFunction1() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction2() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction3() { test("var g;function _f(){var g=function(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineOfNonGlobalFunction4() { test("var g;function _f(){function g(){return 0}}" + "function _h(){return g()}", "var g;function _f(){}" + "function _h(){return g()}"); } public void testNoInlineMaskedFunction() { // Normalization makes this test of marginal value. // The unreferenced function is removed. test("var g=function(){return 0};" + "function _f(g){return g()}", "function _f(g$$1){return g$$1()}"); } public void testNoInlineNonFunction() { testSame("var g=3;function _f(){return g()}"); } public void testInlineCall() { test("function f(g) { return g.h(); } f('x');", "\"x\".h()"); } public void testInlineFunctionWithArgsMismatch1() { test("function f(g) { return g; } f();", "void 0"); } public void testInlineFunctionWithArgsMismatch2() { test("function f() { return 0; } f(1);", "0"); } public void testInlineFunctionWithArgsMismatch3() { test("function f(one, two, three) { return one + two + three; } f(1);", "1+void 0+void 0"); } public void testInlineFunctionWithArgsMismatch4() { test("function f(one, two, three) { return one + two + three; }" + "f(1,2,3,4,5);", "1+2+3"); } public void testArgumentsWithSideEffectsNeverInlined1() { allowBlockInlining = false; testSame("function f(){return 0} f(new goo());"); } public void testArgumentsWithSideEffectsNeverInlined2() { allowBlockInlining = false; testSame("function f(g,h){return h+g}f(g(),h());"); } public void testOneSideEffectCallDoesNotRuinOthers() { allowBlockInlining = false; test("function f(){return 0}f(new goo());f()", "function f(){return 0}f(new goo());0"); } public void testComplexInlineNoResultNoParamCall1() { test("function f(){a()}f()", "{a()}"); } public void testComplexInlineNoResultNoParamCall2() { test("function f(){if (true){return;}else;} f();", "{JSCompiler_inline_label_f_0:{" + "if(true)break JSCompiler_inline_label_f_0;else;}}"); } public void testComplexInlineNoResultNoParamCall3() { // We now allow vars in the global space. // Don't inline into vars into global scope. // testSame("function f(){a();b();var z=1+1}f()"); // But do inline into functions test("function f(){a();b();var z=1+1}function _foo(){f()}", "function _foo(){{a();b();var z$$inline_1=1+1}}"); } public void testComplexInlineNoResultWithParamCall1() { test("function f(x){a(x)}f(1)", "{a(1)}"); } public void testComplexInlineNoResultWithParamCall2() { test("function f(x,y){a(x)}var b=1;f(1,b)", "var b=1;{a(1)}"); } public void testComplexInlineNoResultWithParamCall3() { test("function f(x,y){if (x) y(); return true;}var b=1;f(1,b)", "var b=1;{if(1)b();true}"); } public void testComplexInline1() { test("function f(){if (true){return;}else;} z=f();", "{JSCompiler_inline_label_f_0:" + "{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInline2() { test("function f(){if (true){return;}else return;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=void 0;" + "break JSCompiler_inline_label_f_0}else{z=void 0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline3() { test("function f(){if (true){return 1;}else return 0;} z=f();", "{JSCompiler_inline_label_f_0:{if(true){z=1;" + "break JSCompiler_inline_label_f_0}else{z=0;" + "break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInline4() { test("function f(x){a(x)} z = f(1)", "{a(1);z=void 0}"); } public void testComplexInline5() { test("function f(x,y){a(x)}var b=1;z=f(1,b)", "var b=1;{a(1);z=void 0}"); } public void testComplexInline6() { test("function f(x,y){if (x) y(); return true;}var b=1;z=f(1,b)", "var b=1;{if(1)b();z=true}"); } public void testComplexInline7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;z=f(1,b)", "var b=1;{JSCompiler_inline_label_f_4:{if(1){z=b();" + "break JSCompiler_inline_label_f_4}else{z=true;" + "break JSCompiler_inline_label_f_4}z=void 0}}"); } public void testComplexInline8() { test("function f(x){a(x)}var z=f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars1() { test("function f(){if (true){return;}else;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0}else;z=void 0}}"); } public void testComplexInlineVars2() { test("function f(){if (true){return;}else return;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{" + "if(true){z=void 0;break JSCompiler_inline_label_f_0" + "}else{" + "z=void 0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars3() { test("function f(){if (true){return 1;}else return 0;}var z=f();", "var z;{JSCompiler_inline_label_f_0:{if(true){" + "z=1;break JSCompiler_inline_label_f_0" + "}else{" + "z=0;break JSCompiler_inline_label_f_0}z=void 0}}"); } public void testComplexInlineVars4() { test("function f(x){a(x)}var z = f(1)", "var z;{a(1);z=void 0}"); } public void testComplexInlineVars5() { test("function f(x,y){a(x)}var b=1;var z=f(1,b)", "var b=1;var z;{a(1);z=void 0}"); } public void testComplexInlineVars6() { test("function f(x,y){if (x) y(); return true;}var b=1;var z=f(1,b)", "var b=1;var z;{if(1)b();z=true}"); } public void testComplexInlineVars7() { test("function f(x,y){if (x) return y(); else return true;}" + "var b=1;var z=f(1,b)", "var b=1;var z;" + "{JSCompiler_inline_label_f_4:{if(1){z=b();" + "break JSCompiler_inline_label_f_4" + "}else{" + "z=true;break JSCompiler_inline_label_f_4}z=void 0}}"); } public void testComplexInlineVars8() { test("function f(x){a(x)}var x;var z=f(1)", "var x;var z;{a(1);z=void 0}"); } public void testComplexInlineVars9() { test("function f(x){a(x)}var x;var z=f(1);var y", "var x;var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars10() { test("function f(x){a(x)}var x=blah();var z=f(1);var y=blah();", "var x=blah();var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineVars11() { test("function f(x){a(x)}var x=blah();var z=f(1);var y;", "var x=blah();var z;{a(1);z=void 0}var y"); } public void testComplexInlineVars12() { test("function f(x){a(x)}var x;var z=f(1);var y=blah();", "var x;var z;{a(1);z=void 0}var y=blah()"); } public void testComplexInlineInExpresssions1() { test("function f(){a()}var z=f()", "var z;{a();z=void 0}"); } public void testComplexInlineInExpresssions2() { test("function f(){a()}c=z=f()", "{var JSCompiler_inline_result$$0;a();}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions3() { test("function f(){a()}c=z=f()", "{var JSCompiler_inline_result$$0;a();}" + "c=z=JSCompiler_inline_result$$0"); } public void testComplexInlineInExpresssions4() { test("function f(){a()}if(z=f());", "{var JSCompiler_inline_result$$0;a();}" + "if(z=JSCompiler_inline_result$$0);"); } public void testComplexInlineInExpresssions5() { test("function f(){a()}if(z.y=f());", "var JSCompiler_temp_const$$0=z;" + "{var JSCompiler_inline_result$$1;a()}" + "if(JSCompiler_temp_const$$0.y=JSCompiler_inline_result$$1);"); } public void testComplexNoInline1() { testSame("function f(){a()}while(z=f())continue"); } public void testComplexNoInline2() { testSame("function f(){a()}do;while(z=f())"); } public void testComplexSample() { String result = "" + "{{" + "var styleSheet$$inline_9=null;" + "if(goog$userAgent$IE)" + "styleSheet$$inline_9=0;" + "else " + "var head$$inline_10=0;" + "{" + "var element$$inline_11=" + "styleSheet$$inline_9;" + "var stylesString$$inline_12=a;" + "if(goog$userAgent$IE)" + "element$$inline_11.cssText=" + "stylesString$$inline_12;" + "else " + "{" + "var propToSet$$inline_13=" + "\"innerText\";" + "element$$inline_11[" + "propToSet$$inline_13]=" + "stylesString$$inline_12" + "}" + "}" + "styleSheet$$inline_9" + "}}"; test("var foo = function(stylesString, opt_element) { " + "var styleSheet = null;" + "if (goog$userAgent$IE)" + "styleSheet = 0;" + "else " + "var head = 0;" + "" + "goo$zoo(styleSheet, stylesString);" + "return styleSheet;" + " };\n " + "var goo$zoo = function(element, stylesString) {" + "if (goog$userAgent$IE)" + "element.cssText = stylesString;" + "else {" + "var propToSet = 'innerText';" + "element[propToSet] = stylesString;" + "}" + "};" + "(function(){foo(a,b);})();", result); } public void testComplexSampleNoInline() { // This is the result we would expect if we could handle "foo = function" String result = "foo=function(stylesString,opt_element){" + "var styleSheet=null;" + "if(goog$userAgent$IE){" + "styleSheet=0" + "}else{" + "var head=0" + "}" + "{var JSCompiler_inline_element_0=styleSheet;" + "var JSCompiler_inline_stylesString_1=stylesString;" + "if(goog$userAgent$IE){" + "JSCompiler_inline_element_0.cssText=" + "JSCompiler_inline_stylesString_1" + "}else{" + "var propToSet=goog$userAgent$WEBKIT?\"innerText\":\"innerHTML\";" + "JSCompiler_inline_element_0[propToSet]=" + "JSCompiler_inline_stylesString_1" + "}}" + "return styleSheet" + "}"; testSame( "foo=function(stylesString,opt_element){" + "var styleSheet=null;" + "if(goog$userAgent$IE)" + "styleSheet=0;" + "else " + "var head=0;" + "" + "goo$zoo(styleSheet,stylesString);" + "return styleSheet" + "};" + "goo$zoo=function(element,stylesString){" + "if(goog$userAgent$IE)" + "element.cssText=stylesString;" + "else{" + "var propToSet=goog$userAgent$WEBKIT?\"innerText\":\"innerHTML\";" + "element[propToSet]=stylesString" + "}" + "}"); } // Test redefinition of parameter name. public void testComplexNoVarSub() { test( "function foo(x){" + "var x;" + "y=x" + "}" + "foo(1)", "{y=1}" ); } public void testComplexFunctionWithFunctionDefinition1() { test("function f(){call(function(){return})}f()", "{call(function(){return})}"); } public void testComplexFunctionWithFunctionDefinition2() { // Don't inline if local names might need to be captured. testSame("function f(a){call(function(){return})}f()"); } public void testComplexFunctionWithFunctionDefinition3() { // Don't inline if local names might need to be captured. testSame("function f(){var a; call(function(){return})}f()"); } public void testDecomposePlusEquals() { test("function f(){a=1;return 1} var x = 1; x += f()", "var x = 1;" + "var JSCompiler_temp_const$$0 = x;" + "{var JSCompiler_inline_result$$1; a=1;" + " JSCompiler_inline_result$$1=1}" + "x = JSCompiler_temp_const$$0 + JSCompiler_inline_result$$1;"); } public void testDecomposeFunctionExpressionInCall() { test( "(function(map){descriptions_=map})(\n" + "function(){\n" + "var ret={};\n" + "ret[ONE]='a';\n" + "ret[TWO]='b';\n" + "return ret\n" + "}()\n" + ");", "{" + "var JSCompiler_inline_result$$0;" + "var ret$$inline_2={};\n" + "ret$$inline_2[ONE]='a';\n" + "ret$$inline_2[TWO]='b';\n" + "JSCompiler_inline_result$$0 = ret$$inline_2;\n" + "}" + "{" + "descriptions_=JSCompiler_inline_result$$0;" + "}" ); } public void testInlineConstructor1() { test("function f() {} function _g() {f.call(this)}", "function _g() {void 0}"); } public void testInlineConstructor2() { test("function f() {} f.prototype.a = 0; function _g() {f.call(this)}", "function f() {} f.prototype.a = 0; function _g() {void 0}"); } public void testInlineConstructor3() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {{x.call(this)}}"); } public void testInlineConstructor4() { test("function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t = f.call(this)}", "function f() {x.call(this)} f.prototype.a = 0;" + "function _g() {var t; {x.call(this); t = void 0}}"); } public void testFunctionExpressionInlining1() { test("(function(){})()", "void 0"); } public void testFunctionExpressionInlining2() { test("(function(){foo()})()", "{foo()}"); } public void testFunctionExpressionInlining3() { test("var a = (function(){return foo()})()", "var a = foo()"); } public void testFunctionExpressionInlining4() { test("var a; a = 1 + (function(){return foo()})()", "var a; a = 1 + foo()"); } public void testFunctionExpressionCallInlining1() { test("(function(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining2() { test("(function(){foo(this)}).call(this)", "{foo(this)}"); } public void testFunctionExpressionCallInlining3() { test("var a = (function(){return foo(this)}).call(this)", "var a = foo(this)"); } public void testFunctionExpressionCallInlining4() { test("var a; a = 1 + (function(){return foo(this)}).call(this)", "var a; a = 1 + foo(this)"); } public void testFunctionExpressionCallInlining5() { test("a:(function(){return foo()})()", "a:foo()"); } public void testFunctionExpressionCallInlining6() { test("a:(function(){return foo()}).call(this)", "a:foo()"); } public void testFunctionExpressionCallInlining7() { test("a:(function(){})()", "a:void 0"); } public void testFunctionExpressionCallInlining8() { test("a:(function(){}).call(this)", "a:void 0"); } public void testFunctionExpressionCallInlining9() { // ... with unused recursive name. test("(function foo(){})()", "void 0"); } public void testFunctionExpressionCallInlining10() { // ... with unused recursive name. test("(function foo(){}).call(this)", "void 0"); } public void testFunctionExpressionCallInlining11a() { // Inline functions that return inner functions. test("((function(){return function(){foo()}})())();", "{foo()}"); } public void testFunctionExpressionCallInlining11b() { // Can't inline functions that return inner functions and have local names. testSame("((function(){var a; return function(){foo()}})())();"); } public void testFunctionExpressionCallInlining11c() { // Can't inline functions that return inner functions into non-global scope. testSame("function _x() {" + "((function(){return function(){foo()}})())();" + "}"); } public void testFunctionExpressionCallInlining12() { // Can't inline functions that recurse. testSame("(function foo(){foo()})()"); } public void testFunctionExpressionOmega() { // ... with unused recursive name. test("(function (f){f(f)})(function(f){f(f)})", "{var f$$inline_1=function(f$$1){f$$1(f$$1)};" + "{{f$$inline_1(f$$inline_1)}}}"); } public void testLocalFunctionInlining1() { test("function _f(){ function g() {} g() }", "function _f(){ void 0 }"); } public void testLocalFunctionInlining2() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining3() { test("function _f(){ function g() {foo(); bar();} g() }", "function _f(){ {foo(); bar();} }"); } public void testLocalFunctionInlining4() { test("function _f(){ function g() {return 1} return g() }", "function _f(){ return 1 }"); } public void testLocalFunctionInlining5() { testSame("function _f(){ function g() {this;} g() }"); } public void testLocalFunctionInlining6() { testSame("function _f(){ function g() {this;} return g; }"); } public void testLocalFunctionInliningOnly1() { this.allowGlobalFunctionInlining = true; test("function f(){} f()", "void 0;"); this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); } public void testLocalFunctionInliningOnly2() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("function f(){ function g() {return 1} return g() }; f();", "function f(){ return 1 }; f();"); } public void testLocalFunctionInliningOnly3() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ function g() {return 1} return g() })();", "(function(){ return 1 })();"); } public void testLocalFunctionInliningOnly4() { this.allowGlobalFunctionInlining = false; testSame("function f(){} f()"); test("(function(){ return (function() {return 1})() })();", "(function(){ return 1 })();"); } // http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator public void testFunctionExpressionYCombinator() { testSame( "var factorial = ((function(M) {\n" + " return ((function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " })\n" + " (function(f) {\n" + " return M(function(arg) {\n" + " return (f(f))(arg);\n" + " })\n" + " }));\n" + " })\n" + " (function(f) {\n" + " return function(n) {\n" + " if (n === 0)\n" + " return 1;\n" + " else\n" + " return n * f(n - 1);\n" + " };\n" + " }));\n" + "\n" + "factorial(5)\n"); } public void testRenamePropertyFunction() { testSame("function JSCompiler_renameProperty(x) {return x} " + "JSCompiler_renameProperty('foo')"); } public void testReplacePropertyFunction() { // baseline: an alias doesn't prevents declaration removal, but not // inlining. test("function f(x) {return x} " + "foo(window, f); f(1)", "function f(x) {return x} " + "foo(window, f); 1"); // a reference passed to JSCompiler_ObjectPropertyString prevents inlining // as well. testSame("function f(x) {return x} " + "new JSCompiler_ObjectPropertyString(window, f); f(1)"); } public void testIssue423() { test( "(function($) {\n" + " $.fn.multicheck = function(options) {\n" + " initialize.call(this, options);\n" + " };\n" + "\n" + " function initialize(options) {\n" + " options.checkboxes = $(this).siblings(':checkbox');\n" + " preload_check_all.call(this);\n" + " }\n" + "\n" + " function preload_check_all() {\n" + " $(this).data('checkboxes');\n" + " }\n" + "})(jQuery)", "(function($){" + " $.fn.multicheck=function(options$$1){" + " {" + " options$$1.checkboxes=$(this).siblings(\":checkbox\");" + " {" + " $(this).data(\"checkboxes\")" + " }" + " }" + " }" + "})(jQuery)"); } // Inline a single reference function into deeper modules public void testCrossModuleInlining1() { test(createModuleChain( // m1 "function foo(){return f(1)+g(2)+h(3);}", // m2 "foo()" ), new String[] { // m1 "", // m2 "f(1)+g(2)+h(3);" } ); } // Inline a single reference function into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining2() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}" ), new String[] { // m1 "f();", // m2 "" } ); } // Inline a multi-reference functions into shallow modules, only if it // is cheaper than the call itself. public void testCrossModuleInlining3() { testSame(createModuleChain( // m1 "foo()", // m2 "function foo(){return f(1)+g(2)+h(3);}", // m3 "foo()" ) ); test(createModuleChain( // m1 "foo()", // m2 "function foo(){return f();}", // m3 "foo()" ), new String[] { // m1 "f();", // m2 "", // m3 "f();" } ); } }
public void testInfiniteLoop() { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash }
org.apache.commons.cli.bug.BugCLI162Test::testInfiniteLoop
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
45
src/test/org/apache/commons/cli/bug/BugCLI162Test.java
testInfiniteLoop
/* * 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.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 { private Options options; public void setUp() { options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); } public void testInfiniteLoop() { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } private void testPrintHelp(Options options) throws ParseException, IOException { new HelpFormatter().printHelp(this.getClass().getName(), options); } 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); this.testPrintHelp(commandLineOptions); } }
// You are a professional Java test case writer, please create a test case named `testInfiniteLoop` 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 testInfiniteLoop() {
45
23
41
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 `testInfiniteLoop` for the issue `Cli-CLI-162`, utilizing the provided issue report information and the following function signature. ```java public void testInfiniteLoop() { ```
41
[ "org.apache.commons.cli.HelpFormatter" ]
d09fc3c5c2797149241ab2728d0e6b666d94448ddeaccb6ec3d6a25ceeee4965
public void testInfiniteLoop()
// You are a professional Java test case writer, please create a test case named `testInfiniteLoop` 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.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 { private Options options; public void setUp() { options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); } public void testInfiniteLoop() { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } private void testPrintHelp(Options options) throws ParseException, IOException { new HelpFormatter().printHelp(this.getClass().getName(), options); } 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); this.testPrintHelp(commandLineOptions); } }
public void testExceptNoNewLine() throws Exception { assertEquals("foo2:first line", provider.getSourceLine("foo2", 1)); assertEquals("foo2:second line", provider.getSourceLine("foo2", 2)); assertEquals("foo2:third line", provider.getSourceLine("foo2", 3)); assertEquals(null, provider.getSourceLine("foo2", 4)); }
com.google.javascript.jscomp.JSCompilerSourceExcerptProviderTest::testExceptNoNewLine
test/com/google/javascript/jscomp/JSCompilerSourceExcerptProviderTest.java
68
test/com/google/javascript/jscomp/JSCompilerSourceExcerptProviderTest.java
testExceptNoNewLine
/* * 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 junit.framework.TestCase; /** */ public class JSCompilerSourceExcerptProviderTest extends TestCase { private SourceExcerptProvider provider; @Override protected void setUp() throws Exception { JSSourceFile foo = JSSourceFile.fromCode("foo", "foo:first line\nfoo:second line\nfoo:third line\n"); JSSourceFile bar = JSSourceFile.fromCode("bar", "bar:first line\nbar:second line\nbar:third line\nbar:fourth line\n"); JSSourceFile foo2 = JSSourceFile.fromCode("foo2", "foo2:first line\nfoo2:second line\nfoo2:third line"); Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); compiler.init( new JSSourceFile[] {}, new JSSourceFile[] {foo, bar, foo2}, options); this.provider = compiler; } public void testExcerptOneLine() throws Exception { assertEquals("foo:first line", provider.getSourceLine("foo", 1)); assertEquals("foo:second line", provider.getSourceLine("foo", 2)); assertEquals("foo:third line", provider.getSourceLine("foo", 3)); assertEquals("bar:first line", provider.getSourceLine("bar", 1)); assertEquals("bar:second line", provider.getSourceLine("bar", 2)); assertEquals("bar:third line", provider.getSourceLine("bar", 3)); assertEquals("bar:fourth line", provider.getSourceLine("bar", 4)); } public void testExcerptLineFromInexistantSource() throws Exception { assertEquals(null, provider.getSourceLine("inexistant", 1)); assertEquals(null, provider.getSourceLine("inexistant", 7)); assertEquals(null, provider.getSourceLine("inexistant", 90)); } public void testExcerptInexistantLine() throws Exception { assertEquals(null, provider.getSourceLine("foo", 0)); assertEquals(null, provider.getSourceLine("foo", 4)); assertEquals(null, provider.getSourceLine("bar", 0)); assertEquals(null, provider.getSourceLine("bar", 5)); } public void testExceptNoNewLine() throws Exception { assertEquals("foo2:first line", provider.getSourceLine("foo2", 1)); assertEquals("foo2:second line", provider.getSourceLine("foo2", 2)); assertEquals("foo2:third line", provider.getSourceLine("foo2", 3)); assertEquals(null, provider.getSourceLine("foo2", 4)); } public void testExcerptRegion() throws Exception { assertRegionWellFormed("foo", 1); assertRegionWellFormed("foo", 2); assertRegionWellFormed("foo", 3); assertRegionWellFormed("bar", 1); assertRegionWellFormed("bar", 2); assertRegionWellFormed("bar", 3); assertRegionWellFormed("bar", 4); } public void testExcerptRegionFromInexistantSource() throws Exception { assertEquals(null, provider.getSourceRegion("inexistant", 0)); assertEquals(null, provider.getSourceRegion("inexistant", 6)); assertEquals(null, provider.getSourceRegion("inexistant", 90)); } public void testExcerptInexistantRegion() throws Exception { assertEquals(null, provider.getSourceRegion("foo", 0)); assertEquals(null, provider.getSourceRegion("foo", 4)); assertEquals(null, provider.getSourceRegion("bar", 0)); assertEquals(null, provider.getSourceRegion("bar", 5)); } /** * Asserts that a region is 'well formed': it must not be an empty and * cannot start or finish by a carriage return. In addition, it must * contain the line whose region we are taking. */ private void assertRegionWellFormed(String sourceName, int lineNumber) { Region region = provider.getSourceRegion(sourceName, lineNumber); assertNotNull(region); String sourceRegion = region.getSourceExcerpt(); assertNotNull(sourceRegion); if (lineNumber == 1) { assertEquals(1, region.getBeginningLineNumber()); } else { assertTrue(region.getBeginningLineNumber() <= lineNumber); } assertTrue(lineNumber <= region.getEndingLineNumber()); assertNotSame(sourceRegion, 0, sourceRegion.length()); assertNotSame(sourceRegion, '\n', sourceRegion.charAt(0)); assertNotSame(sourceRegion, '\n', sourceRegion.charAt(sourceRegion.length() - 1)); String line = provider.getSourceLine(sourceName, lineNumber); assertTrue(sourceRegion, sourceRegion.contains(line)); } }
// You are a professional Java test case writer, please create a test case named `testExceptNoNewLine` for the issue `Closure-511`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-511 // // ## Issue-Title: // Last warning or error in output is truncated // // ## Issue-Description: // The last error or warning statement written to the output appears to be getting truncated. It's causing a problem for my error / warning parser. // // To reproduce, create a file called test.js and add the following content to it: // // --------------- // alert(foo); // alert(bar); // --------------- // // When compiled, the output looks like this: // // --------------- // >java -jar compiler.jar --warning\_level VERBOSE --js test.js // test.js:1: ERROR - variable foo is undefined // alert(foo); // ^ // // test.js:2: ERROR - variable bar is undefined // // 2 error(s), 0 warning(s) // --------------- // // If you look at the last error includes neither the line the error occurred on nor the column-indicating caret. This happens with warnings as well. // // Tested against r1257 committed 2011-07-11 11:11:32 -0700. // // public void testExceptNoNewLine() throws Exception {
68
56
63
test/com/google/javascript/jscomp/JSCompilerSourceExcerptProviderTest.java
test
```markdown ## Issue-ID: Closure-511 ## Issue-Title: Last warning or error in output is truncated ## Issue-Description: The last error or warning statement written to the output appears to be getting truncated. It's causing a problem for my error / warning parser. To reproduce, create a file called test.js and add the following content to it: --------------- alert(foo); alert(bar); --------------- When compiled, the output looks like this: --------------- >java -jar compiler.jar --warning\_level VERBOSE --js test.js test.js:1: ERROR - variable foo is undefined alert(foo); ^ test.js:2: ERROR - variable bar is undefined 2 error(s), 0 warning(s) --------------- If you look at the last error includes neither the line the error occurred on nor the column-indicating caret. This happens with warnings as well. Tested against r1257 committed 2011-07-11 11:11:32 -0700. ``` You are a professional Java test case writer, please create a test case named `testExceptNoNewLine` for the issue `Closure-511`, utilizing the provided issue report information and the following function signature. ```java public void testExceptNoNewLine() throws Exception { ```
63
[ "com.google.javascript.jscomp.SourceFile" ]
d0aac51ee96afccaf8ced74cfa5179fd85f8631f460c3ca1d304877e728ce036
public void testExceptNoNewLine() throws Exception
// You are a professional Java test case writer, please create a test case named `testExceptNoNewLine` for the issue `Closure-511`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-511 // // ## Issue-Title: // Last warning or error in output is truncated // // ## Issue-Description: // The last error or warning statement written to the output appears to be getting truncated. It's causing a problem for my error / warning parser. // // To reproduce, create a file called test.js and add the following content to it: // // --------------- // alert(foo); // alert(bar); // --------------- // // When compiled, the output looks like this: // // --------------- // >java -jar compiler.jar --warning\_level VERBOSE --js test.js // test.js:1: ERROR - variable foo is undefined // alert(foo); // ^ // // test.js:2: ERROR - variable bar is undefined // // 2 error(s), 0 warning(s) // --------------- // // If you look at the last error includes neither the line the error occurred on nor the column-indicating caret. This happens with warnings as well. // // Tested against r1257 committed 2011-07-11 11:11:32 -0700. // //
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 junit.framework.TestCase; /** */ public class JSCompilerSourceExcerptProviderTest extends TestCase { private SourceExcerptProvider provider; @Override protected void setUp() throws Exception { JSSourceFile foo = JSSourceFile.fromCode("foo", "foo:first line\nfoo:second line\nfoo:third line\n"); JSSourceFile bar = JSSourceFile.fromCode("bar", "bar:first line\nbar:second line\nbar:third line\nbar:fourth line\n"); JSSourceFile foo2 = JSSourceFile.fromCode("foo2", "foo2:first line\nfoo2:second line\nfoo2:third line"); Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); compiler.init( new JSSourceFile[] {}, new JSSourceFile[] {foo, bar, foo2}, options); this.provider = compiler; } public void testExcerptOneLine() throws Exception { assertEquals("foo:first line", provider.getSourceLine("foo", 1)); assertEquals("foo:second line", provider.getSourceLine("foo", 2)); assertEquals("foo:third line", provider.getSourceLine("foo", 3)); assertEquals("bar:first line", provider.getSourceLine("bar", 1)); assertEquals("bar:second line", provider.getSourceLine("bar", 2)); assertEquals("bar:third line", provider.getSourceLine("bar", 3)); assertEquals("bar:fourth line", provider.getSourceLine("bar", 4)); } public void testExcerptLineFromInexistantSource() throws Exception { assertEquals(null, provider.getSourceLine("inexistant", 1)); assertEquals(null, provider.getSourceLine("inexistant", 7)); assertEquals(null, provider.getSourceLine("inexistant", 90)); } public void testExcerptInexistantLine() throws Exception { assertEquals(null, provider.getSourceLine("foo", 0)); assertEquals(null, provider.getSourceLine("foo", 4)); assertEquals(null, provider.getSourceLine("bar", 0)); assertEquals(null, provider.getSourceLine("bar", 5)); } public void testExceptNoNewLine() throws Exception { assertEquals("foo2:first line", provider.getSourceLine("foo2", 1)); assertEquals("foo2:second line", provider.getSourceLine("foo2", 2)); assertEquals("foo2:third line", provider.getSourceLine("foo2", 3)); assertEquals(null, provider.getSourceLine("foo2", 4)); } public void testExcerptRegion() throws Exception { assertRegionWellFormed("foo", 1); assertRegionWellFormed("foo", 2); assertRegionWellFormed("foo", 3); assertRegionWellFormed("bar", 1); assertRegionWellFormed("bar", 2); assertRegionWellFormed("bar", 3); assertRegionWellFormed("bar", 4); } public void testExcerptRegionFromInexistantSource() throws Exception { assertEquals(null, provider.getSourceRegion("inexistant", 0)); assertEquals(null, provider.getSourceRegion("inexistant", 6)); assertEquals(null, provider.getSourceRegion("inexistant", 90)); } public void testExcerptInexistantRegion() throws Exception { assertEquals(null, provider.getSourceRegion("foo", 0)); assertEquals(null, provider.getSourceRegion("foo", 4)); assertEquals(null, provider.getSourceRegion("bar", 0)); assertEquals(null, provider.getSourceRegion("bar", 5)); } /** * Asserts that a region is 'well formed': it must not be an empty and * cannot start or finish by a carriage return. In addition, it must * contain the line whose region we are taking. */ private void assertRegionWellFormed(String sourceName, int lineNumber) { Region region = provider.getSourceRegion(sourceName, lineNumber); assertNotNull(region); String sourceRegion = region.getSourceExcerpt(); assertNotNull(sourceRegion); if (lineNumber == 1) { assertEquals(1, region.getBeginningLineNumber()); } else { assertTrue(region.getBeginningLineNumber() <= lineNumber); } assertTrue(lineNumber <= region.getEndingLineNumber()); assertNotSame(sourceRegion, 0, sourceRegion.length()); assertNotSame(sourceRegion, '\n', sourceRegion.charAt(0)); assertNotSame(sourceRegion, '\n', sourceRegion.charAt(sourceRegion.length() - 1)); String line = provider.getSourceLine(sourceName, lineNumber); assertTrue(sourceRegion, sourceRegion.contains(line)); } }
@Test public void testCOMPRESS335() throws Exception { final ArchiveInputStream tar = getStreamFor("COMPRESS-335.tar"); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); }
org.apache.commons.compress.DetectArchiverTestCase::testCOMPRESS335
src/test/java/org/apache/commons/compress/DetectArchiverTestCase.java
62
src/test/java/org/apache/commons/compress/DetectArchiverTestCase.java
testCOMPRESS335
/* * 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; import static org.junit.Assert.*; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; import org.apache.commons.compress.archivers.arj.ArjArchiveInputStream; import org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.junit.Test; public final class DetectArchiverTestCase extends AbstractTestCase { final ClassLoader classLoader = getClass().getClassLoader(); @Test public void testDetectionNotArchive() throws IOException { try { getStreamFor("test.txt"); fail("Expected ArchiveException"); } catch (ArchiveException e) { // expected } } @Test public void testCOMPRESS117() throws Exception { final ArchiveInputStream tar = getStreamFor("COMPRESS-117.tar"); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); } @Test public void testCOMPRESS335() throws Exception { final ArchiveInputStream tar = getStreamFor("COMPRESS-335.tar"); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); } @Test public void testDetection() throws Exception { final ArchiveInputStream ar = getStreamFor("bla.ar"); assertNotNull(ar); assertTrue(ar instanceof ArArchiveInputStream); final ArchiveInputStream tar = getStreamFor("bla.tar"); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); final ArchiveInputStream zip = getStreamFor("bla.zip"); assertNotNull(zip); assertTrue(zip instanceof ZipArchiveInputStream); final ArchiveInputStream jar = getStreamFor("bla.jar"); assertNotNull(jar); assertTrue(jar instanceof ZipArchiveInputStream); final ArchiveInputStream cpio = getStreamFor("bla.cpio"); assertNotNull(cpio); assertTrue(cpio instanceof CpioArchiveInputStream); final ArchiveInputStream arj = getStreamFor("bla.arj"); assertNotNull(arj); assertTrue(arj instanceof ArjArchiveInputStream); // Not yet implemented // final ArchiveInputStream tgz = getStreamFor("bla.tgz"); // assertNotNull(tgz); // assertTrue(tgz instanceof TarArchiveInputStream); } private ArchiveInputStream getStreamFor(String resource) throws ArchiveException, IOException { return factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( getFile(resource)))); } // Check that the empty archives created by the code are readable // Not possible to detect empty "ar" archive as it is completely empty // public void testEmptyArArchive() throws Exception { // emptyArchive("ar"); // } @Test public void testEmptyCpioArchive() throws Exception { checkEmptyArchive("cpio"); } @Test public void testEmptyJarArchive() throws Exception { checkEmptyArchive("jar"); } // empty tar archives just have 512 null bytes // public void testEmptyTarArchive() throws Exception { // checkEmptyArchive("tar"); // } @Test public void testEmptyZipArchive() throws Exception { checkEmptyArchive("zip"); } private void checkEmptyArchive(String type) throws Exception{ File ar = createEmptyArchive(type); // will be deleted by tearDown() ar.deleteOnExit(); // Just in case file cannot be deleted ArchiveInputStream ais = null; BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(ar)); ais = factory.createArchiveInputStream(in); } catch (ArchiveException ae) { fail("Should have recognised empty archive for "+type); } finally { if (ais != null) { ais.close(); // will close input as well } else if (in != null){ in.close(); } } } }
// You are a professional Java test case writer, please create a test case named `testCOMPRESS335` for the issue `Compress-COMPRESS-335`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-335 // // ## Issue-Title: // TAR checksum fails when checksum is right aligned // // ## Issue-Description: // // The linked TAR has a checksum with zero padding on the left instead of the expected NULL-SPACE terminator on the right. As a result the last two digits of the stored checksum are lost and the otherwise valid checksum is treated as invalid. // // // Given that the code already checks for digits being in range before adding them to the stored sum, is it necessary to only look at the first 6 octal digits instead of the whole field? // // // // // @Test public void testCOMPRESS335() throws Exception {
62
35
57
src/test/java/org/apache/commons/compress/DetectArchiverTestCase.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-335 ## Issue-Title: TAR checksum fails when checksum is right aligned ## Issue-Description: The linked TAR has a checksum with zero padding on the left instead of the expected NULL-SPACE terminator on the right. As a result the last two digits of the stored checksum are lost and the otherwise valid checksum is treated as invalid. Given that the code already checks for digits being in range before adding them to the stored sum, is it necessary to only look at the first 6 octal digits instead of the whole field? ``` You are a professional Java test case writer, please create a test case named `testCOMPRESS335` for the issue `Compress-COMPRESS-335`, utilizing the provided issue report information and the following function signature. ```java @Test public void testCOMPRESS335() throws Exception { ```
57
[ "org.apache.commons.compress.archivers.tar.TarUtils" ]
d14a17cecd0574444c928158a483c2667610e59ca3930d756359503c99a013dc
@Test public void testCOMPRESS335() throws Exception
// You are a professional Java test case writer, please create a test case named `testCOMPRESS335` for the issue `Compress-COMPRESS-335`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-335 // // ## Issue-Title: // TAR checksum fails when checksum is right aligned // // ## Issue-Description: // // The linked TAR has a checksum with zero padding on the left instead of the expected NULL-SPACE terminator on the right. As a result the last two digits of the stored checksum are lost and the otherwise valid checksum is treated as invalid. // // // Given that the code already checks for digits being in range before adding them to the stored sum, is it necessary to only look at the first 6 octal digits instead of the whole field? // // // // //
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; import static org.junit.Assert.*; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; import org.apache.commons.compress.archivers.arj.ArjArchiveInputStream; import org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.junit.Test; public final class DetectArchiverTestCase extends AbstractTestCase { final ClassLoader classLoader = getClass().getClassLoader(); @Test public void testDetectionNotArchive() throws IOException { try { getStreamFor("test.txt"); fail("Expected ArchiveException"); } catch (ArchiveException e) { // expected } } @Test public void testCOMPRESS117() throws Exception { final ArchiveInputStream tar = getStreamFor("COMPRESS-117.tar"); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); } @Test public void testCOMPRESS335() throws Exception { final ArchiveInputStream tar = getStreamFor("COMPRESS-335.tar"); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); } @Test public void testDetection() throws Exception { final ArchiveInputStream ar = getStreamFor("bla.ar"); assertNotNull(ar); assertTrue(ar instanceof ArArchiveInputStream); final ArchiveInputStream tar = getStreamFor("bla.tar"); assertNotNull(tar); assertTrue(tar instanceof TarArchiveInputStream); final ArchiveInputStream zip = getStreamFor("bla.zip"); assertNotNull(zip); assertTrue(zip instanceof ZipArchiveInputStream); final ArchiveInputStream jar = getStreamFor("bla.jar"); assertNotNull(jar); assertTrue(jar instanceof ZipArchiveInputStream); final ArchiveInputStream cpio = getStreamFor("bla.cpio"); assertNotNull(cpio); assertTrue(cpio instanceof CpioArchiveInputStream); final ArchiveInputStream arj = getStreamFor("bla.arj"); assertNotNull(arj); assertTrue(arj instanceof ArjArchiveInputStream); // Not yet implemented // final ArchiveInputStream tgz = getStreamFor("bla.tgz"); // assertNotNull(tgz); // assertTrue(tgz instanceof TarArchiveInputStream); } private ArchiveInputStream getStreamFor(String resource) throws ArchiveException, IOException { return factory.createArchiveInputStream( new BufferedInputStream(new FileInputStream( getFile(resource)))); } // Check that the empty archives created by the code are readable // Not possible to detect empty "ar" archive as it is completely empty // public void testEmptyArArchive() throws Exception { // emptyArchive("ar"); // } @Test public void testEmptyCpioArchive() throws Exception { checkEmptyArchive("cpio"); } @Test public void testEmptyJarArchive() throws Exception { checkEmptyArchive("jar"); } // empty tar archives just have 512 null bytes // public void testEmptyTarArchive() throws Exception { // checkEmptyArchive("tar"); // } @Test public void testEmptyZipArchive() throws Exception { checkEmptyArchive("zip"); } private void checkEmptyArchive(String type) throws Exception{ File ar = createEmptyArchive(type); // will be deleted by tearDown() ar.deleteOnExit(); // Just in case file cannot be deleted ArchiveInputStream ais = null; BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(ar)); ais = factory.createArchiveInputStream(in); } catch (ArchiveException ae) { fail("Should have recognised empty archive for "+type); } finally { if (ais != null) { ais.close(); // will close input as well } else if (in != null){ in.close(); } } } }
public void testUnwrappedAsPropertyIndicator() throws Exception { Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; String actual = MAPPER.writeValueAsString(outer); assertTrue(actual.contains("animal")); assertTrue(actual.contains("Zebra")); assertFalse(actual.contains("inner")); }
com.fasterxml.jackson.databind.struct.TestUnwrapped::testUnwrappedAsPropertyIndicator
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
193
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
testUnwrappedAsPropertyIndicator
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; /** * Unit tests for verifying that basic {@link JsonUnwrapped} annotation * handling works as expected; some more advanced tests are separated out * to more specific test classes (like prefix/suffix handling). */ public class TestUnwrapped extends BaseMapTest { static class Unwrapping { public String name; @JsonUnwrapped public Location location; public Unwrapping() { } public Unwrapping(String str, int x, int y) { name = str; location = new Location(x, y); } } static class DeepUnwrapping { @JsonUnwrapped public Unwrapping unwrapped; public DeepUnwrapping() { } public DeepUnwrapping(String str, int x, int y) { unwrapped = new Unwrapping(str, x, y); } } static class UnwrappingWithCreator { public String name; @JsonUnwrapped public Location location; @JsonCreator public UnwrappingWithCreator(@JsonProperty("name") String n) { name = n; } } final static class Location { public int x; public int y; public Location() { } public Location(int x, int y) { this.x = x; this.y = y; } } // Class with two unwrapped properties static class TwoUnwrappedProperties { @JsonUnwrapped public Location location; @JsonUnwrapped public Name name; public TwoUnwrappedProperties() { } } static class Name { public String first, last; } // [databind#615] static class Parent { @JsonUnwrapped public Child c1; public Parent() { } public Parent(String str) { c1 = new Child(str); } } static class Child { public String field; public Child() { } public Child(String f) { field = f; } } static class Inner { public String animal; } static class Outer { // @JsonProperty @JsonUnwrapped private Inner inner; } /* /********************************************************** /* Tests, serialization /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new Unwrapping("Tatu", 1, 2))); } public void testDeepUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new DeepUnwrapping("Tatu", 1, 2))); } /* /********************************************************** /* Tests, deserialization /********************************************************** */ public void testSimpleUnwrappedDeserialize() throws Exception { Unwrapping bean = MAPPER.readValue("{\"name\":\"Tatu\",\"y\":7,\"x\":-13}", Unwrapping.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); } public void testDoubleUnwrapping() throws Exception { TwoUnwrappedProperties bean = MAPPER.readValue("{\"first\":\"Joe\",\"y\":7,\"last\":\"Smith\",\"x\":-13}", TwoUnwrappedProperties.class); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); Name name = bean.name; assertNotNull(name); assertEquals("Joe", name.first); assertEquals("Smith", name.last); } public void testDeepUnwrapping() throws Exception { DeepUnwrapping bean = MAPPER.readValue("{\"x\":3,\"name\":\"Bob\",\"y\":27}", DeepUnwrapping.class); Unwrapping uw = bean.unwrapped; assertNotNull(uw); assertEquals("Bob", uw.name); Location loc = uw.location; assertNotNull(loc); assertEquals(3, loc.x); assertEquals(27, loc.y); } public void testUnwrappedDeserializeWithCreator() throws Exception { UnwrappingWithCreator bean = MAPPER.readValue("{\"x\":1,\"y\":2,\"name\":\"Tatu\"}", UnwrappingWithCreator.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(1, loc.x); assertEquals(2, loc.y); } public void testIssue615() throws Exception { Parent input = new Parent("name"); String json = MAPPER.writeValueAsString(input); Parent output = MAPPER.readValue(json, Parent.class); assertEquals("name", output.c1.field); } public void testUnwrappedAsPropertyIndicator() throws Exception { Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; String actual = MAPPER.writeValueAsString(outer); assertTrue(actual.contains("animal")); assertTrue(actual.contains("Zebra")); assertFalse(actual.contains("inner")); } // 22-Apr-2013, tatu: Commented out as it can't be simply fixed; requires implementing // deep-update/merge. But leaving here to help with that effort, if/when it proceeds. /* // [databind#211]: Actually just variant of #160 static class Issue211Bean { public String test1; public String test2; @JsonUnwrapped public Issue211Unwrapped unwrapped; } static class Issue211Unwrapped { public String test3; public String test4; } public void testIssue211() throws Exception { Issue211Bean bean = new Issue211Bean(); bean.test1 = "Field 1"; bean.test2 = "Field 2"; Issue211Unwrapped tJackson2 = new Issue211Unwrapped(); tJackson2.test3 = "Field 3"; tJackson2.test4 = "Field 4"; bean.unwrapped = tJackson2; final String JSON = "{\"test1\": \"Field 1 merged\", \"test3\": \"Field 3 merged\"}"; ObjectMapper o = new ObjectMapper(); Issue211Bean result = o.readerForUpdating(bean).withType(Issue211Bean.class).readValue(JSON); assertSame(bean, result); assertEquals("Field 1 merged", result.test1); assertEquals("Field 2", result.test2); assertNotNull(result.unwrapped); assertEquals("Field 3 merged", result.unwrapped.test3); assertEquals("Field 4", result.unwrapped.test4); } */ }
// You are a professional Java test case writer, please create a test case named `testUnwrappedAsPropertyIndicator` for the issue `JacksonDatabind-1013`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1013 // // ## Issue-Title: // @JsonUnwrapped is not treated as assuming @JsonProperty("") // // ## Issue-Description: // See discussion [here](https://groups.google.com/forum/#!topic/jackson-user/QLpWb8YzIoE) but basically `@JsonUnwrapped` on a private field by itself does not cause that field to be serialized, currently, You need to add an explicit `@JsonProperty`. You shouldn't have to do that. (Following test fails currently, should pass, though you can make it pass by commenting out the line with `@JsonProperty`. Uses TestNG and AssertJ.) // // // // ``` // package com.bakins\_bits; // // import static org.assertj.core.api.Assertions.assertThat; // // import org.testng.annotations.Test; // // import com.fasterxml.jackson.annotation.JsonUnwrapped; // import com.fasterxml.jackson.core.JsonProcessingException; // import com.fasterxml.jackson.databind.ObjectMapper; // // public class TestJsonUnwrappedShouldMakePrivateFieldsSerializable // { // public static class Inner // { // public String animal; // } // // public static class Outer // { // // @JsonProperty // @JsonUnwrapped // private Inner inner; // } // // @Test // public void jsonUnwrapped\_should\_make\_private\_fields\_serializable() throws JsonProcessingException { // // ARRANGE // Inner inner = new Inner(); // inner.animal = "Zebra"; // // Outer outer = new Outer(); // outer.inner = inner; // // ObjectMapper sut = new ObjectMapper(); // // // ACT // String actual = sut.writeValueAsString(outer); // // // ASSERT // assertThat(actual).contains("animal"); // assertThat(actual).contains("Zebra"); // assertThat(actual).doesNotContain("inner"); // } // } // ``` // // // public void testUnwrappedAsPropertyIndicator() throws Exception {
193
33
180
src/test/java/com/fasterxml/jackson/databind/struct/TestUnwrapped.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-1013 ## Issue-Title: @JsonUnwrapped is not treated as assuming @JsonProperty("") ## Issue-Description: See discussion [here](https://groups.google.com/forum/#!topic/jackson-user/QLpWb8YzIoE) but basically `@JsonUnwrapped` on a private field by itself does not cause that field to be serialized, currently, You need to add an explicit `@JsonProperty`. You shouldn't have to do that. (Following test fails currently, should pass, though you can make it pass by commenting out the line with `@JsonProperty`. Uses TestNG and AssertJ.) ``` package com.bakins\_bits; import static org.assertj.core.api.Assertions.assertThat; import org.testng.annotations.Test; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class TestJsonUnwrappedShouldMakePrivateFieldsSerializable { public static class Inner { public String animal; } public static class Outer { // @JsonProperty @JsonUnwrapped private Inner inner; } @Test public void jsonUnwrapped\_should\_make\_private\_fields\_serializable() throws JsonProcessingException { // ARRANGE Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; ObjectMapper sut = new ObjectMapper(); // ACT String actual = sut.writeValueAsString(outer); // ASSERT assertThat(actual).contains("animal"); assertThat(actual).contains("Zebra"); assertThat(actual).doesNotContain("inner"); } } ``` ``` You are a professional Java test case writer, please create a test case named `testUnwrappedAsPropertyIndicator` for the issue `JacksonDatabind-1013`, utilizing the provided issue report information and the following function signature. ```java public void testUnwrappedAsPropertyIndicator() throws Exception { ```
180
[ "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector" ]
d15c65e65a4ddeef657af3684ca7cd6d8240e4c858f5b25ec2c7204a856f3752
public void testUnwrappedAsPropertyIndicator() throws Exception
// You are a professional Java test case writer, please create a test case named `testUnwrappedAsPropertyIndicator` for the issue `JacksonDatabind-1013`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-1013 // // ## Issue-Title: // @JsonUnwrapped is not treated as assuming @JsonProperty("") // // ## Issue-Description: // See discussion [here](https://groups.google.com/forum/#!topic/jackson-user/QLpWb8YzIoE) but basically `@JsonUnwrapped` on a private field by itself does not cause that field to be serialized, currently, You need to add an explicit `@JsonProperty`. You shouldn't have to do that. (Following test fails currently, should pass, though you can make it pass by commenting out the line with `@JsonProperty`. Uses TestNG and AssertJ.) // // // // ``` // package com.bakins\_bits; // // import static org.assertj.core.api.Assertions.assertThat; // // import org.testng.annotations.Test; // // import com.fasterxml.jackson.annotation.JsonUnwrapped; // import com.fasterxml.jackson.core.JsonProcessingException; // import com.fasterxml.jackson.databind.ObjectMapper; // // public class TestJsonUnwrappedShouldMakePrivateFieldsSerializable // { // public static class Inner // { // public String animal; // } // // public static class Outer // { // // @JsonProperty // @JsonUnwrapped // private Inner inner; // } // // @Test // public void jsonUnwrapped\_should\_make\_private\_fields\_serializable() throws JsonProcessingException { // // ARRANGE // Inner inner = new Inner(); // inner.animal = "Zebra"; // // Outer outer = new Outer(); // outer.inner = inner; // // ObjectMapper sut = new ObjectMapper(); // // // ACT // String actual = sut.writeValueAsString(outer); // // // ASSERT // assertThat(actual).contains("animal"); // assertThat(actual).contains("Zebra"); // assertThat(actual).doesNotContain("inner"); // } // } // ``` // // //
JacksonDatabind
package com.fasterxml.jackson.databind.struct; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; /** * Unit tests for verifying that basic {@link JsonUnwrapped} annotation * handling works as expected; some more advanced tests are separated out * to more specific test classes (like prefix/suffix handling). */ public class TestUnwrapped extends BaseMapTest { static class Unwrapping { public String name; @JsonUnwrapped public Location location; public Unwrapping() { } public Unwrapping(String str, int x, int y) { name = str; location = new Location(x, y); } } static class DeepUnwrapping { @JsonUnwrapped public Unwrapping unwrapped; public DeepUnwrapping() { } public DeepUnwrapping(String str, int x, int y) { unwrapped = new Unwrapping(str, x, y); } } static class UnwrappingWithCreator { public String name; @JsonUnwrapped public Location location; @JsonCreator public UnwrappingWithCreator(@JsonProperty("name") String n) { name = n; } } final static class Location { public int x; public int y; public Location() { } public Location(int x, int y) { this.x = x; this.y = y; } } // Class with two unwrapped properties static class TwoUnwrappedProperties { @JsonUnwrapped public Location location; @JsonUnwrapped public Name name; public TwoUnwrappedProperties() { } } static class Name { public String first, last; } // [databind#615] static class Parent { @JsonUnwrapped public Child c1; public Parent() { } public Parent(String str) { c1 = new Child(str); } } static class Child { public String field; public Child() { } public Child(String f) { field = f; } } static class Inner { public String animal; } static class Outer { // @JsonProperty @JsonUnwrapped private Inner inner; } /* /********************************************************** /* Tests, serialization /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); public void testSimpleUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new Unwrapping("Tatu", 1, 2))); } public void testDeepUnwrappingSerialize() throws Exception { assertEquals("{\"name\":\"Tatu\",\"x\":1,\"y\":2}", MAPPER.writeValueAsString(new DeepUnwrapping("Tatu", 1, 2))); } /* /********************************************************** /* Tests, deserialization /********************************************************** */ public void testSimpleUnwrappedDeserialize() throws Exception { Unwrapping bean = MAPPER.readValue("{\"name\":\"Tatu\",\"y\":7,\"x\":-13}", Unwrapping.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); } public void testDoubleUnwrapping() throws Exception { TwoUnwrappedProperties bean = MAPPER.readValue("{\"first\":\"Joe\",\"y\":7,\"last\":\"Smith\",\"x\":-13}", TwoUnwrappedProperties.class); Location loc = bean.location; assertNotNull(loc); assertEquals(-13, loc.x); assertEquals(7, loc.y); Name name = bean.name; assertNotNull(name); assertEquals("Joe", name.first); assertEquals("Smith", name.last); } public void testDeepUnwrapping() throws Exception { DeepUnwrapping bean = MAPPER.readValue("{\"x\":3,\"name\":\"Bob\",\"y\":27}", DeepUnwrapping.class); Unwrapping uw = bean.unwrapped; assertNotNull(uw); assertEquals("Bob", uw.name); Location loc = uw.location; assertNotNull(loc); assertEquals(3, loc.x); assertEquals(27, loc.y); } public void testUnwrappedDeserializeWithCreator() throws Exception { UnwrappingWithCreator bean = MAPPER.readValue("{\"x\":1,\"y\":2,\"name\":\"Tatu\"}", UnwrappingWithCreator.class); assertEquals("Tatu", bean.name); Location loc = bean.location; assertNotNull(loc); assertEquals(1, loc.x); assertEquals(2, loc.y); } public void testIssue615() throws Exception { Parent input = new Parent("name"); String json = MAPPER.writeValueAsString(input); Parent output = MAPPER.readValue(json, Parent.class); assertEquals("name", output.c1.field); } public void testUnwrappedAsPropertyIndicator() throws Exception { Inner inner = new Inner(); inner.animal = "Zebra"; Outer outer = new Outer(); outer.inner = inner; String actual = MAPPER.writeValueAsString(outer); assertTrue(actual.contains("animal")); assertTrue(actual.contains("Zebra")); assertFalse(actual.contains("inner")); } // 22-Apr-2013, tatu: Commented out as it can't be simply fixed; requires implementing // deep-update/merge. But leaving here to help with that effort, if/when it proceeds. /* // [databind#211]: Actually just variant of #160 static class Issue211Bean { public String test1; public String test2; @JsonUnwrapped public Issue211Unwrapped unwrapped; } static class Issue211Unwrapped { public String test3; public String test4; } public void testIssue211() throws Exception { Issue211Bean bean = new Issue211Bean(); bean.test1 = "Field 1"; bean.test2 = "Field 2"; Issue211Unwrapped tJackson2 = new Issue211Unwrapped(); tJackson2.test3 = "Field 3"; tJackson2.test4 = "Field 4"; bean.unwrapped = tJackson2; final String JSON = "{\"test1\": \"Field 1 merged\", \"test3\": \"Field 3 merged\"}"; ObjectMapper o = new ObjectMapper(); Issue211Bean result = o.readerForUpdating(bean).withType(Issue211Bean.class).readValue(JSON); assertSame(bean, result); assertEquals("Field 1 merged", result.test1); assertEquals("Field 2", result.test2); assertNotNull(result.unwrapped); assertEquals("Field 3 merged", result.unwrapped.test3); assertEquals("Field 4", result.unwrapped.test4); } */ }
public void testJira567(){ Number[] n; // Valid array construction n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}); assertEquals(2,n.length); assertEquals(Number.class,n.getClass().getComponentType()); try { // Invalid - can't store Long in Integer array n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}); fail("Should have generated IllegalArgumentException"); } catch (IllegalArgumentException expected) { } }
org.apache.commons.lang3.ArrayUtilsAddTest::testJira567
src/test/org/apache/commons/lang3/ArrayUtilsAddTest.java
43
src/test/org/apache/commons/lang3/ArrayUtilsAddTest.java
testJira567
/* * 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.util.Arrays; import junit.framework.TestCase; /** * Tests ArrayUtils add methods. * * @author Gary D. Gregory * @version $Id$ */ public class ArrayUtilsAddTest extends TestCase { public void testJira567(){ Number[] n; // Valid array construction n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}); assertEquals(2,n.length); assertEquals(Number.class,n.getClass().getComponentType()); try { // Invalid - can't store Long in Integer array n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}); fail("Should have generated IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testAddObjectArrayBoolean() { boolean[] newArray; newArray = ArrayUtils.add((boolean[])null, false); assertTrue(Arrays.equals(new boolean[]{false}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((boolean[])null, true); assertTrue(Arrays.equals(new boolean[]{true}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); boolean[] array1 = new boolean[]{true, false, true}; newArray = ArrayUtils.add(array1, false); assertTrue(Arrays.equals(new boolean[]{true, false, true, false}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayByte() { byte[] newArray; newArray = ArrayUtils.add((byte[])null, (byte)0); assertTrue(Arrays.equals(new byte[]{0}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((byte[])null, (byte)1); assertTrue(Arrays.equals(new byte[]{1}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); byte[] array1 = new byte[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (byte)0); assertTrue(Arrays.equals(new byte[]{1, 2, 3, 0}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (byte)4); assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayChar() { char[] newArray; newArray = ArrayUtils.add((char[])null, (char)0); assertTrue(Arrays.equals(new char[]{0}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((char[])null, (char)1); assertTrue(Arrays.equals(new char[]{1}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); char[] array1 = new char[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (char)0); assertTrue(Arrays.equals(new char[]{1, 2, 3, 0}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (char)4); assertTrue(Arrays.equals(new char[]{1, 2, 3, 4}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayDouble() { double[] newArray; newArray = ArrayUtils.add((double[])null, 0); assertTrue(Arrays.equals(new double[]{0}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((double[])null, 1); assertTrue(Arrays.equals(new double[]{1}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); double[] array1 = new double[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new double[]{1, 2, 3, 0}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new double[]{1, 2, 3, 4}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayFloat() { float[] newArray; newArray = ArrayUtils.add((float[])null, 0); assertTrue(Arrays.equals(new float[]{0}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((float[])null, 1); assertTrue(Arrays.equals(new float[]{1}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); float[] array1 = new float[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new float[]{1, 2, 3, 0}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new float[]{1, 2, 3, 4}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayInt() { int[] newArray; newArray = ArrayUtils.add((int[])null, 0); assertTrue(Arrays.equals(new int[]{0}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((int[])null, 1); assertTrue(Arrays.equals(new int[]{1}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); int[] array1 = new int[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new int[]{1, 2, 3, 0}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new int[]{1, 2, 3, 4}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayLong() { long[] newArray; newArray = ArrayUtils.add((long[])null, 0); assertTrue(Arrays.equals(new long[]{0}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((long[])null, 1); assertTrue(Arrays.equals(new long[]{1}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); long[] array1 = new long[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new long[]{1, 2, 3, 0}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new long[]{1, 2, 3, 4}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayShort() { short[] newArray; newArray = ArrayUtils.add((short[])null, (short)0); assertTrue(Arrays.equals(new short[]{0}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((short[])null, (short)1); assertTrue(Arrays.equals(new short[]{1}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); short[] array1 = new short[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (short)0); assertTrue(Arrays.equals(new short[]{1, 2, 3, 0}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (short)4); assertTrue(Arrays.equals(new short[]{1, 2, 3, 4}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayObject() { Object[] newArray; newArray = ArrayUtils.add((Object[])null, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); //show that not casting is okay newArray = ArrayUtils.add(null, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((Object[])null, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); //show that not casting to Object[] is okay and will assume String based on "a" String[] newStringArray = ArrayUtils.add(null, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newStringArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newStringArray)); assertEquals(String.class, newStringArray.getClass().getComponentType()); String[] stringArray1 = new String[]{"a", "b", "c"}; newArray = ArrayUtils.add(stringArray1, null); assertTrue(Arrays.equals((new String[]{"a", "b", "c", null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, "d"); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "d"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); Number[] numberArray1 = new Number[]{new Integer(1), new Double(2)}; newArray = ArrayUtils.add(numberArray1, new Float(3)); assertTrue(Arrays.equals((new Number[]{new Integer(1), new Double(2), new Float(3)}), newArray)); assertEquals(Number.class, newArray.getClass().getComponentType()); numberArray1 = null; newArray = ArrayUtils.add(numberArray1, new Float(3)); assertTrue(Arrays.equals((new Float[]{new Float(3)}), newArray)); assertEquals(Float.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(numberArray1, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); } public void testAddObjectArrayToObjectArray() { assertNull(ArrayUtils.addAll((Object[]) null, (Object[]) null)); Object[] newArray; String[] stringArray1 = new String[]{"a", "b", "c"}; String[] stringArray2 = new String[]{"1", "2", "3"}; newArray = ArrayUtils.addAll(stringArray1, (String[]) null); assertNotSame(stringArray1, newArray); assertTrue(Arrays.equals(stringArray1, newArray)); assertTrue(Arrays.equals((new String[]{"a", "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(null, stringArray2); assertNotSame(stringArray2, newArray); assertTrue(Arrays.equals(stringArray2, newArray)); assertTrue(Arrays.equals((new String[]{"1", "2", "3"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(stringArray1, stringArray2); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "1", "2", "3"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, (String[]) null); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(null, ArrayUtils.EMPTY_STRING_ARRAY); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); String[] stringArrayNull = new String []{null}; newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull); assertTrue(Arrays.equals((new String[]{null, null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); // boolean assertTrue( Arrays.equals( new boolean[] { true, false, false, true }, ArrayUtils.addAll( new boolean[] { true, false }, new boolean[] { false, true } ) ) ); assertTrue( Arrays.equals( new boolean[] { false, true }, ArrayUtils.addAll( null, new boolean[] { false, true } ) ) ); assertTrue( Arrays.equals( new boolean[] { true, false }, ArrayUtils.addAll( new boolean[] { true, false }, null ) ) ); // char assertTrue( Arrays.equals( new char[] { 'a', 'b', 'c', 'd' }, ArrayUtils.addAll( new char[] { 'a', 'b' }, new char[] { 'c', 'd' } ) ) ); assertTrue( Arrays.equals( new char[] { 'c', 'd' }, ArrayUtils.addAll( null, new char[] { 'c', 'd' } ) ) ); assertTrue( Arrays.equals( new char[] { 'a', 'b' }, ArrayUtils.addAll( new char[] { 'a', 'b' }, null ) ) ); // byte assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1, (byte) 2, (byte) 3 }, ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, new byte[] { (byte) 2, (byte) 3 } ) ) ); assertTrue( Arrays.equals( new byte[] { (byte) 2, (byte) 3 }, ArrayUtils.addAll( null, new byte[] { (byte) 2, (byte) 3 } ) ) ); assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1 }, ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, null ) ) ); // short assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20, (short) 30, (short) 40 }, ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, new short[] { (short) 30, (short) 40 } ) ) ); assertTrue( Arrays.equals( new short[] { (short) 30, (short) 40 }, ArrayUtils.addAll( null, new short[] { (short) 30, (short) 40 } ) ) ); assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20 }, ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, null ) ) ); // int assertTrue( Arrays.equals( new int[] { 1, 1000, -1000, -1 }, ArrayUtils.addAll( new int[] { 1, 1000 }, new int[] { -1000, -1 } ) ) ); assertTrue( Arrays.equals( new int[] { -1000, -1 }, ArrayUtils.addAll( null, new int[] { -1000, -1 } ) ) ); assertTrue( Arrays.equals( new int[] { 1, 1000 }, ArrayUtils.addAll( new int[] { 1, 1000 }, null ) ) ); // long assertTrue( Arrays.equals( new long[] { 1L, -1L, 1000L, -1000L }, ArrayUtils.addAll( new long[] { 1L, -1L }, new long[] { 1000L, -1000L } ) ) ); assertTrue( Arrays.equals( new long[] { 1000L, -1000L }, ArrayUtils.addAll( null, new long[] { 1000L, -1000L } ) ) ); assertTrue( Arrays.equals( new long[] { 1L, -1L }, ArrayUtils.addAll( new long[] { 1L, -1L }, null ) ) ); // float assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f, 1.6f, 0.01f }, ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, new float[] { 1.6f, 0.01f } ) ) ); assertTrue( Arrays.equals( new float[] { 1.6f, 0.01f }, ArrayUtils.addAll( null, new float[] { 1.6f, 0.01f } ) ) ); assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f }, ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, null ) ) ); // double assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI, 0, 9.99 }, ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, new double[] { 0, 9.99 } ) ) ); assertTrue( Arrays.equals( new double[] { 0, 9.99 }, ArrayUtils.addAll( null, new double[] { 0, 9.99 } ) ) ); assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI }, ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, null ) ) ); } public void testAddObjectAtIndex() { Object[] newArray; newArray = ArrayUtils.add((Object[])null, 0, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((Object[])null, 0, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); String[] stringArray1 = new String[]{"a", "b", "c"}; newArray = ArrayUtils.add(stringArray1, 0, null); assertTrue(Arrays.equals((new String[]{null, "a", "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 1, null); assertTrue(Arrays.equals((new String[]{"a", null, "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 3, null); assertTrue(Arrays.equals((new String[]{"a", "b", "c", null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 3, "d"); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "d"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType()); Object[] o = new Object[] {"1", "2", "4"}; Object[] result = ArrayUtils.add(o, 2, "3"); Object[] result2 = ArrayUtils.add(o, 3, "5"); assertNotNull(result); assertEquals(4, result.length); assertEquals("1", result[0]); assertEquals("2", result[1]); assertEquals("3", result[2]); assertEquals("4", result[3]); assertNotNull(result2); assertEquals(4, result2.length); assertEquals("1", result2[0]); assertEquals("2", result2[1]); assertEquals("4", result2[2]); assertEquals("5", result2[3]); // boolean tests boolean[] booleanArray = ArrayUtils.add( null, 0, true ); assertTrue( Arrays.equals( new boolean[] { true }, booleanArray ) ); try { booleanArray = ArrayUtils.add( null, -1, true ); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false); assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) ); booleanArray = ArrayUtils.add( new boolean[] { false }, 1, true); assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) ); booleanArray = ArrayUtils.add( new boolean[] { true, false }, 1, true); assertTrue( Arrays.equals( new boolean[] { true, true, false }, booleanArray ) ); try { booleanArray = ArrayUtils.add( new boolean[] { true, false }, 4, true); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { booleanArray = ArrayUtils.add( new boolean[] { true, false }, -1, true); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // char tests char[] charArray = ArrayUtils.add( (char[]) null, 0, 'a' ); assertTrue( Arrays.equals( new char[] { 'a' }, charArray ) ); try { charArray = ArrayUtils.add( (char[]) null, -1, 'a' ); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b'); assertTrue( Arrays.equals( new char[] { 'b', 'a' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 0, 'c'); assertTrue( Arrays.equals( new char[] { 'c', 'a', 'b' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 1, 'k'); assertTrue( Arrays.equals( new char[] { 'a', 'k', 'b' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b', 'c' }, 1, 't'); assertTrue( Arrays.equals( new char[] { 'a', 't', 'b', 'c' }, charArray ) ); try { charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c'); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { charArray = ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c'); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // short tests short[] shortArray = ArrayUtils.add( new short[] { 1 }, 0, (short) 2); assertTrue( Arrays.equals( new short[] { 2, 1 }, shortArray ) ); try { shortArray = ArrayUtils.add( (short[]) null, -1, (short) 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10); assertTrue( Arrays.equals( new short[] { 2, 6, 10 }, shortArray ) ); shortArray = ArrayUtils.add( new short[] { 2, 6 }, 0, (short) -4); assertTrue( Arrays.equals( new short[] { -4, 2, 6 }, shortArray ) ); shortArray = ArrayUtils.add( new short[] { 2, 6, 3 }, 2, (short) 1); assertTrue( Arrays.equals( new short[] { 2, 6, 1, 3 }, shortArray ) ); try { shortArray = ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { shortArray = ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // byte tests byte[] byteArray = ArrayUtils.add( new byte[] { 1 }, 0, (byte) 2); assertTrue( Arrays.equals( new byte[] { 2, 1 }, byteArray ) ); try { byteArray = ArrayUtils.add( (byte[]) null, -1, (byte) 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3); assertTrue( Arrays.equals( new byte[] { 2, 6, 3 }, byteArray ) ); byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 0, (byte) 1); assertTrue( Arrays.equals( new byte[] { 1, 2, 6 }, byteArray ) ); byteArray = ArrayUtils.add( new byte[] { 2, 6, 3 }, 2, (byte) 1); assertTrue( Arrays.equals( new byte[] { 2, 6, 1, 3 }, byteArray ) ); try { byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { byteArray = ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // int tests int[] intArray = ArrayUtils.add( new int[] { 1 }, 0, 2); assertTrue( Arrays.equals( new int[] { 2, 1 }, intArray ) ); try { intArray = ArrayUtils.add( (int[]) null, -1, 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10); assertTrue( Arrays.equals( new int[] { 2, 6, 10 }, intArray ) ); intArray = ArrayUtils.add( new int[] { 2, 6 }, 0, -4); assertTrue( Arrays.equals( new int[] { -4, 2, 6 }, intArray ) ); intArray = ArrayUtils.add( new int[] { 2, 6, 3 }, 2, 1); assertTrue( Arrays.equals( new int[] { 2, 6, 1, 3 }, intArray ) ); try { intArray = ArrayUtils.add( new int[] { 2, 6 }, 4, 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { intArray = ArrayUtils.add( new int[] { 2, 6 }, -1, 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // long tests long[] longArray = ArrayUtils.add( new long[] { 1L }, 0, 2L); assertTrue( Arrays.equals( new long[] { 2L, 1L }, longArray ) ); try { longArray = ArrayUtils.add( (long[]) null, -1, 2L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L); assertTrue( Arrays.equals( new long[] { 2L, 6L, 10L }, longArray ) ); longArray = ArrayUtils.add( new long[] { 2L, 6L }, 0, -4L); assertTrue( Arrays.equals( new long[] { -4L, 2L, 6L }, longArray ) ); longArray = ArrayUtils.add( new long[] { 2L, 6L, 3L }, 2, 1L); assertTrue( Arrays.equals( new long[] { 2L, 6L, 1L, 3L }, longArray ) ); try { longArray = ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { longArray = ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // float tests float[] floatArray = ArrayUtils.add( new float[] { 1.1f }, 0, 2.2f); assertTrue( Arrays.equals( new float[] { 2.2f, 1.1f }, floatArray ) ); try { floatArray = ArrayUtils.add( (float[]) null, -1, 2.2f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f); assertTrue( Arrays.equals( new float[] { 2.3f, 6.4f, 10.5f }, floatArray ) ); floatArray = ArrayUtils.add( new float[] { 2.6f, 6.7f }, 0, -4.8f); assertTrue( Arrays.equals( new float[] { -4.8f, 2.6f, 6.7f }, floatArray ) ); floatArray = ArrayUtils.add( new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f); assertTrue( Arrays.equals( new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray ) ); try { floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // double tests double[] doubleArray = ArrayUtils.add( new double[] { 1.1 }, 0, 2.2); assertTrue( Arrays.equals( new double[] { 2.2, 1.1 }, doubleArray ) ); try { doubleArray = ArrayUtils.add( (double[]) null, -1, 2.2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5); assertTrue( Arrays.equals( new double[] { 2.3, 6.4, 10.5 }, doubleArray ) ); doubleArray = ArrayUtils.add( new double[] { 2.6, 6.7 }, 0, -4.8); assertTrue( Arrays.equals( new double[] { -4.8, 2.6, 6.7 }, doubleArray ) ); doubleArray = ArrayUtils.add( new double[] { 2.9, 6.0, 0.3 }, 2, 1.0); assertTrue( Arrays.equals( new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray ) ); try { doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } } }
// You are a professional Java test case writer, please create a test case named `testJira567` for the issue `Lang-LANG-567`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-567 // // ## Issue-Title: // ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed types very well // // ## Issue-Description: // // ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed array types very well. // // // The stack trace for // // // Number[] st = ArrayUtils.addAll(new Integer[] // // // {1} // , new Long[] // // // {2L} // ); // // // starts: // // // java.lang.ArrayStoreException // // at java.lang.System.arraycopy(Native Method) // // at org.apache.commons.lang3.ArrayUtils.addAll(ArrayUtils.java:2962) // // // which is not all that obvious. // // // It would be a lot clearer if the method threw an IlegalArgumentException or similar. // // // // // public void testJira567() {
43
37
31
src/test/org/apache/commons/lang3/ArrayUtilsAddTest.java
src/test
```markdown ## Issue-ID: Lang-LANG-567 ## Issue-Title: ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed types very well ## Issue-Description: ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed array types very well. The stack trace for Number[] st = ArrayUtils.addAll(new Integer[] {1} , new Long[] {2L} ); starts: java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at org.apache.commons.lang3.ArrayUtils.addAll(ArrayUtils.java:2962) which is not all that obvious. It would be a lot clearer if the method threw an IlegalArgumentException or similar. ``` You are a professional Java test case writer, please create a test case named `testJira567` for the issue `Lang-LANG-567`, utilizing the provided issue report information and the following function signature. ```java public void testJira567() { ```
31
[ "org.apache.commons.lang3.ArrayUtils" ]
d26df486d2f301eb72b0e7163db9da1f3860db2f6f4fd09fef700ffa902cecc6
public void testJira567()
// You are a professional Java test case writer, please create a test case named `testJira567` for the issue `Lang-LANG-567`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-567 // // ## Issue-Title: // ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed types very well // // ## Issue-Description: // // ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed array types very well. // // // The stack trace for // // // Number[] st = ArrayUtils.addAll(new Integer[] // // // {1} // , new Long[] // // // {2L} // ); // // // starts: // // // java.lang.ArrayStoreException // // at java.lang.System.arraycopy(Native Method) // // at org.apache.commons.lang3.ArrayUtils.addAll(ArrayUtils.java:2962) // // // which is not all that obvious. // // // It would be a lot clearer if the method threw an IlegalArgumentException or similar. // // // // //
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.util.Arrays; import junit.framework.TestCase; /** * Tests ArrayUtils add methods. * * @author Gary D. Gregory * @version $Id$ */ public class ArrayUtilsAddTest extends TestCase { public void testJira567(){ Number[] n; // Valid array construction n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}); assertEquals(2,n.length); assertEquals(Number.class,n.getClass().getComponentType()); try { // Invalid - can't store Long in Integer array n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}); fail("Should have generated IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testAddObjectArrayBoolean() { boolean[] newArray; newArray = ArrayUtils.add((boolean[])null, false); assertTrue(Arrays.equals(new boolean[]{false}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((boolean[])null, true); assertTrue(Arrays.equals(new boolean[]{true}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); boolean[] array1 = new boolean[]{true, false, true}; newArray = ArrayUtils.add(array1, false); assertTrue(Arrays.equals(new boolean[]{true, false, true, false}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayByte() { byte[] newArray; newArray = ArrayUtils.add((byte[])null, (byte)0); assertTrue(Arrays.equals(new byte[]{0}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((byte[])null, (byte)1); assertTrue(Arrays.equals(new byte[]{1}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); byte[] array1 = new byte[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (byte)0); assertTrue(Arrays.equals(new byte[]{1, 2, 3, 0}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (byte)4); assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayChar() { char[] newArray; newArray = ArrayUtils.add((char[])null, (char)0); assertTrue(Arrays.equals(new char[]{0}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((char[])null, (char)1); assertTrue(Arrays.equals(new char[]{1}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); char[] array1 = new char[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (char)0); assertTrue(Arrays.equals(new char[]{1, 2, 3, 0}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (char)4); assertTrue(Arrays.equals(new char[]{1, 2, 3, 4}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayDouble() { double[] newArray; newArray = ArrayUtils.add((double[])null, 0); assertTrue(Arrays.equals(new double[]{0}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((double[])null, 1); assertTrue(Arrays.equals(new double[]{1}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); double[] array1 = new double[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new double[]{1, 2, 3, 0}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new double[]{1, 2, 3, 4}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayFloat() { float[] newArray; newArray = ArrayUtils.add((float[])null, 0); assertTrue(Arrays.equals(new float[]{0}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((float[])null, 1); assertTrue(Arrays.equals(new float[]{1}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); float[] array1 = new float[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new float[]{1, 2, 3, 0}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new float[]{1, 2, 3, 4}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayInt() { int[] newArray; newArray = ArrayUtils.add((int[])null, 0); assertTrue(Arrays.equals(new int[]{0}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((int[])null, 1); assertTrue(Arrays.equals(new int[]{1}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); int[] array1 = new int[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new int[]{1, 2, 3, 0}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new int[]{1, 2, 3, 4}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayLong() { long[] newArray; newArray = ArrayUtils.add((long[])null, 0); assertTrue(Arrays.equals(new long[]{0}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((long[])null, 1); assertTrue(Arrays.equals(new long[]{1}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); long[] array1 = new long[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new long[]{1, 2, 3, 0}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new long[]{1, 2, 3, 4}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayShort() { short[] newArray; newArray = ArrayUtils.add((short[])null, (short)0); assertTrue(Arrays.equals(new short[]{0}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((short[])null, (short)1); assertTrue(Arrays.equals(new short[]{1}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); short[] array1 = new short[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (short)0); assertTrue(Arrays.equals(new short[]{1, 2, 3, 0}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (short)4); assertTrue(Arrays.equals(new short[]{1, 2, 3, 4}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayObject() { Object[] newArray; newArray = ArrayUtils.add((Object[])null, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); //show that not casting is okay newArray = ArrayUtils.add(null, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((Object[])null, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); //show that not casting to Object[] is okay and will assume String based on "a" String[] newStringArray = ArrayUtils.add(null, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newStringArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newStringArray)); assertEquals(String.class, newStringArray.getClass().getComponentType()); String[] stringArray1 = new String[]{"a", "b", "c"}; newArray = ArrayUtils.add(stringArray1, null); assertTrue(Arrays.equals((new String[]{"a", "b", "c", null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, "d"); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "d"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); Number[] numberArray1 = new Number[]{new Integer(1), new Double(2)}; newArray = ArrayUtils.add(numberArray1, new Float(3)); assertTrue(Arrays.equals((new Number[]{new Integer(1), new Double(2), new Float(3)}), newArray)); assertEquals(Number.class, newArray.getClass().getComponentType()); numberArray1 = null; newArray = ArrayUtils.add(numberArray1, new Float(3)); assertTrue(Arrays.equals((new Float[]{new Float(3)}), newArray)); assertEquals(Float.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(numberArray1, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); } public void testAddObjectArrayToObjectArray() { assertNull(ArrayUtils.addAll((Object[]) null, (Object[]) null)); Object[] newArray; String[] stringArray1 = new String[]{"a", "b", "c"}; String[] stringArray2 = new String[]{"1", "2", "3"}; newArray = ArrayUtils.addAll(stringArray1, (String[]) null); assertNotSame(stringArray1, newArray); assertTrue(Arrays.equals(stringArray1, newArray)); assertTrue(Arrays.equals((new String[]{"a", "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(null, stringArray2); assertNotSame(stringArray2, newArray); assertTrue(Arrays.equals(stringArray2, newArray)); assertTrue(Arrays.equals((new String[]{"1", "2", "3"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(stringArray1, stringArray2); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "1", "2", "3"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, (String[]) null); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(null, ArrayUtils.EMPTY_STRING_ARRAY); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); String[] stringArrayNull = new String []{null}; newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull); assertTrue(Arrays.equals((new String[]{null, null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); // boolean assertTrue( Arrays.equals( new boolean[] { true, false, false, true }, ArrayUtils.addAll( new boolean[] { true, false }, new boolean[] { false, true } ) ) ); assertTrue( Arrays.equals( new boolean[] { false, true }, ArrayUtils.addAll( null, new boolean[] { false, true } ) ) ); assertTrue( Arrays.equals( new boolean[] { true, false }, ArrayUtils.addAll( new boolean[] { true, false }, null ) ) ); // char assertTrue( Arrays.equals( new char[] { 'a', 'b', 'c', 'd' }, ArrayUtils.addAll( new char[] { 'a', 'b' }, new char[] { 'c', 'd' } ) ) ); assertTrue( Arrays.equals( new char[] { 'c', 'd' }, ArrayUtils.addAll( null, new char[] { 'c', 'd' } ) ) ); assertTrue( Arrays.equals( new char[] { 'a', 'b' }, ArrayUtils.addAll( new char[] { 'a', 'b' }, null ) ) ); // byte assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1, (byte) 2, (byte) 3 }, ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, new byte[] { (byte) 2, (byte) 3 } ) ) ); assertTrue( Arrays.equals( new byte[] { (byte) 2, (byte) 3 }, ArrayUtils.addAll( null, new byte[] { (byte) 2, (byte) 3 } ) ) ); assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1 }, ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, null ) ) ); // short assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20, (short) 30, (short) 40 }, ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, new short[] { (short) 30, (short) 40 } ) ) ); assertTrue( Arrays.equals( new short[] { (short) 30, (short) 40 }, ArrayUtils.addAll( null, new short[] { (short) 30, (short) 40 } ) ) ); assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20 }, ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, null ) ) ); // int assertTrue( Arrays.equals( new int[] { 1, 1000, -1000, -1 }, ArrayUtils.addAll( new int[] { 1, 1000 }, new int[] { -1000, -1 } ) ) ); assertTrue( Arrays.equals( new int[] { -1000, -1 }, ArrayUtils.addAll( null, new int[] { -1000, -1 } ) ) ); assertTrue( Arrays.equals( new int[] { 1, 1000 }, ArrayUtils.addAll( new int[] { 1, 1000 }, null ) ) ); // long assertTrue( Arrays.equals( new long[] { 1L, -1L, 1000L, -1000L }, ArrayUtils.addAll( new long[] { 1L, -1L }, new long[] { 1000L, -1000L } ) ) ); assertTrue( Arrays.equals( new long[] { 1000L, -1000L }, ArrayUtils.addAll( null, new long[] { 1000L, -1000L } ) ) ); assertTrue( Arrays.equals( new long[] { 1L, -1L }, ArrayUtils.addAll( new long[] { 1L, -1L }, null ) ) ); // float assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f, 1.6f, 0.01f }, ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, new float[] { 1.6f, 0.01f } ) ) ); assertTrue( Arrays.equals( new float[] { 1.6f, 0.01f }, ArrayUtils.addAll( null, new float[] { 1.6f, 0.01f } ) ) ); assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f }, ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, null ) ) ); // double assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI, 0, 9.99 }, ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, new double[] { 0, 9.99 } ) ) ); assertTrue( Arrays.equals( new double[] { 0, 9.99 }, ArrayUtils.addAll( null, new double[] { 0, 9.99 } ) ) ); assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI }, ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, null ) ) ); } public void testAddObjectAtIndex() { Object[] newArray; newArray = ArrayUtils.add((Object[])null, 0, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((Object[])null, 0, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); String[] stringArray1 = new String[]{"a", "b", "c"}; newArray = ArrayUtils.add(stringArray1, 0, null); assertTrue(Arrays.equals((new String[]{null, "a", "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 1, null); assertTrue(Arrays.equals((new String[]{"a", null, "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 3, null); assertTrue(Arrays.equals((new String[]{"a", "b", "c", null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 3, "d"); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "d"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType()); Object[] o = new Object[] {"1", "2", "4"}; Object[] result = ArrayUtils.add(o, 2, "3"); Object[] result2 = ArrayUtils.add(o, 3, "5"); assertNotNull(result); assertEquals(4, result.length); assertEquals("1", result[0]); assertEquals("2", result[1]); assertEquals("3", result[2]); assertEquals("4", result[3]); assertNotNull(result2); assertEquals(4, result2.length); assertEquals("1", result2[0]); assertEquals("2", result2[1]); assertEquals("4", result2[2]); assertEquals("5", result2[3]); // boolean tests boolean[] booleanArray = ArrayUtils.add( null, 0, true ); assertTrue( Arrays.equals( new boolean[] { true }, booleanArray ) ); try { booleanArray = ArrayUtils.add( null, -1, true ); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false); assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) ); booleanArray = ArrayUtils.add( new boolean[] { false }, 1, true); assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) ); booleanArray = ArrayUtils.add( new boolean[] { true, false }, 1, true); assertTrue( Arrays.equals( new boolean[] { true, true, false }, booleanArray ) ); try { booleanArray = ArrayUtils.add( new boolean[] { true, false }, 4, true); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { booleanArray = ArrayUtils.add( new boolean[] { true, false }, -1, true); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // char tests char[] charArray = ArrayUtils.add( (char[]) null, 0, 'a' ); assertTrue( Arrays.equals( new char[] { 'a' }, charArray ) ); try { charArray = ArrayUtils.add( (char[]) null, -1, 'a' ); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b'); assertTrue( Arrays.equals( new char[] { 'b', 'a' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 0, 'c'); assertTrue( Arrays.equals( new char[] { 'c', 'a', 'b' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 1, 'k'); assertTrue( Arrays.equals( new char[] { 'a', 'k', 'b' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b', 'c' }, 1, 't'); assertTrue( Arrays.equals( new char[] { 'a', 't', 'b', 'c' }, charArray ) ); try { charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c'); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { charArray = ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c'); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // short tests short[] shortArray = ArrayUtils.add( new short[] { 1 }, 0, (short) 2); assertTrue( Arrays.equals( new short[] { 2, 1 }, shortArray ) ); try { shortArray = ArrayUtils.add( (short[]) null, -1, (short) 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10); assertTrue( Arrays.equals( new short[] { 2, 6, 10 }, shortArray ) ); shortArray = ArrayUtils.add( new short[] { 2, 6 }, 0, (short) -4); assertTrue( Arrays.equals( new short[] { -4, 2, 6 }, shortArray ) ); shortArray = ArrayUtils.add( new short[] { 2, 6, 3 }, 2, (short) 1); assertTrue( Arrays.equals( new short[] { 2, 6, 1, 3 }, shortArray ) ); try { shortArray = ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { shortArray = ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // byte tests byte[] byteArray = ArrayUtils.add( new byte[] { 1 }, 0, (byte) 2); assertTrue( Arrays.equals( new byte[] { 2, 1 }, byteArray ) ); try { byteArray = ArrayUtils.add( (byte[]) null, -1, (byte) 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3); assertTrue( Arrays.equals( new byte[] { 2, 6, 3 }, byteArray ) ); byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 0, (byte) 1); assertTrue( Arrays.equals( new byte[] { 1, 2, 6 }, byteArray ) ); byteArray = ArrayUtils.add( new byte[] { 2, 6, 3 }, 2, (byte) 1); assertTrue( Arrays.equals( new byte[] { 2, 6, 1, 3 }, byteArray ) ); try { byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { byteArray = ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // int tests int[] intArray = ArrayUtils.add( new int[] { 1 }, 0, 2); assertTrue( Arrays.equals( new int[] { 2, 1 }, intArray ) ); try { intArray = ArrayUtils.add( (int[]) null, -1, 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10); assertTrue( Arrays.equals( new int[] { 2, 6, 10 }, intArray ) ); intArray = ArrayUtils.add( new int[] { 2, 6 }, 0, -4); assertTrue( Arrays.equals( new int[] { -4, 2, 6 }, intArray ) ); intArray = ArrayUtils.add( new int[] { 2, 6, 3 }, 2, 1); assertTrue( Arrays.equals( new int[] { 2, 6, 1, 3 }, intArray ) ); try { intArray = ArrayUtils.add( new int[] { 2, 6 }, 4, 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { intArray = ArrayUtils.add( new int[] { 2, 6 }, -1, 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // long tests long[] longArray = ArrayUtils.add( new long[] { 1L }, 0, 2L); assertTrue( Arrays.equals( new long[] { 2L, 1L }, longArray ) ); try { longArray = ArrayUtils.add( (long[]) null, -1, 2L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L); assertTrue( Arrays.equals( new long[] { 2L, 6L, 10L }, longArray ) ); longArray = ArrayUtils.add( new long[] { 2L, 6L }, 0, -4L); assertTrue( Arrays.equals( new long[] { -4L, 2L, 6L }, longArray ) ); longArray = ArrayUtils.add( new long[] { 2L, 6L, 3L }, 2, 1L); assertTrue( Arrays.equals( new long[] { 2L, 6L, 1L, 3L }, longArray ) ); try { longArray = ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { longArray = ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // float tests float[] floatArray = ArrayUtils.add( new float[] { 1.1f }, 0, 2.2f); assertTrue( Arrays.equals( new float[] { 2.2f, 1.1f }, floatArray ) ); try { floatArray = ArrayUtils.add( (float[]) null, -1, 2.2f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f); assertTrue( Arrays.equals( new float[] { 2.3f, 6.4f, 10.5f }, floatArray ) ); floatArray = ArrayUtils.add( new float[] { 2.6f, 6.7f }, 0, -4.8f); assertTrue( Arrays.equals( new float[] { -4.8f, 2.6f, 6.7f }, floatArray ) ); floatArray = ArrayUtils.add( new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f); assertTrue( Arrays.equals( new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray ) ); try { floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // double tests double[] doubleArray = ArrayUtils.add( new double[] { 1.1 }, 0, 2.2); assertTrue( Arrays.equals( new double[] { 2.2, 1.1 }, doubleArray ) ); try { doubleArray = ArrayUtils.add( (double[]) null, -1, 2.2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5); assertTrue( Arrays.equals( new double[] { 2.3, 6.4, 10.5 }, doubleArray ) ); doubleArray = ArrayUtils.add( new double[] { 2.6, 6.7 }, 0, -4.8); assertTrue( Arrays.equals( new double[] { -4.8, 2.6, 6.7 }, doubleArray ) ); doubleArray = ArrayUtils.add( new double[] { 2.9, 6.0, 0.3 }, 2, 1.0); assertTrue( Arrays.equals( new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray ) ); try { doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } } }
@Test public void absHandlesRelativeQuery() { Document doc = Jsoup.parse("<a href='?foo'>One</a> <a href='bar.html?foo'>Two</a>", "http://jsoup.org/path/file?bar"); Element a1 = doc.select("a").first(); assertEquals("http://jsoup.org/path/file?foo", a1.absUrl("href")); Element a2 = doc.select("a").get(1); assertEquals("http://jsoup.org/path/bar.html?foo", a2.absUrl("href")); }
org.jsoup.nodes.NodeTest::absHandlesRelativeQuery
src/test/java/org/jsoup/nodes/NodeTest.java
52
src/test/java/org/jsoup/nodes/NodeTest.java
absHandlesRelativeQuery
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.junit.Test; import static org.junit.Assert.*; /** Tests Nodes @author Jonathan Hedley, [email protected] */ public class NodeTest { @Test public void handlesBaseUri() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); attribs.put("relHref", "/foo"); attribs.put("absHref", "http://bar/qux"); Element noBase = new Element(tag, "", attribs); assertEquals("", noBase.absUrl("relHref")); // with no base, should NOT fallback to href attrib, whatever it is assertEquals("http://bar/qux", noBase.absUrl("absHref")); // no base but valid attrib, return attrib Element withBase = new Element(tag, "http://foo/", attribs); assertEquals("http://foo/foo", withBase.absUrl("relHref")); // construct abs from base + rel assertEquals("http://bar/qux", withBase.absUrl("absHref")); // href is abs, so returns that assertEquals("", withBase.absUrl("noval")); Element dodgyBase = new Element(tag, "wtf://no-such-protocol/", attribs); assertEquals("http://bar/qux", dodgyBase.absUrl("absHref")); // base fails, but href good, so get that assertEquals("", dodgyBase.absUrl("relHref")); // base fails, only rel href, so return nothing } @Test public void handlesAbsPrefix() { Document doc = Jsoup.parse("<a href=/foo>Hello</a>", "http://jsoup.org/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://jsoup.org/foo", a.attr("abs:href")); assertFalse(a.hasAttr("abs:href")); // only realised on the get method, not in has or iterator } /* Test for an issue with Java's abs URL handler. */ @Test public void absHandlesRelativeQuery() { Document doc = Jsoup.parse("<a href='?foo'>One</a> <a href='bar.html?foo'>Two</a>", "http://jsoup.org/path/file?bar"); Element a1 = doc.select("a").first(); assertEquals("http://jsoup.org/path/file?foo", a1.absUrl("href")); Element a2 = doc.select("a").get(1); assertEquals("http://jsoup.org/path/bar.html?foo", a2.absUrl("href")); } @Test public void testRemove() { Document doc = Jsoup.parse("<p>One <span>two</span> three</p>"); Element p = doc.select("p").first(); p.childNode(0).remove(); assertEquals("two three", p.text()); assertEquals("<span>two</span> three", TextUtil.stripNewlines(p.html())); } @Test public void testReplace() { Document doc = Jsoup.parse("<p>One <span>two</span> three</p>"); Element p = doc.select("p").first(); Element insert = doc.createElement("em").text("foo"); p.childNode(1).replaceWith(insert); assertEquals("One <em>foo</em> three", p.html()); } @Test public void ownerDocument() { Document doc = Jsoup.parse("<p>Hello"); Element p = doc.select("p").first(); assertTrue(p.ownerDocument() == doc); assertTrue(doc.ownerDocument() == doc); assertNull(doc.parent()); } }
// You are a professional Java test case writer, please create a test case named `absHandlesRelativeQuery` for the issue `Jsoup-49`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-49 // // ## Issue-Title: // attr("abs:href") , absUrl("href") // // ## Issue-Description: // Document doc = Jsoup.parse(new URL("<http://www.oschina.net/bbs/thread/12975>"), 5\*1000); // // Elements es = doc.select("a[href]"); // // for(Iterator it = es.iterator();it.hasNext();){ // // Element e = it.next(); // // System.out.println(e.absUrl("href")); // // } // // // attr("abs:href") ------ <a href="?p=1">1</a> // // result: ------------------- <http://www.oschina.net/bbs/thread/?p=1> // // // I think it's a wrong result~. // // The correct results should be "<http://www.oschina.net/bbs/thread/12975?p=1>" // // // // @Test public void absHandlesRelativeQuery() {
52
/* Test for an issue with Java's abs URL handler. */
10
44
src/test/java/org/jsoup/nodes/NodeTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-49 ## Issue-Title: attr("abs:href") , absUrl("href") ## Issue-Description: Document doc = Jsoup.parse(new URL("<http://www.oschina.net/bbs/thread/12975>"), 5\*1000); Elements es = doc.select("a[href]"); for(Iterator it = es.iterator();it.hasNext();){ Element e = it.next(); System.out.println(e.absUrl("href")); } attr("abs:href") ------ <a href="?p=1">1</a> result: ------------------- <http://www.oschina.net/bbs/thread/?p=1> I think it's a wrong result~. The correct results should be "<http://www.oschina.net/bbs/thread/12975?p=1>" ``` You are a professional Java test case writer, please create a test case named `absHandlesRelativeQuery` for the issue `Jsoup-49`, utilizing the provided issue report information and the following function signature. ```java @Test public void absHandlesRelativeQuery() { ```
44
[ "org.jsoup.nodes.Node" ]
d2bfbc7dee53fa8f21e3ac6ee9c27d9b420c9fe9eb25fd15fad41ca393b5c076
@Test public void absHandlesRelativeQuery()
// You are a professional Java test case writer, please create a test case named `absHandlesRelativeQuery` for the issue `Jsoup-49`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-49 // // ## Issue-Title: // attr("abs:href") , absUrl("href") // // ## Issue-Description: // Document doc = Jsoup.parse(new URL("<http://www.oschina.net/bbs/thread/12975>"), 5\*1000); // // Elements es = doc.select("a[href]"); // // for(Iterator it = es.iterator();it.hasNext();){ // // Element e = it.next(); // // System.out.println(e.absUrl("href")); // // } // // // attr("abs:href") ------ <a href="?p=1">1</a> // // result: ------------------- <http://www.oschina.net/bbs/thread/?p=1> // // // I think it's a wrong result~. // // The correct results should be "<http://www.oschina.net/bbs/thread/12975?p=1>" // // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.junit.Test; import static org.junit.Assert.*; /** Tests Nodes @author Jonathan Hedley, [email protected] */ public class NodeTest { @Test public void handlesBaseUri() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); attribs.put("relHref", "/foo"); attribs.put("absHref", "http://bar/qux"); Element noBase = new Element(tag, "", attribs); assertEquals("", noBase.absUrl("relHref")); // with no base, should NOT fallback to href attrib, whatever it is assertEquals("http://bar/qux", noBase.absUrl("absHref")); // no base but valid attrib, return attrib Element withBase = new Element(tag, "http://foo/", attribs); assertEquals("http://foo/foo", withBase.absUrl("relHref")); // construct abs from base + rel assertEquals("http://bar/qux", withBase.absUrl("absHref")); // href is abs, so returns that assertEquals("", withBase.absUrl("noval")); Element dodgyBase = new Element(tag, "wtf://no-such-protocol/", attribs); assertEquals("http://bar/qux", dodgyBase.absUrl("absHref")); // base fails, but href good, so get that assertEquals("", dodgyBase.absUrl("relHref")); // base fails, only rel href, so return nothing } @Test public void handlesAbsPrefix() { Document doc = Jsoup.parse("<a href=/foo>Hello</a>", "http://jsoup.org/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://jsoup.org/foo", a.attr("abs:href")); assertFalse(a.hasAttr("abs:href")); // only realised on the get method, not in has or iterator } /* Test for an issue with Java's abs URL handler. */ @Test public void absHandlesRelativeQuery() { Document doc = Jsoup.parse("<a href='?foo'>One</a> <a href='bar.html?foo'>Two</a>", "http://jsoup.org/path/file?bar"); Element a1 = doc.select("a").first(); assertEquals("http://jsoup.org/path/file?foo", a1.absUrl("href")); Element a2 = doc.select("a").get(1); assertEquals("http://jsoup.org/path/bar.html?foo", a2.absUrl("href")); } @Test public void testRemove() { Document doc = Jsoup.parse("<p>One <span>two</span> three</p>"); Element p = doc.select("p").first(); p.childNode(0).remove(); assertEquals("two three", p.text()); assertEquals("<span>two</span> three", TextUtil.stripNewlines(p.html())); } @Test public void testReplace() { Document doc = Jsoup.parse("<p>One <span>two</span> three</p>"); Element p = doc.select("p").first(); Element insert = doc.createElement("em").text("foo"); p.childNode(1).replaceWith(insert); assertEquals("One <em>foo</em> three", p.html()); } @Test public void ownerDocument() { Document doc = Jsoup.parse("<p>Hello"); Element p = doc.select("p").first(); assertTrue(p.ownerDocument() == doc); assertTrue(doc.ownerDocument() == doc); assertNull(doc.parent()); } }
@Test public void testConstrainedRosenWithMoreInterpolationPoints() { final double[] startPoint = point(DIM, 0.1); final double[][] boundaries = boundaries(DIM, -1, 2); final RealPointValuePair expected = new RealPointValuePair(point(DIM, 1.0), 0.0); // This should have been 78 because in the code the hard limit is // said to be // ((DIM + 1) * (DIM + 2)) / 2 - (2 * DIM + 1) // i.e. 78 in this case, but the test fails for 48, 59, 62, 63, 64, // 65, 66, ... final int maxAdditionalPoints = 47; for (int num = 1; num <= maxAdditionalPoints; num++) { doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-12, 1e-6, 2000, num, expected, "num=" + num); } }
org.apache.commons.math.optimization.direct.BOBYQAOptimizerTest::testConstrainedRosenWithMoreInterpolationPoints
src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java
261
src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java
testConstrainedRosenWithMoreInterpolationPoints
/* * 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.direct; import java.util.Arrays; import java.util.Random; import org.apache.commons.math.analysis.MultivariateFunction; import org.apache.commons.math.exception.DimensionMismatchException; import org.apache.commons.math.exception.TooManyEvaluationsException; import org.apache.commons.math.exception.NumberIsTooLargeException; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Assert; import org.junit.Test; /** * Test for {@link BOBYQAOptimizer}. */ public class BOBYQAOptimizerTest { static final int DIM = 13; @Test(expected=NumberIsTooLargeException.class) public void testInitOutOfBounds() { double[] startPoint = point(DIM, 3); double[][] boundaries = boundaries(DIM, -1, 2); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, null); } @Test(expected=DimensionMismatchException.class) public void testBoundariesDimensionMismatch() { double[] startPoint = point(DIM, 0.5); double[][] boundaries = boundaries(DIM + 1, -1, 2); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, null); } @Test(expected=NumberIsTooSmallException.class) public void testProblemDimensionTooSmall() { double[] startPoint = point(1, 0.5); doTest(new Rosen(), startPoint, null, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, null); } @Test(expected=TooManyEvaluationsException.class) public void testMaxEvaluations() { final int lowMaxEval = 2; double[] startPoint = point(DIM, 0.1); double[][] boundaries = null; doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, lowMaxEval, null); } @Test public void testRosen() { double[] startPoint = point(DIM,0.1); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, expected); } @Test public void testMaximize() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),1.0); doTest(new MinusElli(), startPoint, boundaries, GoalType.MAXIMIZE, 2e-10, 5e-6, 1000, expected); boundaries = boundaries(DIM,-0.3,0.3); startPoint = point(DIM,0.1); doTest(new MinusElli(), startPoint, boundaries, GoalType.MAXIMIZE, 2e-10, 5e-6, 1000, expected); } @Test public void testEllipse() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Elli(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 1000, expected); } @Test public void testElliRotated() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new ElliRotated(), startPoint, boundaries, GoalType.MINIMIZE, 1e-12, 1e-6, 10000, expected); } @Test public void testCigar() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Cigar(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 100, expected); } @Test public void testTwoAxes() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new TwoAxes(), startPoint, boundaries, GoalType.MINIMIZE, 2* 1e-13, 1e-6, 100, expected); } @Test public void testCigTab() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new CigTab(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 5e-5, 100, expected); } @Test public void testSphere() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Sphere(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 100, expected); } @Test public void testTablet() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Tablet(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 100, expected); } @Test public void testDiffPow() {} // Defects4J: flaky method // @Test // public void testDiffPow() { // double[] startPoint = point(DIM/2,1.0); // double[][] boundaries = null; // RealPointValuePair expected = // new RealPointValuePair(point(DIM/2,0.0),0.0); // doTest(new DiffPow(), startPoint, boundaries, // GoalType.MINIMIZE, // 1e-8, 1e-1, 12000, expected); // } @Test public void testSsDiffPow() { double[] startPoint = point(DIM/2,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM/2,0.0),0.0); doTest(new SsDiffPow(), startPoint, boundaries, GoalType.MINIMIZE, 1e-2, 1.3e-1, 50000, expected); } @Test public void testAckley() {} // Defects4J: flaky method // @Test // public void testAckley() { // double[] startPoint = point(DIM,0.1); // double[][] boundaries = null; // RealPointValuePair expected = // new RealPointValuePair(point(DIM,0.0),0.0); // doTest(new Ackley(), startPoint, boundaries, // GoalType.MINIMIZE, // 1e-8, 1e-5, 1000, expected); // } @Test public void testRastrigin() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Rastrigin(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 1000, expected); } @Test public void testConstrainedRosen() { double[] startPoint = point(DIM,0.1); double[][] boundaries = boundaries(DIM,-1,2); RealPointValuePair expected = new RealPointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, expected); } // See MATH-728 @Test public void testConstrainedRosenWithMoreInterpolationPoints() { final double[] startPoint = point(DIM, 0.1); final double[][] boundaries = boundaries(DIM, -1, 2); final RealPointValuePair expected = new RealPointValuePair(point(DIM, 1.0), 0.0); // This should have been 78 because in the code the hard limit is // said to be // ((DIM + 1) * (DIM + 2)) / 2 - (2 * DIM + 1) // i.e. 78 in this case, but the test fails for 48, 59, 62, 63, 64, // 65, 66, ... final int maxAdditionalPoints = 47; for (int num = 1; num <= maxAdditionalPoints; num++) { doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-12, 1e-6, 2000, num, expected, "num=" + num); } } /** * @param func Function to optimize. * @param startPoint Starting point. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[][] boundaries, GoalType goal, double fTol, double pointTol, int maxEvaluations, RealPointValuePair expected) { doTest(func, startPoint, boundaries, goal, fTol, pointTol, maxEvaluations, 0, expected, ""); } /** * @param func Function to optimize. * @param startPoint Starting point. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param additionalInterpolationPoints Number of interpolation to used * in addition to the default (2 * dim + 1). * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[][] boundaries, GoalType goal, double fTol, double pointTol, int maxEvaluations, int additionalInterpolationPoints, RealPointValuePair expected, String assertMsg) { System.out.println(func.getClass().getName() + " BEGIN"); // XXX int dim = startPoint.length; // MultivariateOptimizer optim = // new PowellOptimizer(1e-13, Math.ulp(1d)); // RealPointValuePair result = optim.optimize(100000, func, goal, startPoint); final double[] lB = boundaries == null ? null : boundaries[0]; final double[] uB = boundaries == null ? null : boundaries[1]; final int numIterpolationPoints = 2 * dim + 1 + additionalInterpolationPoints; BOBYQAOptimizer optim = new BOBYQAOptimizer(numIterpolationPoints); RealPointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); // System.out.println(func.getClass().getName() + " = " // + optim.getEvaluations() + " f("); // for (double x: result.getPoint()) System.out.print(x + " "); // System.out.println(") = " + result.getValue()); Assert.assertEquals(assertMsg, expected.getValue(), result.getValue(), fTol); for (int i = 0; i < dim; i++) { Assert.assertEquals(expected.getPoint()[i], result.getPoint()[i], pointTol); } System.out.println(func.getClass().getName() + " END"); // XXX } private static double[] point(int n, double value) { double[] ds = new double[n]; Arrays.fill(ds, value); return ds; } private static double[][] boundaries(int dim, double lower, double upper) { double[][] boundaries = new double[2][dim]; for (int i = 0; i < dim; i++) boundaries[0][i] = lower; for (int i = 0; i < dim; i++) boundaries[1][i] = upper; return boundaries; } private static class Sphere implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class Cigar implements MultivariateFunction { private double factor; Cigar() { this(1e3); } Cigar(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += factor * x[i] * x[i]; return f; } } private static class Tablet implements MultivariateFunction { private double factor; Tablet() { this(1e3); } Tablet(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = factor * x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class CigTab implements MultivariateFunction { private double factor; CigTab() { this(1e4); } CigTab(double axisratio) { factor = axisratio; } public double value(double[] x) { int end = x.length - 1; double f = x[0] * x[0] / factor + factor * x[end] * x[end]; for (int i = 1; i < end; ++i) f += x[i] * x[i]; return f; } } private static class TwoAxes implements MultivariateFunction { private double factor; TwoAxes() { this(1e6); } TwoAxes(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += (i < x.length / 2 ? factor : 1) * x[i] * x[i]; return f; } } private static class ElliRotated implements MultivariateFunction { private Basis B = new Basis(); private double factor; ElliRotated() { this(1e3); } ElliRotated(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; x = B.Rotate(x); for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class Elli implements MultivariateFunction { private double factor; Elli() { this(1e3); } Elli(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class MinusElli implements MultivariateFunction { private final Elli elli = new Elli(); public double value(double[] x) { return 1.0 - elli.value(x); } } private static class DiffPow implements MultivariateFunction { // private int fcount = 0; public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(Math.abs(x[i]), 2. + 10 * (double) i / (x.length - 1.)); // System.out.print("" + (fcount++) + ") "); // for (int i = 0; i < x.length; i++) // System.out.print(x[i] + " "); // System.out.println(" = " + f); return f; } } private static class SsDiffPow implements MultivariateFunction { public double value(double[] x) { double f = Math.pow(new DiffPow().value(x), 0.25); return f; } } private static class Rosen implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length - 1; ++i) f += 1e2 * (x[i] * x[i] - x[i + 1]) * (x[i] * x[i] - x[i + 1]) + (x[i] - 1.) * (x[i] - 1.); return f; } } private static class Ackley implements MultivariateFunction { private double axisratio; Ackley(double axra) { axisratio = axra; } public Ackley() { this(1); } public double value(double[] x) { double f = 0; double res2 = 0; double fac = 0; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); f += fac * fac * x[i] * x[i]; res2 += Math.cos(2. * Math.PI * fac * x[i]); } f = (20. - 20. * Math.exp(-0.2 * Math.sqrt(f / x.length)) + Math.exp(1.) - Math.exp(res2 / x.length)); return f; } } private static class Rastrigin implements MultivariateFunction { private double axisratio; private double amplitude; Rastrigin() { this(1, 10); } Rastrigin(double axisratio, double amplitude) { this.axisratio = axisratio; this.amplitude = amplitude; } public double value(double[] x) { double f = 0; double fac; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); if (i == 0 && x[i] < 0) fac *= 1.; f += fac * fac * x[i] * x[i] + amplitude * (1. - Math.cos(2. * Math.PI * fac * x[i])); } return f; } } private static class Basis { double[][] basis; Random rand = new Random(2); // use not always the same basis double[] Rotate(double[] x) { GenBasis(x.length); double[] y = new double[x.length]; for (int i = 0; i < x.length; ++i) { y[i] = 0; for (int j = 0; j < x.length; ++j) y[i] += basis[i][j] * x[j]; } return y; } void GenBasis(int DIM) { if (basis != null ? basis.length == DIM : false) return; double sp; int i, j, k; /* generate orthogonal basis */ basis = new double[DIM][DIM]; for (i = 0; i < DIM; ++i) { /* sample components gaussian */ for (j = 0; j < DIM; ++j) basis[i][j] = rand.nextGaussian(); /* substract projection of previous vectors */ for (j = i - 1; j >= 0; --j) { for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[j][k]; /* scalar product */ for (k = 0; k < DIM; ++k) basis[i][k] -= sp * basis[j][k]; /* substract */ } /* normalize */ for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[i][k]; /* squared norm */ for (k = 0; k < DIM; ++k) basis[i][k] /= Math.sqrt(sp); } } } }
// You are a professional Java test case writer, please create a test case named `testConstrainedRosenWithMoreInterpolationPoints` for the issue `Math-MATH-728`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-728 // // ## Issue-Title: // Errors in BOBYQAOptimizer when numberOfInterpolationPoints is greater than 2*dim+1 // // ## Issue-Description: // // I've been having trouble getting BOBYQA to minimize a function (actually a non-linear least squares fit) so as one change I increased the number of interpolation points. It seems that anything larger than 2\*dim+1 causes an error (typically at // // // line 1662 // // interpolationPoints.setEntry(nfm, ipt, interpolationPoints.getEntry(ipt, ipt)); // // // I'm guessing there is an off by one error in the translation from FORTRAN. Changing the BOBYQAOptimizerTest as follows (increasing number of interpolation points by one) will cause failures. // // // Bruce // // // Index: src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java // // =================================================================== // // — src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java (revision 1221065) // // +++ src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java (working copy) // // @@ -258,7 +258,7 @@ // // // RealPointValuePair result = optim.optimize(100000, func, goal, startPoint); // // final double[] lB = boundaries == null ? null : boundaries[0]; // // final double[] uB = boundaries == null ? null : boundaries[1]; // // // * BOBYQAOptimizer optim = new BOBYQAOptimizer(2 \* dim + 1); // // + BOBYQAOptimizer optim = new BOBYQAOptimizer(2 \* dim + 2); // // RealPointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); // // // System.out.println(func.getClass().getName() + " = " // // // + optim.getEvaluations() + " f("); // // // // // @Test public void testConstrainedRosenWithMoreInterpolationPoints() {
261
// See MATH-728
38
240
src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-728 ## Issue-Title: Errors in BOBYQAOptimizer when numberOfInterpolationPoints is greater than 2*dim+1 ## Issue-Description: I've been having trouble getting BOBYQA to minimize a function (actually a non-linear least squares fit) so as one change I increased the number of interpolation points. It seems that anything larger than 2\*dim+1 causes an error (typically at line 1662 interpolationPoints.setEntry(nfm, ipt, interpolationPoints.getEntry(ipt, ipt)); I'm guessing there is an off by one error in the translation from FORTRAN. Changing the BOBYQAOptimizerTest as follows (increasing number of interpolation points by one) will cause failures. Bruce Index: src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java =================================================================== — src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java (revision 1221065) +++ src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java (working copy) @@ -258,7 +258,7 @@ // RealPointValuePair result = optim.optimize(100000, func, goal, startPoint); final double[] lB = boundaries == null ? null : boundaries[0]; final double[] uB = boundaries == null ? null : boundaries[1]; * BOBYQAOptimizer optim = new BOBYQAOptimizer(2 \* dim + 1); + BOBYQAOptimizer optim = new BOBYQAOptimizer(2 \* dim + 2); RealPointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); // System.out.println(func.getClass().getName() + " = " // + optim.getEvaluations() + " f("); ``` You are a professional Java test case writer, please create a test case named `testConstrainedRosenWithMoreInterpolationPoints` for the issue `Math-MATH-728`, utilizing the provided issue report information and the following function signature. ```java @Test public void testConstrainedRosenWithMoreInterpolationPoints() { ```
240
[ "org.apache.commons.math.optimization.direct.BOBYQAOptimizer" ]
d301af613de1198c85f614ed521961393b671b3cc8ad87d4b9b0867825e77088
@Test public void testConstrainedRosenWithMoreInterpolationPoints()
// You are a professional Java test case writer, please create a test case named `testConstrainedRosenWithMoreInterpolationPoints` for the issue `Math-MATH-728`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-728 // // ## Issue-Title: // Errors in BOBYQAOptimizer when numberOfInterpolationPoints is greater than 2*dim+1 // // ## Issue-Description: // // I've been having trouble getting BOBYQA to minimize a function (actually a non-linear least squares fit) so as one change I increased the number of interpolation points. It seems that anything larger than 2\*dim+1 causes an error (typically at // // // line 1662 // // interpolationPoints.setEntry(nfm, ipt, interpolationPoints.getEntry(ipt, ipt)); // // // I'm guessing there is an off by one error in the translation from FORTRAN. Changing the BOBYQAOptimizerTest as follows (increasing number of interpolation points by one) will cause failures. // // // Bruce // // // Index: src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java // // =================================================================== // // — src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java (revision 1221065) // // +++ src/test/java/org/apache/commons/math/optimization/direct/BOBYQAOptimizerTest.java (working copy) // // @@ -258,7 +258,7 @@ // // // RealPointValuePair result = optim.optimize(100000, func, goal, startPoint); // // final double[] lB = boundaries == null ? null : boundaries[0]; // // final double[] uB = boundaries == null ? null : boundaries[1]; // // // * BOBYQAOptimizer optim = new BOBYQAOptimizer(2 \* dim + 1); // // + BOBYQAOptimizer optim = new BOBYQAOptimizer(2 \* dim + 2); // // RealPointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); // // // System.out.println(func.getClass().getName() + " = " // // // + optim.getEvaluations() + " f("); // // // // //
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.direct; import java.util.Arrays; import java.util.Random; import org.apache.commons.math.analysis.MultivariateFunction; import org.apache.commons.math.exception.DimensionMismatchException; import org.apache.commons.math.exception.TooManyEvaluationsException; import org.apache.commons.math.exception.NumberIsTooLargeException; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.RealPointValuePair; import org.junit.Assert; import org.junit.Test; /** * Test for {@link BOBYQAOptimizer}. */ public class BOBYQAOptimizerTest { static final int DIM = 13; @Test(expected=NumberIsTooLargeException.class) public void testInitOutOfBounds() { double[] startPoint = point(DIM, 3); double[][] boundaries = boundaries(DIM, -1, 2); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, null); } @Test(expected=DimensionMismatchException.class) public void testBoundariesDimensionMismatch() { double[] startPoint = point(DIM, 0.5); double[][] boundaries = boundaries(DIM + 1, -1, 2); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, null); } @Test(expected=NumberIsTooSmallException.class) public void testProblemDimensionTooSmall() { double[] startPoint = point(1, 0.5); doTest(new Rosen(), startPoint, null, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, null); } @Test(expected=TooManyEvaluationsException.class) public void testMaxEvaluations() { final int lowMaxEval = 2; double[] startPoint = point(DIM, 0.1); double[][] boundaries = null; doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, lowMaxEval, null); } @Test public void testRosen() { double[] startPoint = point(DIM,0.1); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, expected); } @Test public void testMaximize() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),1.0); doTest(new MinusElli(), startPoint, boundaries, GoalType.MAXIMIZE, 2e-10, 5e-6, 1000, expected); boundaries = boundaries(DIM,-0.3,0.3); startPoint = point(DIM,0.1); doTest(new MinusElli(), startPoint, boundaries, GoalType.MAXIMIZE, 2e-10, 5e-6, 1000, expected); } @Test public void testEllipse() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Elli(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 1000, expected); } @Test public void testElliRotated() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new ElliRotated(), startPoint, boundaries, GoalType.MINIMIZE, 1e-12, 1e-6, 10000, expected); } @Test public void testCigar() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Cigar(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 100, expected); } @Test public void testTwoAxes() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new TwoAxes(), startPoint, boundaries, GoalType.MINIMIZE, 2* 1e-13, 1e-6, 100, expected); } @Test public void testCigTab() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new CigTab(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 5e-5, 100, expected); } @Test public void testSphere() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Sphere(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 100, expected); } @Test public void testTablet() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Tablet(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 100, expected); } @Test public void testDiffPow() {} // Defects4J: flaky method // @Test // public void testDiffPow() { // double[] startPoint = point(DIM/2,1.0); // double[][] boundaries = null; // RealPointValuePair expected = // new RealPointValuePair(point(DIM/2,0.0),0.0); // doTest(new DiffPow(), startPoint, boundaries, // GoalType.MINIMIZE, // 1e-8, 1e-1, 12000, expected); // } @Test public void testSsDiffPow() { double[] startPoint = point(DIM/2,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM/2,0.0),0.0); doTest(new SsDiffPow(), startPoint, boundaries, GoalType.MINIMIZE, 1e-2, 1.3e-1, 50000, expected); } @Test public void testAckley() {} // Defects4J: flaky method // @Test // public void testAckley() { // double[] startPoint = point(DIM,0.1); // double[][] boundaries = null; // RealPointValuePair expected = // new RealPointValuePair(point(DIM,0.0),0.0); // doTest(new Ackley(), startPoint, boundaries, // GoalType.MINIMIZE, // 1e-8, 1e-5, 1000, expected); // } @Test public void testRastrigin() { double[] startPoint = point(DIM,1.0); double[][] boundaries = null; RealPointValuePair expected = new RealPointValuePair(point(DIM,0.0),0.0); doTest(new Rastrigin(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 1000, expected); } @Test public void testConstrainedRosen() { double[] startPoint = point(DIM,0.1); double[][] boundaries = boundaries(DIM,-1,2); RealPointValuePair expected = new RealPointValuePair(point(DIM,1.0),0.0); doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-13, 1e-6, 2000, expected); } // See MATH-728 @Test public void testConstrainedRosenWithMoreInterpolationPoints() { final double[] startPoint = point(DIM, 0.1); final double[][] boundaries = boundaries(DIM, -1, 2); final RealPointValuePair expected = new RealPointValuePair(point(DIM, 1.0), 0.0); // This should have been 78 because in the code the hard limit is // said to be // ((DIM + 1) * (DIM + 2)) / 2 - (2 * DIM + 1) // i.e. 78 in this case, but the test fails for 48, 59, 62, 63, 64, // 65, 66, ... final int maxAdditionalPoints = 47; for (int num = 1; num <= maxAdditionalPoints; num++) { doTest(new Rosen(), startPoint, boundaries, GoalType.MINIMIZE, 1e-12, 1e-6, 2000, num, expected, "num=" + num); } } /** * @param func Function to optimize. * @param startPoint Starting point. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[][] boundaries, GoalType goal, double fTol, double pointTol, int maxEvaluations, RealPointValuePair expected) { doTest(func, startPoint, boundaries, goal, fTol, pointTol, maxEvaluations, 0, expected, ""); } /** * @param func Function to optimize. * @param startPoint Starting point. * @param boundaries Upper / lower point limit. * @param goal Minimization or maximization. * @param fTol Tolerance relative error on the objective function. * @param pointTol Tolerance for checking that the optimum is correct. * @param maxEvaluations Maximum number of evaluations. * @param additionalInterpolationPoints Number of interpolation to used * in addition to the default (2 * dim + 1). * @param expected Expected point / value. */ private void doTest(MultivariateFunction func, double[] startPoint, double[][] boundaries, GoalType goal, double fTol, double pointTol, int maxEvaluations, int additionalInterpolationPoints, RealPointValuePair expected, String assertMsg) { System.out.println(func.getClass().getName() + " BEGIN"); // XXX int dim = startPoint.length; // MultivariateOptimizer optim = // new PowellOptimizer(1e-13, Math.ulp(1d)); // RealPointValuePair result = optim.optimize(100000, func, goal, startPoint); final double[] lB = boundaries == null ? null : boundaries[0]; final double[] uB = boundaries == null ? null : boundaries[1]; final int numIterpolationPoints = 2 * dim + 1 + additionalInterpolationPoints; BOBYQAOptimizer optim = new BOBYQAOptimizer(numIterpolationPoints); RealPointValuePair result = optim.optimize(maxEvaluations, func, goal, startPoint, lB, uB); // System.out.println(func.getClass().getName() + " = " // + optim.getEvaluations() + " f("); // for (double x: result.getPoint()) System.out.print(x + " "); // System.out.println(") = " + result.getValue()); Assert.assertEquals(assertMsg, expected.getValue(), result.getValue(), fTol); for (int i = 0; i < dim; i++) { Assert.assertEquals(expected.getPoint()[i], result.getPoint()[i], pointTol); } System.out.println(func.getClass().getName() + " END"); // XXX } private static double[] point(int n, double value) { double[] ds = new double[n]; Arrays.fill(ds, value); return ds; } private static double[][] boundaries(int dim, double lower, double upper) { double[][] boundaries = new double[2][dim]; for (int i = 0; i < dim; i++) boundaries[0][i] = lower; for (int i = 0; i < dim; i++) boundaries[1][i] = upper; return boundaries; } private static class Sphere implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class Cigar implements MultivariateFunction { private double factor; Cigar() { this(1e3); } Cigar(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += factor * x[i] * x[i]; return f; } } private static class Tablet implements MultivariateFunction { private double factor; Tablet() { this(1e3); } Tablet(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = factor * x[0] * x[0]; for (int i = 1; i < x.length; ++i) f += x[i] * x[i]; return f; } } private static class CigTab implements MultivariateFunction { private double factor; CigTab() { this(1e4); } CigTab(double axisratio) { factor = axisratio; } public double value(double[] x) { int end = x.length - 1; double f = x[0] * x[0] / factor + factor * x[end] * x[end]; for (int i = 1; i < end; ++i) f += x[i] * x[i]; return f; } } private static class TwoAxes implements MultivariateFunction { private double factor; TwoAxes() { this(1e6); } TwoAxes(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += (i < x.length / 2 ? factor : 1) * x[i] * x[i]; return f; } } private static class ElliRotated implements MultivariateFunction { private Basis B = new Basis(); private double factor; ElliRotated() { this(1e3); } ElliRotated(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; x = B.Rotate(x); for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class Elli implements MultivariateFunction { private double factor; Elli() { this(1e3); } Elli(double axisratio) { factor = axisratio * axisratio; } public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(factor, i / (x.length - 1.)) * x[i] * x[i]; return f; } } private static class MinusElli implements MultivariateFunction { private final Elli elli = new Elli(); public double value(double[] x) { return 1.0 - elli.value(x); } } private static class DiffPow implements MultivariateFunction { // private int fcount = 0; public double value(double[] x) { double f = 0; for (int i = 0; i < x.length; ++i) f += Math.pow(Math.abs(x[i]), 2. + 10 * (double) i / (x.length - 1.)); // System.out.print("" + (fcount++) + ") "); // for (int i = 0; i < x.length; i++) // System.out.print(x[i] + " "); // System.out.println(" = " + f); return f; } } private static class SsDiffPow implements MultivariateFunction { public double value(double[] x) { double f = Math.pow(new DiffPow().value(x), 0.25); return f; } } private static class Rosen implements MultivariateFunction { public double value(double[] x) { double f = 0; for (int i = 0; i < x.length - 1; ++i) f += 1e2 * (x[i] * x[i] - x[i + 1]) * (x[i] * x[i] - x[i + 1]) + (x[i] - 1.) * (x[i] - 1.); return f; } } private static class Ackley implements MultivariateFunction { private double axisratio; Ackley(double axra) { axisratio = axra; } public Ackley() { this(1); } public double value(double[] x) { double f = 0; double res2 = 0; double fac = 0; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); f += fac * fac * x[i] * x[i]; res2 += Math.cos(2. * Math.PI * fac * x[i]); } f = (20. - 20. * Math.exp(-0.2 * Math.sqrt(f / x.length)) + Math.exp(1.) - Math.exp(res2 / x.length)); return f; } } private static class Rastrigin implements MultivariateFunction { private double axisratio; private double amplitude; Rastrigin() { this(1, 10); } Rastrigin(double axisratio, double amplitude) { this.axisratio = axisratio; this.amplitude = amplitude; } public double value(double[] x) { double f = 0; double fac; for (int i = 0; i < x.length; ++i) { fac = Math.pow(axisratio, (i - 1.) / (x.length - 1.)); if (i == 0 && x[i] < 0) fac *= 1.; f += fac * fac * x[i] * x[i] + amplitude * (1. - Math.cos(2. * Math.PI * fac * x[i])); } return f; } } private static class Basis { double[][] basis; Random rand = new Random(2); // use not always the same basis double[] Rotate(double[] x) { GenBasis(x.length); double[] y = new double[x.length]; for (int i = 0; i < x.length; ++i) { y[i] = 0; for (int j = 0; j < x.length; ++j) y[i] += basis[i][j] * x[j]; } return y; } void GenBasis(int DIM) { if (basis != null ? basis.length == DIM : false) return; double sp; int i, j, k; /* generate orthogonal basis */ basis = new double[DIM][DIM]; for (i = 0; i < DIM; ++i) { /* sample components gaussian */ for (j = 0; j < DIM; ++j) basis[i][j] = rand.nextGaussian(); /* substract projection of previous vectors */ for (j = i - 1; j >= 0; --j) { for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[j][k]; /* scalar product */ for (k = 0; k < DIM; ++k) basis[i][k] -= sp * basis[j][k]; /* substract */ } /* normalize */ for (sp = 0., k = 0; k < DIM; ++k) sp += basis[i][k] * basis[i][k]; /* squared norm */ for (k = 0; k < DIM; ++k) basis[i][k] /= Math.sqrt(sp); } } } }
public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); }
org.apache.commons.compress.archivers.CpioTestCase::testCpioUnarchive
src/test/java/org/apache/commons/compress/archivers/CpioTestCase.java
101
src/test/java/org/apache/commons/compress/archivers/CpioTestCase.java
testCpioUnarchive
/* * 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.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.compress.AbstractTestCase; import org.apache.commons.compress.archivers.cpio.CpioArchiveEntry; import org.apache.commons.compress.utils.IOUtils; public final class CpioTestCase extends AbstractTestCase { public void testCpioArchiveCreation() throws Exception { final File output = new File(dir, "bla.cpio"); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); } public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); } }
// You are a professional Java test case writer, please create a test case named `testCpioUnarchive` for the issue `Compress-COMPRESS-28`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-28 // // ## Issue-Title: // CPIO reports unexpected EOF // // ## Issue-Description: // // When unpacking an CPIO archive (made with the compress classes or even made with OSX cpio comandline tool) an EOF exception is thrown. // // Here is the testcode: // // // final File input = getFile("cmdcreated.cpio"); // // // final InputStream in = new FileInputStream(input); // // CpioArchiveInputStream cin = new CpioArchiveInputStream(in); // // // CpioArchiveEntry entry = null; // // // while ((entry = (CpioArchiveEntry) cin.getNextCPIOEntry()) != null) // // // { // File target = new File(dir, entry.getName()); // final OutputStream out = new FileOutputStream(target); // IOUtils.copy(in, out); // out.close(); // } // // cin.close(); // // // Stacktrace is here: // // // java.io.EOFException // // at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream.readFully(CpioArchiveInputStream.java:293) // // at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream.getNextCPIOEntry(CpioArchiveInputStream.java:168) // // at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStreamTest.testCpioUnpack(CpioArchiveInputStreamTest.java:26) // // ... // // // This happens with the first read access to the archive. It occured while my try to improve the testcases. // // // // // public void testCpioUnarchive() throws Exception {
101
1
53
src/test/java/org/apache/commons/compress/archivers/CpioTestCase.java
src/test/java
```markdown ## Issue-ID: Compress-COMPRESS-28 ## Issue-Title: CPIO reports unexpected EOF ## Issue-Description: When unpacking an CPIO archive (made with the compress classes or even made with OSX cpio comandline tool) an EOF exception is thrown. Here is the testcode: final File input = getFile("cmdcreated.cpio"); final InputStream in = new FileInputStream(input); CpioArchiveInputStream cin = new CpioArchiveInputStream(in); CpioArchiveEntry entry = null; while ((entry = (CpioArchiveEntry) cin.getNextCPIOEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); } cin.close(); Stacktrace is here: java.io.EOFException at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream.readFully(CpioArchiveInputStream.java:293) at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream.getNextCPIOEntry(CpioArchiveInputStream.java:168) at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStreamTest.testCpioUnpack(CpioArchiveInputStreamTest.java:26) ... This happens with the first read access to the archive. It occured while my try to improve the testcases. ``` You are a professional Java test case writer, please create a test case named `testCpioUnarchive` for the issue `Compress-COMPRESS-28`, utilizing the provided issue report information and the following function signature. ```java public void testCpioUnarchive() throws Exception { ```
53
[ "org.apache.commons.compress.archivers.cpio.CpioArchiveOutputStream" ]
d426dcc571af2c18ce763609715ac0063cdd0048db0eb84485fa1df76c3ae3ea
public void testCpioUnarchive() throws Exception
// You are a professional Java test case writer, please create a test case named `testCpioUnarchive` for the issue `Compress-COMPRESS-28`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Compress-COMPRESS-28 // // ## Issue-Title: // CPIO reports unexpected EOF // // ## Issue-Description: // // When unpacking an CPIO archive (made with the compress classes or even made with OSX cpio comandline tool) an EOF exception is thrown. // // Here is the testcode: // // // final File input = getFile("cmdcreated.cpio"); // // // final InputStream in = new FileInputStream(input); // // CpioArchiveInputStream cin = new CpioArchiveInputStream(in); // // // CpioArchiveEntry entry = null; // // // while ((entry = (CpioArchiveEntry) cin.getNextCPIOEntry()) != null) // // // { // File target = new File(dir, entry.getName()); // final OutputStream out = new FileOutputStream(target); // IOUtils.copy(in, out); // out.close(); // } // // cin.close(); // // // Stacktrace is here: // // // java.io.EOFException // // at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream.readFully(CpioArchiveInputStream.java:293) // // at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream.getNextCPIOEntry(CpioArchiveInputStream.java:168) // // at org.apache.commons.compress.archivers.cpio.CpioArchiveInputStreamTest.testCpioUnpack(CpioArchiveInputStreamTest.java:26) // // ... // // // This happens with the first read access to the archive. It occured while my try to improve the testcases. // // // // //
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.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.compress.AbstractTestCase; import org.apache.commons.compress.archivers.cpio.CpioArchiveEntry; import org.apache.commons.compress.utils.IOUtils; public final class CpioTestCase extends AbstractTestCase { public void testCpioArchiveCreation() throws Exception { final File output = new File(dir, "bla.cpio"); final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); } public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); os.close(); out.close(); } // Unarchive Operation final File input = output; final InputStream is = new FileInputStream(input); final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); Map result = new HashMap(); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File target = new File(dir, entry.getName()); final OutputStream out = new FileOutputStream(target); IOUtils.copy(in, out); out.close(); result.put(entry.getName(), target); } in.close(); int lineSepLength = System.getProperty("line.separator").length(); File t = (File)result.get("test1.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 72 + 4 * lineSepLength, t.length()); t = (File)result.get("test2.xml"); assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); assertEquals("length of " + t.getAbsolutePath(), 73 + 5 * lineSepLength, t.length()); } }
public void test2947660() { AbstractCategoryItemRenderer r = new LineAndShapeRenderer(); assertNotNull(r.getLegendItems()); assertEquals(0, r.getLegendItems().getItemCount()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); CategoryPlot plot = new CategoryPlot(); plot.setDataset(dataset); plot.setRenderer(r); assertEquals(0, r.getLegendItems().getItemCount()); dataset.addValue(1.0, "S1", "C1"); LegendItemCollection lic = r.getLegendItems(); assertEquals(1, lic.getItemCount()); assertEquals("S1", lic.get(0).getLabel()); }
org.jfree.chart.renderer.category.junit.AbstractCategoryItemRendererTests::test2947660
tests/org/jfree/chart/renderer/category/junit/AbstractCategoryItemRendererTests.java
410
tests/org/jfree/chart/renderer/category/junit/AbstractCategoryItemRendererTests.java
test2947660
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2010, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------------------- * AbstractCategoryItemRendererTests.java * -------------------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 12-Feb-2004 : Version 1 (DG); * 24-Nov-2006 : New cloning tests (DG); * 07-Dec-2006 : Added testEquals() method (DG); * 26-Jun-2007 : Added testGetSeriesItemLabelGenerator() and * testGetSeriesURLGenerator() (DG); * 25-Nov-2008 : Added testFindRangeBounds() (DG); * 09-Feb-2010 : Added test2947660() (DG); * */ package org.jfree.chart.renderer.category.junit; import java.text.NumberFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.CategoryTextAnnotation; import org.jfree.chart.labels.IntervalCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardCategorySeriesLabelGenerator; import org.jfree.chart.labels.StandardCategoryToolTipGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.renderer.category.AbstractCategoryItemRenderer; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.chart.urls.StandardCategoryURLGenerator; import org.jfree.chart.util.Layer; import org.jfree.data.Range; import org.jfree.data.category.DefaultCategoryDataset; /** * Tests for the {@link AbstractCategoryItemRenderer} class. */ public class AbstractCategoryItemRendererTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(AbstractCategoryItemRendererTests.class); } /** * Checks that all fields are distinguished. */ public void testEquals() { BarRenderer r1 = new BarRenderer(); BarRenderer r2 = new BarRenderer(); assertEquals(r1, r2); // the plot field is NOT tested // toolTipGeneratorList r1.setSeriesToolTipGenerator(1, new StandardCategoryToolTipGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesToolTipGenerator(1, new StandardCategoryToolTipGenerator()); assertTrue(r1.equals(r2)); // baseToolTipGenerator r1.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("{2}", NumberFormat.getInstance())); assertFalse(r1.equals(r2)); r2.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("{2}", NumberFormat.getInstance())); assertTrue(r1.equals(r2)); // itemLabelGeneratorList r1.setSeriesItemLabelGenerator(1, new StandardCategoryItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesItemLabelGenerator(1, new StandardCategoryItemLabelGenerator()); assertTrue(r1.equals(r2)); // baseItemLabelGenerator r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator( "{2}", NumberFormat.getInstance())); assertFalse(r1.equals(r2)); r2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator( "{2}", NumberFormat.getInstance())); assertTrue(r1.equals(r2)); // urlGeneratorList r1.setSeriesURLGenerator(1, new StandardCategoryURLGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesURLGenerator(1, new StandardCategoryURLGenerator()); assertTrue(r1.equals(r2)); // baseItemURLGenerator r1.setBaseURLGenerator(new StandardCategoryURLGenerator( "abc.html")); assertFalse(r1.equals(r2)); r2.setBaseURLGenerator(new StandardCategoryURLGenerator( "abc.html")); assertTrue(r1.equals(r2)); // legendItemLabelGenerator r1.setLegendItemLabelGenerator(new StandardCategorySeriesLabelGenerator( "XYZ")); assertFalse(r1.equals(r2)); r2.setLegendItemLabelGenerator(new StandardCategorySeriesLabelGenerator( "XYZ")); assertTrue(r1.equals(r2)); // legendItemToolTipGenerator r1.setLegendItemToolTipGenerator( new StandardCategorySeriesLabelGenerator("ToolTip")); assertFalse(r1.equals(r2)); r2.setLegendItemToolTipGenerator( new StandardCategorySeriesLabelGenerator("ToolTip")); assertTrue(r1.equals(r2)); // legendItemURLGenerator r1.setLegendItemURLGenerator( new StandardCategorySeriesLabelGenerator("URL")); assertFalse(r1.equals(r2)); r2.setLegendItemURLGenerator( new StandardCategorySeriesLabelGenerator("URL")); assertTrue(r1.equals(r2)); // background annotation r1.addAnnotation(new CategoryTextAnnotation("ABC", "A", 2.0), Layer.BACKGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new CategoryTextAnnotation("ABC", "A", 2.0), Layer.BACKGROUND); assertTrue(r1.equals(r2)); // foreground annotation r1.addAnnotation(new CategoryTextAnnotation("DEF", "B", 4.0), Layer.FOREGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new CategoryTextAnnotation("DEF", "B", 4.0), Layer.FOREGROUND); assertTrue(r1.equals(r2)); } /** * Confirm that cloning works. */ public void testCloning1() { AbstractCategoryItemRenderer r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); AbstractCategoryItemRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Confirm that cloning works. */ public void testCloning2() { BarRenderer r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new IntervalCategoryItemLabelGenerator()); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setSeriesItemLabelGenerator(0, new IntervalCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new IntervalCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Check that the legendItemLabelGenerator is cloned. */ public void testCloning_LegendItemLabelGenerator() { StandardCategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("Series {0}"); BarRenderer r1 = new BarRenderer(); r1.setLegendItemLabelGenerator(generator); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check that the generator has been cloned assertTrue(r1.getLegendItemLabelGenerator() != r2.getLegendItemLabelGenerator()); } /** * Check that the legendItemToolTipGenerator is cloned. */ public void testCloning_LegendItemToolTipGenerator() { StandardCategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("Series {0}"); BarRenderer r1 = new BarRenderer(); r1.setLegendItemToolTipGenerator(generator); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check that the generator has been cloned assertTrue(r1.getLegendItemToolTipGenerator() != r2.getLegendItemToolTipGenerator()); } /** * Check that the legendItemURLGenerator is cloned. */ public void testCloning_LegendItemURLGenerator() { StandardCategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("Series {0}"); BarRenderer r1 = new BarRenderer(); r1.setLegendItemURLGenerator(generator); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check that the generator has been cloned assertTrue(r1.getLegendItemURLGenerator() != r2.getLegendItemURLGenerator()); } /** * Check that the getSeriesItemLabelGenerator() method behaves as * expected. */ public void testGetSeriesItemLabelGenerator() { CategoryItemRenderer r = new BarRenderer(); assertNull(r.getSeriesItemLabelGenerator(2)); r.setSeriesItemLabelGenerator(2, new StandardCategoryItemLabelGenerator()); assertNotNull(r.getSeriesItemLabelGenerator(2)); r.setSeriesItemLabelGenerator(2, null); assertNull(r.getSeriesItemLabelGenerator(2)); r.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); assertNull(r.getSeriesItemLabelGenerator(2)); } /** * Check that the getSeriesURLGenerator() method behaves as expected. */ public void testGetSeriesURLGenerator() { CategoryItemRenderer r = new BarRenderer(); assertNull(r.getSeriesURLGenerator(2)); r.setSeriesURLGenerator(2, new StandardCategoryURLGenerator()); assertNotNull(r.getSeriesURLGenerator(2)); r.setSeriesURLGenerator(2, null); assertNull(r.getSeriesURLGenerator(2)); r.setBaseURLGenerator(new StandardCategoryURLGenerator()); assertNull(r.getSeriesURLGenerator(2)); } /** * Some checks for the findRangeBounds() method. */ public void testFindRangeBounds() { AbstractCategoryItemRenderer r = new LineAndShapeRenderer(); assertNull(r.findRangeBounds(null)); // an empty dataset should return a null range DefaultCategoryDataset dataset = new DefaultCategoryDataset(); assertNull(r.findRangeBounds(dataset)); dataset.addValue(1.0, "R1", "C1"); assertEquals(new Range(1.0, 1.0), r.findRangeBounds(dataset)); dataset.addValue(-2.0, "R1", "C2"); assertEquals(new Range(-2.0, 1.0), r.findRangeBounds(dataset)); dataset.addValue(null, "R1", "C3"); assertEquals(new Range(-2.0, 1.0), r.findRangeBounds(dataset)); } /** * A test that reproduces the problem reported in bug 2947660. */ public void test2947660() { AbstractCategoryItemRenderer r = new LineAndShapeRenderer(); assertNotNull(r.getLegendItems()); assertEquals(0, r.getLegendItems().getItemCount()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); CategoryPlot plot = new CategoryPlot(); plot.setDataset(dataset); plot.setRenderer(r); assertEquals(0, r.getLegendItems().getItemCount()); dataset.addValue(1.0, "S1", "C1"); LegendItemCollection lic = r.getLegendItems(); assertEquals(1, lic.getItemCount()); assertEquals("S1", lic.get(0).getLabel()); } }
// You are a professional Java test case writer, please create a test case named `test2947660` for the issue `Chart-983`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-983 // // ## Issue-Title: // #983 Potential NPE in AbstractCategoryItemRender.getLegendItems() // // // // // // ## Issue-Description: // Setting up a working copy of the current JFreeChart trunk in Eclipse I got a warning about a null pointer access in this bit of code from AbstractCategoryItemRender.java: // // // public LegendItemCollection getLegendItems() { // // LegendItemCollection result = new LegendItemCollection(); // // if (this.plot == null) { // // return result; // // } // // int index = this.plot.getIndexOf(this); // // CategoryDataset dataset = this.plot.getDataset(index); // // if (dataset != null) { // // return result; // // } // // int seriesCount = dataset.getRowCount(); // // ... // // } // // // The warning is in the last code line where seriesCount is assigned. The variable dataset is guaranteed to be null in this location, I suppose that the check before that should actually read "if (dataset == null)", not "if (dataset != null)". // // // This is trunk as of 2010-02-08. // // // // public void test2947660() {
410
/** * A test that reproduces the problem reported in bug 2947660. */
1
395
tests/org/jfree/chart/renderer/category/junit/AbstractCategoryItemRendererTests.java
tests
```markdown ## Issue-ID: Chart-983 ## Issue-Title: #983 Potential NPE in AbstractCategoryItemRender.getLegendItems() ## Issue-Description: Setting up a working copy of the current JFreeChart trunk in Eclipse I got a warning about a null pointer access in this bit of code from AbstractCategoryItemRender.java: public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); if (this.plot == null) { return result; } int index = this.plot.getIndexOf(this); CategoryDataset dataset = this.plot.getDataset(index); if (dataset != null) { return result; } int seriesCount = dataset.getRowCount(); ... } The warning is in the last code line where seriesCount is assigned. The variable dataset is guaranteed to be null in this location, I suppose that the check before that should actually read "if (dataset == null)", not "if (dataset != null)". This is trunk as of 2010-02-08. ``` You are a professional Java test case writer, please create a test case named `test2947660` for the issue `Chart-983`, utilizing the provided issue report information and the following function signature. ```java public void test2947660() { ```
395
[ "org.jfree.chart.renderer.category.AbstractCategoryItemRenderer" ]
d5abc2cf62514de735b952a6ca1e1a5fb6ec4809537f4769ef61928f66bbace6
public void test2947660()
// You are a professional Java test case writer, please create a test case named `test2947660` for the issue `Chart-983`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-983 // // ## Issue-Title: // #983 Potential NPE in AbstractCategoryItemRender.getLegendItems() // // // // // // ## Issue-Description: // Setting up a working copy of the current JFreeChart trunk in Eclipse I got a warning about a null pointer access in this bit of code from AbstractCategoryItemRender.java: // // // public LegendItemCollection getLegendItems() { // // LegendItemCollection result = new LegendItemCollection(); // // if (this.plot == null) { // // return result; // // } // // int index = this.plot.getIndexOf(this); // // CategoryDataset dataset = this.plot.getDataset(index); // // if (dataset != null) { // // return result; // // } // // int seriesCount = dataset.getRowCount(); // // ... // // } // // // The warning is in the last code line where seriesCount is assigned. The variable dataset is guaranteed to be null in this location, I suppose that the check before that should actually read "if (dataset == null)", not "if (dataset != null)". // // // This is trunk as of 2010-02-08. // // // //
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2010, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------------------- * AbstractCategoryItemRendererTests.java * -------------------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 12-Feb-2004 : Version 1 (DG); * 24-Nov-2006 : New cloning tests (DG); * 07-Dec-2006 : Added testEquals() method (DG); * 26-Jun-2007 : Added testGetSeriesItemLabelGenerator() and * testGetSeriesURLGenerator() (DG); * 25-Nov-2008 : Added testFindRangeBounds() (DG); * 09-Feb-2010 : Added test2947660() (DG); * */ package org.jfree.chart.renderer.category.junit; import java.text.NumberFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.CategoryTextAnnotation; import org.jfree.chart.labels.IntervalCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardCategorySeriesLabelGenerator; import org.jfree.chart.labels.StandardCategoryToolTipGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.renderer.category.AbstractCategoryItemRenderer; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.chart.urls.StandardCategoryURLGenerator; import org.jfree.chart.util.Layer; import org.jfree.data.Range; import org.jfree.data.category.DefaultCategoryDataset; /** * Tests for the {@link AbstractCategoryItemRenderer} class. */ public class AbstractCategoryItemRendererTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(AbstractCategoryItemRendererTests.class); } /** * Checks that all fields are distinguished. */ public void testEquals() { BarRenderer r1 = new BarRenderer(); BarRenderer r2 = new BarRenderer(); assertEquals(r1, r2); // the plot field is NOT tested // toolTipGeneratorList r1.setSeriesToolTipGenerator(1, new StandardCategoryToolTipGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesToolTipGenerator(1, new StandardCategoryToolTipGenerator()); assertTrue(r1.equals(r2)); // baseToolTipGenerator r1.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("{2}", NumberFormat.getInstance())); assertFalse(r1.equals(r2)); r2.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("{2}", NumberFormat.getInstance())); assertTrue(r1.equals(r2)); // itemLabelGeneratorList r1.setSeriesItemLabelGenerator(1, new StandardCategoryItemLabelGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesItemLabelGenerator(1, new StandardCategoryItemLabelGenerator()); assertTrue(r1.equals(r2)); // baseItemLabelGenerator r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator( "{2}", NumberFormat.getInstance())); assertFalse(r1.equals(r2)); r2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator( "{2}", NumberFormat.getInstance())); assertTrue(r1.equals(r2)); // urlGeneratorList r1.setSeriesURLGenerator(1, new StandardCategoryURLGenerator()); assertFalse(r1.equals(r2)); r2.setSeriesURLGenerator(1, new StandardCategoryURLGenerator()); assertTrue(r1.equals(r2)); // baseItemURLGenerator r1.setBaseURLGenerator(new StandardCategoryURLGenerator( "abc.html")); assertFalse(r1.equals(r2)); r2.setBaseURLGenerator(new StandardCategoryURLGenerator( "abc.html")); assertTrue(r1.equals(r2)); // legendItemLabelGenerator r1.setLegendItemLabelGenerator(new StandardCategorySeriesLabelGenerator( "XYZ")); assertFalse(r1.equals(r2)); r2.setLegendItemLabelGenerator(new StandardCategorySeriesLabelGenerator( "XYZ")); assertTrue(r1.equals(r2)); // legendItemToolTipGenerator r1.setLegendItemToolTipGenerator( new StandardCategorySeriesLabelGenerator("ToolTip")); assertFalse(r1.equals(r2)); r2.setLegendItemToolTipGenerator( new StandardCategorySeriesLabelGenerator("ToolTip")); assertTrue(r1.equals(r2)); // legendItemURLGenerator r1.setLegendItemURLGenerator( new StandardCategorySeriesLabelGenerator("URL")); assertFalse(r1.equals(r2)); r2.setLegendItemURLGenerator( new StandardCategorySeriesLabelGenerator("URL")); assertTrue(r1.equals(r2)); // background annotation r1.addAnnotation(new CategoryTextAnnotation("ABC", "A", 2.0), Layer.BACKGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new CategoryTextAnnotation("ABC", "A", 2.0), Layer.BACKGROUND); assertTrue(r1.equals(r2)); // foreground annotation r1.addAnnotation(new CategoryTextAnnotation("DEF", "B", 4.0), Layer.FOREGROUND); assertFalse(r1.equals(r2)); r2.addAnnotation(new CategoryTextAnnotation("DEF", "B", 4.0), Layer.FOREGROUND); assertTrue(r1.equals(r2)); } /** * Confirm that cloning works. */ public void testCloning1() { AbstractCategoryItemRenderer r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); AbstractCategoryItemRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Confirm that cloning works. */ public void testCloning2() { BarRenderer r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new IntervalCategoryItemLabelGenerator()); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setSeriesItemLabelGenerator(0, new IntervalCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); r1 = new BarRenderer(); r1.setBaseItemLabelGenerator(new IntervalCategoryItemLabelGenerator()); r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Check that the legendItemLabelGenerator is cloned. */ public void testCloning_LegendItemLabelGenerator() { StandardCategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("Series {0}"); BarRenderer r1 = new BarRenderer(); r1.setLegendItemLabelGenerator(generator); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check that the generator has been cloned assertTrue(r1.getLegendItemLabelGenerator() != r2.getLegendItemLabelGenerator()); } /** * Check that the legendItemToolTipGenerator is cloned. */ public void testCloning_LegendItemToolTipGenerator() { StandardCategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("Series {0}"); BarRenderer r1 = new BarRenderer(); r1.setLegendItemToolTipGenerator(generator); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check that the generator has been cloned assertTrue(r1.getLegendItemToolTipGenerator() != r2.getLegendItemToolTipGenerator()); } /** * Check that the legendItemURLGenerator is cloned. */ public void testCloning_LegendItemURLGenerator() { StandardCategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("Series {0}"); BarRenderer r1 = new BarRenderer(); r1.setLegendItemURLGenerator(generator); BarRenderer r2 = null; try { r2 = (BarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check that the generator has been cloned assertTrue(r1.getLegendItemURLGenerator() != r2.getLegendItemURLGenerator()); } /** * Check that the getSeriesItemLabelGenerator() method behaves as * expected. */ public void testGetSeriesItemLabelGenerator() { CategoryItemRenderer r = new BarRenderer(); assertNull(r.getSeriesItemLabelGenerator(2)); r.setSeriesItemLabelGenerator(2, new StandardCategoryItemLabelGenerator()); assertNotNull(r.getSeriesItemLabelGenerator(2)); r.setSeriesItemLabelGenerator(2, null); assertNull(r.getSeriesItemLabelGenerator(2)); r.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); assertNull(r.getSeriesItemLabelGenerator(2)); } /** * Check that the getSeriesURLGenerator() method behaves as expected. */ public void testGetSeriesURLGenerator() { CategoryItemRenderer r = new BarRenderer(); assertNull(r.getSeriesURLGenerator(2)); r.setSeriesURLGenerator(2, new StandardCategoryURLGenerator()); assertNotNull(r.getSeriesURLGenerator(2)); r.setSeriesURLGenerator(2, null); assertNull(r.getSeriesURLGenerator(2)); r.setBaseURLGenerator(new StandardCategoryURLGenerator()); assertNull(r.getSeriesURLGenerator(2)); } /** * Some checks for the findRangeBounds() method. */ public void testFindRangeBounds() { AbstractCategoryItemRenderer r = new LineAndShapeRenderer(); assertNull(r.findRangeBounds(null)); // an empty dataset should return a null range DefaultCategoryDataset dataset = new DefaultCategoryDataset(); assertNull(r.findRangeBounds(dataset)); dataset.addValue(1.0, "R1", "C1"); assertEquals(new Range(1.0, 1.0), r.findRangeBounds(dataset)); dataset.addValue(-2.0, "R1", "C2"); assertEquals(new Range(-2.0, 1.0), r.findRangeBounds(dataset)); dataset.addValue(null, "R1", "C3"); assertEquals(new Range(-2.0, 1.0), r.findRangeBounds(dataset)); } /** * A test that reproduces the problem reported in bug 2947660. */ public void test2947660() { AbstractCategoryItemRenderer r = new LineAndShapeRenderer(); assertNotNull(r.getLegendItems()); assertEquals(0, r.getLegendItems().getItemCount()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); CategoryPlot plot = new CategoryPlot(); plot.setDataset(dataset); plot.setRenderer(r); assertEquals(0, r.getLegendItems().getItemCount()); dataset.addValue(1.0, "S1", "C1"); LegendItemCollection lic = r.getLegendItems(); assertEquals(1, lic.getItemCount()); assertEquals("S1", lic.get(0).getLabel()); } }
public void testIssue620() { assertPrint("alert(/ / / / /);", "alert(/ // / /)"); assertPrint("alert(/ // / /);", "alert(/ // / /)"); }
com.google.javascript.jscomp.CodePrinterTest::testIssue620
test/com/google/javascript/jscomp/CodePrinterTest.java
1,284
test/com/google/javascript/jscomp/CodePrinterTest.java
testIssue620
/* * 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.InputId; 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); 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, 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 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" ); } 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}"); } }
// You are a professional Java test case writer, please create a test case named `testIssue620` for the issue `Closure-620`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-620 // // ## Issue-Title: // alert(/ / / / /) // // ## Issue-Description: // alert(/ / / / /); // output: alert(/ /// /); // should be: alert(/ // / /); // // public void testIssue620() {
1,284
44
1,281
test/com/google/javascript/jscomp/CodePrinterTest.java
test
```markdown ## Issue-ID: Closure-620 ## Issue-Title: alert(/ / / / /) ## Issue-Description: alert(/ / / / /); output: alert(/ /// /); should be: alert(/ // / /); ``` You are a professional Java test case writer, please create a test case named `testIssue620` for the issue `Closure-620`, utilizing the provided issue report information and the following function signature. ```java public void testIssue620() { ```
1,281
[ "com.google.javascript.jscomp.CodeConsumer" ]
d655699ec63ec9e6862fb7e122b6a5967236c80481a41b97538c76df7d43a8ad
public void testIssue620()
// You are a professional Java test case writer, please create a test case named `testIssue620` for the issue `Closure-620`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-620 // // ## Issue-Title: // alert(/ / / / /) // // ## Issue-Description: // alert(/ / / / /); // output: alert(/ /// /); // should be: alert(/ // / /); // //
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.InputId; 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); 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, 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 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" ); } 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}"); } }
@Test public void testShiftJisRoundtrip() throws Exception { String input = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=Shift_JIS\" />" + "</head>" + "<body>" + "before&nbsp;after" + "</body>" + "</html>"; InputStream is = new ByteArrayInputStream(input.getBytes(Charset.forName("ASCII"))); Document doc = Jsoup.parse(is, null, "http://example.com"); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); String output = new String(doc.html().getBytes(doc.outputSettings().charset()), doc.outputSettings().charset()); assertFalse("Should not have contained a '?'.", output.contains("?")); assertTrue("Should have contained a '&#xa0;' or a '&nbsp;'.", output.contains("&#xa0;") || output.contains("&nbsp;")); }
org.jsoup.nodes.DocumentTest::testShiftJisRoundtrip
src/test/java/org/jsoup/nodes/DocumentTest.java
408
src/test/java/org/jsoup/nodes/DocumentTest.java
testShiftJisRoundtrip
package org.jsoup.nodes; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.Document.OutputSettings.Syntax; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; /** Tests for Document. @author Jonathan Hedley, [email protected] */ public class DocumentTest { private static final String charsetUtf8 = "UTF-8"; private static final String charsetIso8859 = "ISO-8859-1"; @Test public void setTextPreservesDocumentStructure() { Document doc = Jsoup.parse("<p>Hello</p>"); doc.text("Replaced"); assertEquals("Replaced", doc.text()); assertEquals("Replaced", doc.body().text()); assertEquals(1, doc.select("head").size()); } @Test public void testTitles() { Document noTitle = Jsoup.parse("<p>Hello</p>"); Document withTitle = Jsoup.parse("<title>First</title><title>Ignore</title><p>Hello</p>"); assertEquals("", noTitle.title()); noTitle.title("Hello"); assertEquals("Hello", noTitle.title()); assertEquals("Hello", noTitle.select("title").first().text()); assertEquals("First", withTitle.title()); withTitle.title("Hello"); assertEquals("Hello", withTitle.title()); assertEquals("Hello", withTitle.select("title").first().text()); Document normaliseTitle = Jsoup.parse("<title> Hello\nthere \n now \n"); assertEquals("Hello there now", normaliseTitle.title()); } @Test public void testOutputEncoding() { Document doc = Jsoup.parse("<p title=π>π & < > </p>"); // default is utf-8 assertEquals("<p title=\"π\">π &amp; &lt; &gt; </p>", doc.body().html()); assertEquals("UTF-8", doc.outputSettings().charset().name()); doc.outputSettings().charset("ascii"); assertEquals(Entities.EscapeMode.base, doc.outputSettings().escapeMode()); assertEquals("<p title=\"&#x3c0;\">&#x3c0; &amp; &lt; &gt; </p>", doc.body().html()); doc.outputSettings().escapeMode(Entities.EscapeMode.extended); assertEquals("<p title=\"&pi;\">&pi; &amp; &lt; &gt; </p>", doc.body().html()); } @Test public void testXhtmlReferences() { Document doc = Jsoup.parse("&lt; &gt; &amp; &quot; &apos; &times;"); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); assertEquals("&lt; &gt; &amp; \" ' ×", doc.body().html()); } @Test public void testNormalisesStructure() { Document doc = Jsoup.parse("<html><head><script>one</script><noscript><p>two</p></noscript></head><body><p>three</p></body><p>four</p></html>"); assertEquals("<html><head><script>one</script><noscript>&lt;p&gt;two</noscript></head><body><p>three</p><p>four</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testClone() { Document doc = Jsoup.parse("<title>Hello</title> <p>One<p>Two"); Document clone = doc.clone(); assertEquals("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>", TextUtil.stripNewlines(clone.html())); clone.title("Hello there"); clone.select("p").first().text("One more").attr("id", "1"); assertEquals("<html><head><title>Hello there</title> </head><body><p id=\"1\">One more</p><p>Two</p></body></html>", TextUtil.stripNewlines(clone.html())); assertEquals("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testClonesDeclarations() { Document doc = Jsoup.parse("<!DOCTYPE html><html><head><title>Doctype test"); Document clone = doc.clone(); assertEquals(doc.html(), clone.html()); assertEquals("<!doctype html><html><head><title>Doctype test</title></head><body></body></html>", TextUtil.stripNewlines(clone.html())); } @Test public void testLocation() throws IOException { File in = new ParseTest().getFile("/htmltests/yahoo-jp.html"); Document doc = Jsoup.parse(in, "UTF-8", "http://www.yahoo.co.jp/index.html"); String location = doc.location(); String baseUri = doc.baseUri(); assertEquals("http://www.yahoo.co.jp/index.html",location); assertEquals("http://www.yahoo.co.jp/_ylh=X3oDMTB0NWxnaGxsBF9TAzIwNzcyOTYyNjUEdGlkAzEyBHRtcGwDZ2Ex/",baseUri); in = new ParseTest().getFile("/htmltests/nyt-article-1.html"); doc = Jsoup.parse(in, null, "http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp"); location = doc.location(); baseUri = doc.baseUri(); assertEquals("http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp",location); assertEquals("http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp",baseUri); } @Test public void testHtmlAndXmlSyntax() { String h = "<!DOCTYPE html><body><img async checked='checked' src='&<>\"'>&lt;&gt;&amp;&quot;<foo />bar"; Document doc = Jsoup.parse(h); doc.outputSettings().syntax(Syntax.html); assertEquals("<!doctype html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async checked src=\"&amp;<>&quot;\">&lt;&gt;&amp;\"\n" + " <foo />bar\n" + " </body>\n" + "</html>", doc.html()); doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml); assertEquals("<!DOCTYPE html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async=\"\" checked=\"checked\" src=\"&amp;<>&quot;\" />&lt;&gt;&amp;\"\n" + " <foo />bar\n" + " </body>\n" + "</html>", doc.html()); } @Test public void htmlParseDefaultsToHtmlOutputSyntax() { Document doc = Jsoup.parse("x"); assertEquals(Syntax.html, doc.outputSettings().syntax()); } // Ignored since this test can take awhile to run. @Ignore @Test public void testOverflowClone() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < 100000; i++) { builder.insert(0, "<i>"); builder.append("</i>"); } Document doc = Jsoup.parse(builder.toString()); doc.clone(); } @Test public void DocumentsWithSameContentAreEqual() throws Exception { Document docA = Jsoup.parse("<div/>One"); Document docB = Jsoup.parse("<div/>One"); Document docC = Jsoup.parse("<div/>Two"); assertEquals(docA, docB); assertFalse(docA.equals(docC)); assertEquals(docA.hashCode(), docB.hashCode()); assertFalse(docA.hashCode() == docC.hashCode()); } @Test public void testMetaCharsetUpdateUtf8() { final Document doc = createHtmlDocument("changeThis"); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetUTF8, doc.toString()); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetUtf8, doc.charset().name()); assertEquals(charsetUtf8, selectedElement.attr("charset")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateIso8859() { final Document doc = createHtmlDocument("changeThis"); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetIso8859)); final String htmlCharsetISO = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetIso8859 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetISO, doc.toString()); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetIso8859, doc.charset().name()); assertEquals(charsetIso8859, selectedElement.attr("charset")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateNoCharset() { final Document docNoCharset = Document.createShell(""); docNoCharset.updateMetaCharsetElement(true); docNoCharset.charset(Charset.forName(charsetUtf8)); assertEquals(charsetUtf8, docNoCharset.select("meta[charset]").first().attr("charset")); final String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetUTF8, docNoCharset.toString()); } @Test public void testMetaCharsetUpdateDisabled() { final Document docDisabled = Document.createShell(""); final String htmlNoCharset = "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlNoCharset, docDisabled.toString()); assertNull(docDisabled.select("meta[charset]").first()); } @Test public void testMetaCharsetUpdateDisabledNoChanges() { final Document doc = createHtmlDocument("dontTouch"); final String htmlCharset = "<html>\n" + " <head>\n" + " <meta charset=\"dontTouch\">\n" + " <meta name=\"charset\" content=\"dontTouch\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharset, doc.toString()); Element selectedElement = doc.select("meta[charset]").first(); assertNotNull(selectedElement); assertEquals("dontTouch", selectedElement.attr("charset")); selectedElement = doc.select("meta[name=charset]").first(); assertNotNull(selectedElement); assertEquals("dontTouch", selectedElement.attr("content")); } @Test public void testMetaCharsetUpdateEnabledAfterCharsetChange() { final Document doc = createHtmlDocument("dontTouch"); doc.charset(Charset.forName(charsetUtf8)); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetUtf8, selectedElement.attr("charset")); assertTrue(doc.select("meta[name=charset]").isEmpty()); } @Test public void testMetaCharsetUpdateCleanup() { final Document doc = createHtmlDocument("dontTouch"); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetUTF8, doc.toString()); } @Test public void testMetaCharsetUpdateXmlUtf8() { final Document doc = createXmlDocument("1.0", "changeThis", true); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String xmlCharsetUTF8 = "<?xml version=\"1.0\" encoding=\"" + charsetUtf8 + "\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharsetUTF8, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals(charsetUtf8, doc.charset().name()); assertEquals(charsetUtf8, selectedNode.attr("encoding")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateXmlIso8859() { final Document doc = createXmlDocument("1.0", "changeThis", true); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetIso8859)); final String xmlCharsetISO = "<?xml version=\"1.0\" encoding=\"" + charsetIso8859 + "\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharsetISO, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals(charsetIso8859, doc.charset().name()); assertEquals(charsetIso8859, selectedNode.attr("encoding")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateXmlNoCharset() { final Document doc = createXmlDocument("1.0", "none", false); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String xmlCharsetUTF8 = "<?xml version=\"1.0\" encoding=\"" + charsetUtf8 + "\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharsetUTF8, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals(charsetUtf8, selectedNode.attr("encoding")); } @Test public void testMetaCharsetUpdateXmlDisabled() { final Document doc = createXmlDocument("none", "none", false); final String xmlNoCharset = "<root>\n" + " node\n" + "</root>"; assertEquals(xmlNoCharset, doc.toString()); } @Test public void testMetaCharsetUpdateXmlDisabledNoChanges() { final Document doc = createXmlDocument("dontTouch", "dontTouch", true); final String xmlCharset = "<?xml version=\"dontTouch\" encoding=\"dontTouch\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharset, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals("dontTouch", selectedNode.attr("encoding")); assertEquals("dontTouch", selectedNode.attr("version")); } @Test public void testMetaCharsetUpdatedDisabledPerDefault() { final Document doc = createHtmlDocument("none"); assertFalse(doc.updateMetaCharsetElement()); } private Document createHtmlDocument(String charset) { final Document doc = Document.createShell(""); doc.head().appendElement("meta").attr("charset", charset); doc.head().appendElement("meta").attr("name", "charset").attr("content", charset); return doc; } private Document createXmlDocument(String version, String charset, boolean addDecl) { final Document doc = new Document(""); doc.appendElement("root").text("node"); doc.outputSettings().syntax(Syntax.xml); if( addDecl == true ) { XmlDeclaration decl = new XmlDeclaration("xml", "", false); decl.attr("version", version); decl.attr("encoding", charset); doc.prependChild(decl); } return doc; } @Test public void testShiftJisRoundtrip() throws Exception { String input = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=Shift_JIS\" />" + "</head>" + "<body>" + "before&nbsp;after" + "</body>" + "</html>"; InputStream is = new ByteArrayInputStream(input.getBytes(Charset.forName("ASCII"))); Document doc = Jsoup.parse(is, null, "http://example.com"); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); String output = new String(doc.html().getBytes(doc.outputSettings().charset()), doc.outputSettings().charset()); assertFalse("Should not have contained a '?'.", output.contains("?")); assertTrue("Should have contained a '&#xa0;' or a '&nbsp;'.", output.contains("&#xa0;") || output.contains("&nbsp;")); } }
// You are a professional Java test case writer, please create a test case named `testShiftJisRoundtrip` for the issue `Jsoup-523`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-523 // // ## Issue-Title: // EscapeMode.xhtml no longer falls back to numeric escapes - Can cause '?' replacement in output // // ## Issue-Description: // I've been using EscapeMode.xhtml with JSoup to avoid encoding things which don't (from my perspective) need to be encoded, like egrave in a UTF-8 document for example. // // // While upgrading from JSoup 1.7.2 to 1.8.1 however, I've noticed a problem with a shift-jis related test I have. Here's a simplified/reduced version. // // // // ``` // package test; // // import java.io.ByteArrayInputStream; // import java.io.InputStream; // import java.nio.charset.Charset; // // import org.jsoup.Jsoup; // import org.jsoup.nodes.Document; // import org.jsoup.nodes.Entities.EscapeMode; // import org.junit.Assert; // import org.junit.Test; // // public class ShiftJisTest { // // @Test // public void testShiftJisRoundtrip() throws Exception { // String input = // "<html>" // + "<head>" // + "<meta http-equiv=\"content-type\" content=\"text/html; charset=Shift_JIS\" />" // + "</head>" // + "<body>" // + "before&nbsp;after" // + "</body>" // + "</html>"; // InputStream is = new ByteArrayInputStream(input.getBytes(Charset.forName("ASCII"))); // // Document doc = Jsoup.parse(is, null, "http://example.com"); // doc.outputSettings().escapeMode(EscapeMode.xhtml); // // String output = new String(doc.html().getBytes(doc.outputSettings().charset()), doc.outputSettings().charset()); // // System.out.println(output); // // Assert.assertFalse("Should not have contained a '?'.", output.contains("?")); // Assert.assertTrue("Should have contained a '&#xa0;' or a '&nbsp;'.", // output.contains("&#xa0;") || output.contains("&nbsp;")); // } // // } // // ``` // // Under JSoup 1.7.2, the body of the output in this test is "before after" (which looks as expected when rendered in Firefox), where as under 1.8.1 it is "before?after". // // // I assume the issue here is that I've asked JSoup to escape only XHTML characters (i.e. not nbsp), and it's producing a charset where (I assume) there's no character to represent 'non-breaking space'. // // // The upshot of this is that, as a result of upgrading JSoup, I end up with '?' replaced in for what used to be shown as a non breaking space. // // // It seems like the old behaviour was to fall back to providing an escaped numeric character (odd if there's no valid character for that in Shift\_JIS, but it still rendered correctly). From my perspective, the old behaviour was better - Is there any way it can be reinstated (or an escape mode provided for it)? // // // Obviously using EscapeMode.base instead of EscapeMode.xhtml is a possible workaround, however I would really prefer not to have characters unnecessarily escaped if possible. // // // // @Test public void testShiftJisRoundtrip() throws Exception {
408
46
387
src/test/java/org/jsoup/nodes/DocumentTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-523 ## Issue-Title: EscapeMode.xhtml no longer falls back to numeric escapes - Can cause '?' replacement in output ## Issue-Description: I've been using EscapeMode.xhtml with JSoup to avoid encoding things which don't (from my perspective) need to be encoded, like egrave in a UTF-8 document for example. While upgrading from JSoup 1.7.2 to 1.8.1 however, I've noticed a problem with a shift-jis related test I have. Here's a simplified/reduced version. ``` package test; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.Charset; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Entities.EscapeMode; import org.junit.Assert; import org.junit.Test; public class ShiftJisTest { @Test public void testShiftJisRoundtrip() throws Exception { String input = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=Shift_JIS\" />" + "</head>" + "<body>" + "before&nbsp;after" + "</body>" + "</html>"; InputStream is = new ByteArrayInputStream(input.getBytes(Charset.forName("ASCII"))); Document doc = Jsoup.parse(is, null, "http://example.com"); doc.outputSettings().escapeMode(EscapeMode.xhtml); String output = new String(doc.html().getBytes(doc.outputSettings().charset()), doc.outputSettings().charset()); System.out.println(output); Assert.assertFalse("Should not have contained a '?'.", output.contains("?")); Assert.assertTrue("Should have contained a '&#xa0;' or a '&nbsp;'.", output.contains("&#xa0;") || output.contains("&nbsp;")); } } ``` Under JSoup 1.7.2, the body of the output in this test is "before after" (which looks as expected when rendered in Firefox), where as under 1.8.1 it is "before?after". I assume the issue here is that I've asked JSoup to escape only XHTML characters (i.e. not nbsp), and it's producing a charset where (I assume) there's no character to represent 'non-breaking space'. The upshot of this is that, as a result of upgrading JSoup, I end up with '?' replaced in for what used to be shown as a non breaking space. It seems like the old behaviour was to fall back to providing an escaped numeric character (odd if there's no valid character for that in Shift\_JIS, but it still rendered correctly). From my perspective, the old behaviour was better - Is there any way it can be reinstated (or an escape mode provided for it)? Obviously using EscapeMode.base instead of EscapeMode.xhtml is a possible workaround, however I would really prefer not to have characters unnecessarily escaped if possible. ``` You are a professional Java test case writer, please create a test case named `testShiftJisRoundtrip` for the issue `Jsoup-523`, utilizing the provided issue report information and the following function signature. ```java @Test public void testShiftJisRoundtrip() throws Exception { ```
387
[ "org.jsoup.nodes.Entities" ]
d669f5d666e00f561fa76583567cef6e01ff4f717c76242a2e73559c70854bb1
@Test public void testShiftJisRoundtrip() throws Exception
// You are a professional Java test case writer, please create a test case named `testShiftJisRoundtrip` for the issue `Jsoup-523`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-523 // // ## Issue-Title: // EscapeMode.xhtml no longer falls back to numeric escapes - Can cause '?' replacement in output // // ## Issue-Description: // I've been using EscapeMode.xhtml with JSoup to avoid encoding things which don't (from my perspective) need to be encoded, like egrave in a UTF-8 document for example. // // // While upgrading from JSoup 1.7.2 to 1.8.1 however, I've noticed a problem with a shift-jis related test I have. Here's a simplified/reduced version. // // // // ``` // package test; // // import java.io.ByteArrayInputStream; // import java.io.InputStream; // import java.nio.charset.Charset; // // import org.jsoup.Jsoup; // import org.jsoup.nodes.Document; // import org.jsoup.nodes.Entities.EscapeMode; // import org.junit.Assert; // import org.junit.Test; // // public class ShiftJisTest { // // @Test // public void testShiftJisRoundtrip() throws Exception { // String input = // "<html>" // + "<head>" // + "<meta http-equiv=\"content-type\" content=\"text/html; charset=Shift_JIS\" />" // + "</head>" // + "<body>" // + "before&nbsp;after" // + "</body>" // + "</html>"; // InputStream is = new ByteArrayInputStream(input.getBytes(Charset.forName("ASCII"))); // // Document doc = Jsoup.parse(is, null, "http://example.com"); // doc.outputSettings().escapeMode(EscapeMode.xhtml); // // String output = new String(doc.html().getBytes(doc.outputSettings().charset()), doc.outputSettings().charset()); // // System.out.println(output); // // Assert.assertFalse("Should not have contained a '?'.", output.contains("?")); // Assert.assertTrue("Should have contained a '&#xa0;' or a '&nbsp;'.", // output.contains("&#xa0;") || output.contains("&nbsp;")); // } // // } // // ``` // // Under JSoup 1.7.2, the body of the output in this test is "before after" (which looks as expected when rendered in Firefox), where as under 1.8.1 it is "before?after". // // // I assume the issue here is that I've asked JSoup to escape only XHTML characters (i.e. not nbsp), and it's producing a charset where (I assume) there's no character to represent 'non-breaking space'. // // // The upshot of this is that, as a result of upgrading JSoup, I end up with '?' replaced in for what used to be shown as a non breaking space. // // // It seems like the old behaviour was to fall back to providing an escaped numeric character (odd if there's no valid character for that in Shift\_JIS, but it still rendered correctly). From my perspective, the old behaviour was better - Is there any way it can be reinstated (or an escape mode provided for it)? // // // Obviously using EscapeMode.base instead of EscapeMode.xhtml is a possible workaround, however I would really prefer not to have characters unnecessarily escaped if possible. // // // //
Jsoup
package org.jsoup.nodes; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.integration.ParseTest; import org.jsoup.nodes.Document.OutputSettings.Syntax; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; /** Tests for Document. @author Jonathan Hedley, [email protected] */ public class DocumentTest { private static final String charsetUtf8 = "UTF-8"; private static final String charsetIso8859 = "ISO-8859-1"; @Test public void setTextPreservesDocumentStructure() { Document doc = Jsoup.parse("<p>Hello</p>"); doc.text("Replaced"); assertEquals("Replaced", doc.text()); assertEquals("Replaced", doc.body().text()); assertEquals(1, doc.select("head").size()); } @Test public void testTitles() { Document noTitle = Jsoup.parse("<p>Hello</p>"); Document withTitle = Jsoup.parse("<title>First</title><title>Ignore</title><p>Hello</p>"); assertEquals("", noTitle.title()); noTitle.title("Hello"); assertEquals("Hello", noTitle.title()); assertEquals("Hello", noTitle.select("title").first().text()); assertEquals("First", withTitle.title()); withTitle.title("Hello"); assertEquals("Hello", withTitle.title()); assertEquals("Hello", withTitle.select("title").first().text()); Document normaliseTitle = Jsoup.parse("<title> Hello\nthere \n now \n"); assertEquals("Hello there now", normaliseTitle.title()); } @Test public void testOutputEncoding() { Document doc = Jsoup.parse("<p title=π>π & < > </p>"); // default is utf-8 assertEquals("<p title=\"π\">π &amp; &lt; &gt; </p>", doc.body().html()); assertEquals("UTF-8", doc.outputSettings().charset().name()); doc.outputSettings().charset("ascii"); assertEquals(Entities.EscapeMode.base, doc.outputSettings().escapeMode()); assertEquals("<p title=\"&#x3c0;\">&#x3c0; &amp; &lt; &gt; </p>", doc.body().html()); doc.outputSettings().escapeMode(Entities.EscapeMode.extended); assertEquals("<p title=\"&pi;\">&pi; &amp; &lt; &gt; </p>", doc.body().html()); } @Test public void testXhtmlReferences() { Document doc = Jsoup.parse("&lt; &gt; &amp; &quot; &apos; &times;"); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); assertEquals("&lt; &gt; &amp; \" ' ×", doc.body().html()); } @Test public void testNormalisesStructure() { Document doc = Jsoup.parse("<html><head><script>one</script><noscript><p>two</p></noscript></head><body><p>three</p></body><p>four</p></html>"); assertEquals("<html><head><script>one</script><noscript>&lt;p&gt;two</noscript></head><body><p>three</p><p>four</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testClone() { Document doc = Jsoup.parse("<title>Hello</title> <p>One<p>Two"); Document clone = doc.clone(); assertEquals("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>", TextUtil.stripNewlines(clone.html())); clone.title("Hello there"); clone.select("p").first().text("One more").attr("id", "1"); assertEquals("<html><head><title>Hello there</title> </head><body><p id=\"1\">One more</p><p>Two</p></body></html>", TextUtil.stripNewlines(clone.html())); assertEquals("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testClonesDeclarations() { Document doc = Jsoup.parse("<!DOCTYPE html><html><head><title>Doctype test"); Document clone = doc.clone(); assertEquals(doc.html(), clone.html()); assertEquals("<!doctype html><html><head><title>Doctype test</title></head><body></body></html>", TextUtil.stripNewlines(clone.html())); } @Test public void testLocation() throws IOException { File in = new ParseTest().getFile("/htmltests/yahoo-jp.html"); Document doc = Jsoup.parse(in, "UTF-8", "http://www.yahoo.co.jp/index.html"); String location = doc.location(); String baseUri = doc.baseUri(); assertEquals("http://www.yahoo.co.jp/index.html",location); assertEquals("http://www.yahoo.co.jp/_ylh=X3oDMTB0NWxnaGxsBF9TAzIwNzcyOTYyNjUEdGlkAzEyBHRtcGwDZ2Ex/",baseUri); in = new ParseTest().getFile("/htmltests/nyt-article-1.html"); doc = Jsoup.parse(in, null, "http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp"); location = doc.location(); baseUri = doc.baseUri(); assertEquals("http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp",location); assertEquals("http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp",baseUri); } @Test public void testHtmlAndXmlSyntax() { String h = "<!DOCTYPE html><body><img async checked='checked' src='&<>\"'>&lt;&gt;&amp;&quot;<foo />bar"; Document doc = Jsoup.parse(h); doc.outputSettings().syntax(Syntax.html); assertEquals("<!doctype html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async checked src=\"&amp;<>&quot;\">&lt;&gt;&amp;\"\n" + " <foo />bar\n" + " </body>\n" + "</html>", doc.html()); doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml); assertEquals("<!DOCTYPE html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async=\"\" checked=\"checked\" src=\"&amp;<>&quot;\" />&lt;&gt;&amp;\"\n" + " <foo />bar\n" + " </body>\n" + "</html>", doc.html()); } @Test public void htmlParseDefaultsToHtmlOutputSyntax() { Document doc = Jsoup.parse("x"); assertEquals(Syntax.html, doc.outputSettings().syntax()); } // Ignored since this test can take awhile to run. @Ignore @Test public void testOverflowClone() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < 100000; i++) { builder.insert(0, "<i>"); builder.append("</i>"); } Document doc = Jsoup.parse(builder.toString()); doc.clone(); } @Test public void DocumentsWithSameContentAreEqual() throws Exception { Document docA = Jsoup.parse("<div/>One"); Document docB = Jsoup.parse("<div/>One"); Document docC = Jsoup.parse("<div/>Two"); assertEquals(docA, docB); assertFalse(docA.equals(docC)); assertEquals(docA.hashCode(), docB.hashCode()); assertFalse(docA.hashCode() == docC.hashCode()); } @Test public void testMetaCharsetUpdateUtf8() { final Document doc = createHtmlDocument("changeThis"); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetUTF8, doc.toString()); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetUtf8, doc.charset().name()); assertEquals(charsetUtf8, selectedElement.attr("charset")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateIso8859() { final Document doc = createHtmlDocument("changeThis"); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetIso8859)); final String htmlCharsetISO = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetIso8859 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetISO, doc.toString()); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetIso8859, doc.charset().name()); assertEquals(charsetIso8859, selectedElement.attr("charset")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateNoCharset() { final Document docNoCharset = Document.createShell(""); docNoCharset.updateMetaCharsetElement(true); docNoCharset.charset(Charset.forName(charsetUtf8)); assertEquals(charsetUtf8, docNoCharset.select("meta[charset]").first().attr("charset")); final String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetUTF8, docNoCharset.toString()); } @Test public void testMetaCharsetUpdateDisabled() { final Document docDisabled = Document.createShell(""); final String htmlNoCharset = "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlNoCharset, docDisabled.toString()); assertNull(docDisabled.select("meta[charset]").first()); } @Test public void testMetaCharsetUpdateDisabledNoChanges() { final Document doc = createHtmlDocument("dontTouch"); final String htmlCharset = "<html>\n" + " <head>\n" + " <meta charset=\"dontTouch\">\n" + " <meta name=\"charset\" content=\"dontTouch\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharset, doc.toString()); Element selectedElement = doc.select("meta[charset]").first(); assertNotNull(selectedElement); assertEquals("dontTouch", selectedElement.attr("charset")); selectedElement = doc.select("meta[name=charset]").first(); assertNotNull(selectedElement); assertEquals("dontTouch", selectedElement.attr("content")); } @Test public void testMetaCharsetUpdateEnabledAfterCharsetChange() { final Document doc = createHtmlDocument("dontTouch"); doc.charset(Charset.forName(charsetUtf8)); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetUtf8, selectedElement.attr("charset")); assertTrue(doc.select("meta[name=charset]").isEmpty()); } @Test public void testMetaCharsetUpdateCleanup() { final Document doc = createHtmlDocument("dontTouch"); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlCharsetUTF8, doc.toString()); } @Test public void testMetaCharsetUpdateXmlUtf8() { final Document doc = createXmlDocument("1.0", "changeThis", true); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String xmlCharsetUTF8 = "<?xml version=\"1.0\" encoding=\"" + charsetUtf8 + "\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharsetUTF8, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals(charsetUtf8, doc.charset().name()); assertEquals(charsetUtf8, selectedNode.attr("encoding")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateXmlIso8859() { final Document doc = createXmlDocument("1.0", "changeThis", true); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetIso8859)); final String xmlCharsetISO = "<?xml version=\"1.0\" encoding=\"" + charsetIso8859 + "\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharsetISO, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals(charsetIso8859, doc.charset().name()); assertEquals(charsetIso8859, selectedNode.attr("encoding")); assertEquals(doc.charset(), doc.outputSettings().charset()); } @Test public void testMetaCharsetUpdateXmlNoCharset() { final Document doc = createXmlDocument("1.0", "none", false); doc.updateMetaCharsetElement(true); doc.charset(Charset.forName(charsetUtf8)); final String xmlCharsetUTF8 = "<?xml version=\"1.0\" encoding=\"" + charsetUtf8 + "\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharsetUTF8, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals(charsetUtf8, selectedNode.attr("encoding")); } @Test public void testMetaCharsetUpdateXmlDisabled() { final Document doc = createXmlDocument("none", "none", false); final String xmlNoCharset = "<root>\n" + " node\n" + "</root>"; assertEquals(xmlNoCharset, doc.toString()); } @Test public void testMetaCharsetUpdateXmlDisabledNoChanges() { final Document doc = createXmlDocument("dontTouch", "dontTouch", true); final String xmlCharset = "<?xml version=\"dontTouch\" encoding=\"dontTouch\">\n" + "<root>\n" + " node\n" + "</root>"; assertEquals(xmlCharset, doc.toString()); XmlDeclaration selectedNode = (XmlDeclaration) doc.childNode(0); assertEquals("dontTouch", selectedNode.attr("encoding")); assertEquals("dontTouch", selectedNode.attr("version")); } @Test public void testMetaCharsetUpdatedDisabledPerDefault() { final Document doc = createHtmlDocument("none"); assertFalse(doc.updateMetaCharsetElement()); } private Document createHtmlDocument(String charset) { final Document doc = Document.createShell(""); doc.head().appendElement("meta").attr("charset", charset); doc.head().appendElement("meta").attr("name", "charset").attr("content", charset); return doc; } private Document createXmlDocument(String version, String charset, boolean addDecl) { final Document doc = new Document(""); doc.appendElement("root").text("node"); doc.outputSettings().syntax(Syntax.xml); if( addDecl == true ) { XmlDeclaration decl = new XmlDeclaration("xml", "", false); decl.attr("version", version); decl.attr("encoding", charset); doc.prependChild(decl); } return doc; } @Test public void testShiftJisRoundtrip() throws Exception { String input = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=Shift_JIS\" />" + "</head>" + "<body>" + "before&nbsp;after" + "</body>" + "</html>"; InputStream is = new ByteArrayInputStream(input.getBytes(Charset.forName("ASCII"))); Document doc = Jsoup.parse(is, null, "http://example.com"); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); String output = new String(doc.html().getBytes(doc.outputSettings().charset()), doc.outputSettings().charset()); assertFalse("Should not have contained a '?'.", output.contains("?")); assertTrue("Should have contained a '&#xa0;' or a '&nbsp;'.", output.contains("&#xa0;") || output.contains("&nbsp;")); } }
@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())); }
org.jsoup.parser.ParserTest::handlesTextAfterData
src/test/java/org/jsoup/parser/ParserTest.java
138
src/test/java/org/jsoup/parser/ParserTest.java
handlesTextAfterData
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Comment; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** Tests for the Parser @author Jonathan Hedley, [email protected] */ public class ParserTest { @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 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 parsesUnterminatedTag() { String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(1, doc.getElementsByTag("p").size()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); Element d = doc.getElementById("1"); assertEquals(1, d.children().size()); Element p = doc.getElementById("2"); assertNotNull(p); } @Test public void parsesUnterminatedAttribute() { String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); Element p = doc.getElementById("foo"); assertNotNull(p); assertEquals("p", p.tagName()); } @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>Nope</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("Nope", 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 createsImplicitLists() { String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should have created a default ul. assertEquals(1, ol.size()); assertEquals(2, ol.get(0).children().size()); // 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 createsImplicitTable() { String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("<table><tr><td>Hello</td><td><p>There</p><p>now</p></td></tr></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { 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://bar", doc.baseUri()); // gets updated as base changes, so doc.createElement has latest. Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://bar", anchors.get(2).baseUri()); assertEquals("http://foo/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://bar/4", anchors.get(2).absUrl("href")); } @Test public void handlesCdata() { String h = "<div id=1><![CData[<html>\n<foo><&amp;]]></div>"; // "cdata" insensitive. 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.childNodes().size()); // no elements, one text node } @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 handlesEmptyBlocks() { String h = "<div id=1/><div id=2><img /></div>"; Document doc = Jsoup.parse(h); Element div1 = doc.getElementById("1"); assertTrue(div1.children().isEmpty()); } @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() { String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(4, doc.body().getElementsByTag("dl").first().children().size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @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><body></body></html>", TextUtil.stripNewlines(doc.html())); } @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() {} // Defects4J: flaky method // @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><link /></head><body>Five Six Seven One Two Four Three</body></html>", // TextUtil.stripNewlines(doc.html())); // is spaced OK if not newline & space stripped // } @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())); } }
// You are a professional Java test case writer, please create a test case named `handlesTextAfterData` for the issue `Jsoup-22`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-22 // // ## Issue-Title: // Unadorned text following data-only tags doesn't parse properly // // ## Issue-Description: // This HTML, parsed and immediately printed out, results in: // // // <html> // // <body> // // <script type="text/javascript"> // // var inside = true; // // </script> // // this should be outside. // // </body> // // </html> // // // Results: // // // <html> // // <head> // // </head> // // <body> // // <script type="text/javascript"> // // var inside = true; // // // this should be outside. // // // </script> // // </body> // // </html> // // // Note how "this should be outside" ends up inside the <script> tag, instead of following it. From what I can tell, this only happens to data-only tags. // // // // @Test public void handlesTextAfterData() {
138
2
134
src/test/java/org/jsoup/parser/ParserTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-22 ## Issue-Title: Unadorned text following data-only tags doesn't parse properly ## Issue-Description: This HTML, parsed and immediately printed out, results in: <html> <body> <script type="text/javascript"> var inside = true; </script> this should be outside. </body> </html> Results: <html> <head> </head> <body> <script type="text/javascript"> var inside = true; this should be outside. </script> </body> </html> Note how "this should be outside" ends up inside the <script> tag, instead of following it. From what I can tell, this only happens to data-only tags. ``` You are a professional Java test case writer, please create a test case named `handlesTextAfterData` for the issue `Jsoup-22`, utilizing the provided issue report information and the following function signature. ```java @Test public void handlesTextAfterData() { ```
134
[ "org.jsoup.parser.Parser" ]
d6b65e7ac11a8e6d68e44053fcd8409ebdc8ff2064a21a5d75cf4a17b8ec37bc
@Test public void handlesTextAfterData()
// You are a professional Java test case writer, please create a test case named `handlesTextAfterData` for the issue `Jsoup-22`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-22 // // ## Issue-Title: // Unadorned text following data-only tags doesn't parse properly // // ## Issue-Description: // This HTML, parsed and immediately printed out, results in: // // // <html> // // <body> // // <script type="text/javascript"> // // var inside = true; // // </script> // // this should be outside. // // </body> // // </html> // // // Results: // // // <html> // // <head> // // </head> // // <body> // // <script type="text/javascript"> // // var inside = true; // // // this should be outside. // // // </script> // // </body> // // </html> // // // Note how "this should be outside" ends up inside the <script> tag, instead of following it. From what I can tell, this only happens to data-only tags. // // // //
Jsoup
package org.jsoup.parser; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.nodes.Comment; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** Tests for the Parser @author Jonathan Hedley, [email protected] */ public class ParserTest { @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 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 parsesUnterminatedTag() { String h1 = "<p"; Document doc = Jsoup.parse(h1); assertEquals(1, doc.getElementsByTag("p").size()); String h2 = "<div id=1<p id='2'"; doc = Jsoup.parse(h2); Element d = doc.getElementById("1"); assertEquals(1, d.children().size()); Element p = doc.getElementById("2"); assertNotNull(p); } @Test public void parsesUnterminatedAttribute() { String h1 = "<p id=\"foo"; Document doc = Jsoup.parse(h1); Element p = doc.getElementById("foo"); assertNotNull(p); assertEquals("p", p.tagName()); } @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>Nope</script><p>There</p>"; Document doc = Jsoup.parse(s); assertEquals("Hello There", doc.text()); assertEquals("Nope", 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 createsImplicitLists() { String h = "<li>Point one<li>Point two"; Document doc = Jsoup.parse(h); Elements ol = doc.select("ul"); // should have created a default ul. assertEquals(1, ol.size()); assertEquals(2, ol.get(0).children().size()); // 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 createsImplicitTable() { String h = "<td>Hello<td><p>There<p>now"; Document doc = Jsoup.parse(h); assertEquals("<table><tr><td>Hello</td><td><p>There</p><p>now</p></td></tr></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesBaseTags() { 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://bar", doc.baseUri()); // gets updated as base changes, so doc.createElement has latest. Elements anchors = doc.getElementsByTag("a"); assertEquals(3, anchors.size()); assertEquals("http://foo/", anchors.get(0).baseUri()); assertEquals("http://foo/2/", anchors.get(1).baseUri()); assertEquals("http://bar", anchors.get(2).baseUri()); assertEquals("http://foo/1", anchors.get(0).absUrl("href")); assertEquals("http://foo/2/3", anchors.get(1).absUrl("href")); assertEquals("http://bar/4", anchors.get(2).absUrl("href")); } @Test public void handlesCdata() { String h = "<div id=1><![CData[<html>\n<foo><&amp;]]></div>"; // "cdata" insensitive. 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.childNodes().size()); // no elements, one text node } @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 handlesEmptyBlocks() { String h = "<div id=1/><div id=2><img /></div>"; Document doc = Jsoup.parse(h); Element div1 = doc.getElementById("1"); assertTrue(div1.children().isEmpty()); } @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() { String h = "<dt>Foo<dd>Bar<dt>Qux<dd>Zug"; Document doc = Jsoup.parse(h); assertEquals(4, doc.body().getElementsByTag("dl").first().children().size()); Elements dts = doc.select("dt"); assertEquals(2, dts.size()); assertEquals("Zug", dts.get(1).nextElementSibling().text()); } @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><body></body></html>", TextUtil.stripNewlines(doc.html())); } @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() {} // Defects4J: flaky method // @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><link /></head><body>Five Six Seven One Two Four Three</body></html>", // TextUtil.stripNewlines(doc.html())); // is spaced OK if not newline & space stripped // } @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())); } }
public void testBug1832432() { TimeSeries s1 = new TimeSeries("Series"); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); // test independence s1.add(new Day(1, 1, 2007), 100.0); assertFalse(s1.equals(s2)); }
org.jfree.data.time.junit.TimeSeriesTests::testBug1832432
tests/org/jfree/data/time/junit/TimeSeriesTests.java
630
tests/org/jfree/data/time/junit/TimeSeriesTests.java
testBug1832432
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TimeSeriesTests.java * -------------------- * (C) Copyright 2001-2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2001 : Version 1 (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 15-Oct-2003 : Added test for setMaximumItemCount method (DG); * 23-Aug-2004 : Added test that highlights a bug where the addOrUpdate() * method can lead to more than maximumItemCount items in the * dataset (DG); * 24-May-2006 : Added new tests (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 31-Oct-2007 : New hashCode() test (DG); * 21-Nov-2007 : Added testBug1832432() and testClone2() (DG); * */ package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; /** * A collection of test cases for the {@link TimeSeries} class. */ public class TimeSeriesTests extends TestCase implements SeriesChangeListener { /** A time series. */ private TimeSeries seriesA; /** A time series. */ private TimeSeries seriesB; /** A time series. */ private TimeSeries seriesC; /** A flag that indicates whether or not a change event was fired. */ private boolean gotSeriesChangeEvent = false; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.seriesA = new TimeSeries("Series A", Year.class); try { this.seriesA.add(new Year(2000), new Integer(102000)); this.seriesA.add(new Year(2001), new Integer(102001)); this.seriesA.add(new Year(2002), new Integer(102002)); this.seriesA.add(new Year(2003), new Integer(102003)); this.seriesA.add(new Year(2004), new Integer(102004)); this.seriesA.add(new Year(2005), new Integer(102005)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesB = new TimeSeries("Series B", Year.class); try { this.seriesB.add(new Year(2006), new Integer(202006)); this.seriesB.add(new Year(2007), new Integer(202007)); this.seriesB.add(new Year(2008), new Integer(202008)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesC = new TimeSeries("Series C", Year.class); try { this.seriesC.add(new Year(1999), new Integer(301999)); this.seriesC.add(new Year(2000), new Integer(302000)); this.seriesC.add(new Year(2002), new Integer(302002)); } catch (SeriesException e) { System.err.println("Problem creating series."); } } /** * Sets the flag to indicate that a {@link SeriesChangeEvent} has been * received. * * @param event the event. */ public void seriesChanged(SeriesChangeEvent event) { this.gotSeriesChangeEvent = true; } /** * Check that cloning works. */ public void testClone() { TimeSeries series = new TimeSeries("Test Series"); RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002); try { series.add(jan1st2002, new Integer(42)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } TimeSeries clone = null; try { clone = (TimeSeries) series.clone(); clone.setKey("Clone Series"); try { clone.update(jan1st2002, new Integer(10)); } catch (SeriesException e) { e.printStackTrace(); } } catch (CloneNotSupportedException e) { assertTrue(false); } int seriesValue = series.getValue(jan1st2002).intValue(); int cloneValue = Integer.MAX_VALUE; if (clone != null) { cloneValue = clone.getValue(jan1st2002).intValue(); } assertEquals(42, seriesValue); assertEquals(10, cloneValue); assertEquals("Test Series", series.getKey()); if (clone != null) { assertEquals("Clone Series", clone.getKey()); } else { assertTrue(false); } } /** * Another test of the clone() method. */ public void testClone2() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2007), 100.0); s1.add(new Year(2008), null); s1.add(new Year(2009), 200.0); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.addOrUpdate(new Year(2009), 300.0); assertFalse(s1.equals(s2)); s1.addOrUpdate(new Year(2009), 300.0); assertTrue(s1.equals(s2)); } /** * Add a value to series A for 1999. It should be added at index 0. */ public void testAddValue() { try { this.seriesA.add(new Year(1999), new Integer(1)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } int value = this.seriesA.getValue(0).intValue(); assertEquals(1, value); } /** * Tests the retrieval of values. */ public void testGetValue() { Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } /** * Tests the deletion of values. */ public void testDelete() { this.seriesA.delete(0, 0); assertEquals(5, this.seriesA.getItemCount()); Number value = this.seriesA.getValue(new Year(2000)); assertNull(value); } /** * Basic tests for the delete() method. */ public void testDelete2() { TimeSeries s1 = new TimeSeries("Series", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(s1.equals(s2)); } /** * Tests the equals method. */ public void testEquals() { TimeSeries s1 = new TimeSeries("Time Series 1"); TimeSeries s2 = new TimeSeries("Time Series 2"); boolean b1 = s1.equals(s2); assertFalse("b1", b1); s2.setKey("Time Series 1"); boolean b2 = s1.equals(s2); assertTrue("b2", b2); RegularTimePeriod p1 = new Day(); RegularTimePeriod p2 = p1.next(); s1.add(p1, 100.0); s1.add(p2, 200.0); boolean b3 = s1.equals(s2); assertFalse("b3", b3); s2.add(p1, 100.0); s2.add(p2, 200.0); boolean b4 = s1.equals(s2); assertTrue("b4", b4); s1.setMaximumItemCount(100); boolean b5 = s1.equals(s2); assertFalse("b5", b5); s2.setMaximumItemCount(100); boolean b6 = s1.equals(s2); assertTrue("b6", b6); s1.setMaximumItemAge(100); boolean b7 = s1.equals(s2); assertFalse("b7", b7); s2.setMaximumItemAge(100); boolean b8 = s1.equals(s2); assertTrue("b8", b8); } /** * Tests a specific bug report where null arguments in the constructor * cause the equals() method to fail. Fixed for 0.9.21. */ public void testEquals2() { TimeSeries s1 = new TimeSeries("Series", null, null, Day.class); TimeSeries s2 = new TimeSeries("Series", null, null, Day.class); assertTrue(s1.equals(s2)); } /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Some tests to ensure that the createCopy(int, int) method is * functioning correctly. */ public void testCreateCopy2() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy just the first item... TimeSeries result1 = series.createCopy(0, 0); assertEquals(new Month(1, 2003), result1.getTimePeriod(0)); // copy the first two items... result1 = series.createCopy(0, 1); assertEquals(new Month(2, 2003), result1.getTimePeriod(1)); // copy the middle three items... result1 = series.createCopy(1, 3); assertEquals(new Month(2, 2003), result1.getTimePeriod(0)); assertEquals(new Month(11, 2003), result1.getTimePeriod(2)); // copy the last two items... result1 = series.createCopy(3, 4); assertEquals(new Month(11, 2003), result1.getTimePeriod(0)); assertEquals(new Month(12, 2003), result1.getTimePeriod(1)); // copy the last item... result1 = series.createCopy(4, 4); assertEquals(new Month(12, 2003), result1.getTimePeriod(0)); } catch (CloneNotSupportedException e) { assertTrue(false); } // check negative first argument boolean pass = false; try { /* TimeSeries result = */ series.createCopy(-1, 1); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); // check second argument less than first argument pass = false; try { /* TimeSeries result = */ series.createCopy(1, 0); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); TimeSeries series2 = new TimeSeries("Series 2"); try { TimeSeries series3 = series2.createCopy(99, 999); assertEquals(0, series3.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2000), 100.0); assertEquals(1, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 101.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 102.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2002), 103.0); assertEquals(2, s1.getItemCount()); } /** * A test for the bug report 1075255. */ public void testBug1075255() { TimeSeries ts = new TimeSeries("dummy", FixedMillisecond.class); ts.add(new FixedMillisecond(0L), 0.0); TimeSeries ts2 = new TimeSeries("dummy2", FixedMillisecond.class); ts2.add(new FixedMillisecond(0L), 1.0); try { ts.addAndOrUpdate(ts2); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } assertEquals(1, ts.getItemCount()); } /** * A test for bug 1832432. */ public void testBug1832432() { TimeSeries s1 = new TimeSeries("Series"); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); // test independence s1.add(new Day(1, 1, 2007), 100.0); assertFalse(s1.equals(s2)); } /** * Some checks for the getIndex() method. */ public void testGetIndex() { TimeSeries series = new TimeSeries("Series", Month.class); assertEquals(-1, series.getIndex(new Month(1, 2003))); series.add(new Month(1, 2003), 45.0); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(-2, series.getIndex(new Month(2, 2003))); series.add(new Month(3, 2003), 55.0); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-2, series.getIndex(new Month(2, 2003))); assertEquals(1, series.getIndex(new Month(3, 2003))); assertEquals(-3, series.getIndex(new Month(4, 2003))); } /** * Some checks for the getDataItem(int) method. */ public void testGetDataItem1() { TimeSeries series = new TimeSeries("S", Year.class); // can't get anything yet...just an exception boolean pass = false; try { /*TimeSeriesDataItem item =*/ series.getDataItem(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); series.add(new Year(2006), 100.0); TimeSeriesDataItem item = series.getDataItem(0); assertEquals(new Year(2006), item.getPeriod()); pass = false; try { /*item = */series.getDataItem(-1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); pass = false; try { /*item = */series.getDataItem(1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getDataItem(RegularTimePeriod) method. */ public void testGetDataItem2() { TimeSeries series = new TimeSeries("S", Year.class); assertNull(series.getDataItem(new Year(2006))); // try a null argument boolean pass = false; try { /* TimeSeriesDataItem item = */ series.getDataItem(null); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the removeAgedItems() method. */ public void testRemoveAgedItems() { TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with one item series.add(new Year(1999), 1.0); series.setMaximumItemAge(0); this.gotSeriesChangeEvent = false; series.removeAgedItems(true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with two items series.setMaximumItemAge(10); series.add(new Year(2001), 2.0); this.gotSeriesChangeEvent = false; series.setMaximumItemAge(2); assertEquals(2, series.getItemCount()); assertEquals(0, series.getIndex(new Year(1999))); assertFalse(this.gotSeriesChangeEvent); series.setMaximumItemAge(1); assertEquals(1, series.getItemCount()); assertEquals(0, series.getIndex(new Year(2001))); assertTrue(this.gotSeriesChangeEvent); } /** * Some checks for the removeAgedItems(long, boolean) method. */ public void testRemoveAgedItems2() { long y2006 = 1157087372534L; // milliseconds somewhere in 2006 TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test a series with 1 item series.add(new Year(2004), 1.0); series.setMaximumItemAge(1); this.gotSeriesChangeEvent = false; series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); // test a series with two items series.setMaximumItemAge(2); series.add(new Year(2003), 1.0); series.add(new Year(2005), 2.0); assertEquals(2, series.getItemCount()); this.gotSeriesChangeEvent = false; assertEquals(2, series.getItemCount()); series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(2, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(1, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { TimeSeries s1 = new TimeSeries("Test"); TimeSeries s2 = new TimeSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(1, 1, 2007), 500.0); s2.add(new Day(1, 1, 2007), 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(2, 1, 2007), null); s2.add(new Day(2, 1, 2007), null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(5, 1, 2007), 111.0); s2.add(new Day(5, 1, 2007), 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(9, 1, 2007), 1.0); s2.add(new Day(9, 1, 2007), 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } }
// You are a professional Java test case writer, please create a test case named `testBug1832432` for the issue `Chart-803`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-803 // // ## Issue-Title: // #803 cloning of TimeSeries // // // // // // ## Issue-Description: // It's just a minor bug! // // // When I clone a TimeSeries which has no items, I get an IllegalArgumentException ("Requires start <= end"). // // But I don't think the user should be responsible for checking whether the TimeSeries has any items or not. // // // // public void testBug1832432() {
630
/** * A test for bug 1832432. */
17
614
tests/org/jfree/data/time/junit/TimeSeriesTests.java
tests
```markdown ## Issue-ID: Chart-803 ## Issue-Title: #803 cloning of TimeSeries ## Issue-Description: It's just a minor bug! When I clone a TimeSeries which has no items, I get an IllegalArgumentException ("Requires start <= end"). But I don't think the user should be responsible for checking whether the TimeSeries has any items or not. ``` You are a professional Java test case writer, please create a test case named `testBug1832432` for the issue `Chart-803`, utilizing the provided issue report information and the following function signature. ```java public void testBug1832432() { ```
614
[ "org.jfree.data.time.TimeSeries" ]
d737221796bc2e9ca8ddb86daea4e977636e847d01d653c7b6f66c21729d5c57
public void testBug1832432()
// You are a professional Java test case writer, please create a test case named `testBug1832432` for the issue `Chart-803`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-803 // // ## Issue-Title: // #803 cloning of TimeSeries // // // // // // ## Issue-Description: // It's just a minor bug! // // // When I clone a TimeSeries which has no items, I get an IllegalArgumentException ("Requires start <= end"). // // But I don't think the user should be responsible for checking whether the TimeSeries has any items or not. // // // //
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TimeSeriesTests.java * -------------------- * (C) Copyright 2001-2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Nov-2001 : Version 1 (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 15-Oct-2003 : Added test for setMaximumItemCount method (DG); * 23-Aug-2004 : Added test that highlights a bug where the addOrUpdate() * method can lead to more than maximumItemCount items in the * dataset (DG); * 24-May-2006 : Added new tests (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 31-Oct-2007 : New hashCode() test (DG); * 21-Nov-2007 : Added testBug1832432() and testClone2() (DG); * */ package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.general.SeriesChangeEvent; import org.jfree.data.general.SeriesChangeListener; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Day; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.Month; import org.jfree.data.time.MonthConstants; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.data.time.Year; /** * A collection of test cases for the {@link TimeSeries} class. */ public class TimeSeriesTests extends TestCase implements SeriesChangeListener { /** A time series. */ private TimeSeries seriesA; /** A time series. */ private TimeSeries seriesB; /** A time series. */ private TimeSeries seriesC; /** A flag that indicates whether or not a change event was fired. */ private boolean gotSeriesChangeEvent = false; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimeSeriesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimeSeriesTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.seriesA = new TimeSeries("Series A", Year.class); try { this.seriesA.add(new Year(2000), new Integer(102000)); this.seriesA.add(new Year(2001), new Integer(102001)); this.seriesA.add(new Year(2002), new Integer(102002)); this.seriesA.add(new Year(2003), new Integer(102003)); this.seriesA.add(new Year(2004), new Integer(102004)); this.seriesA.add(new Year(2005), new Integer(102005)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesB = new TimeSeries("Series B", Year.class); try { this.seriesB.add(new Year(2006), new Integer(202006)); this.seriesB.add(new Year(2007), new Integer(202007)); this.seriesB.add(new Year(2008), new Integer(202008)); } catch (SeriesException e) { System.err.println("Problem creating series."); } this.seriesC = new TimeSeries("Series C", Year.class); try { this.seriesC.add(new Year(1999), new Integer(301999)); this.seriesC.add(new Year(2000), new Integer(302000)); this.seriesC.add(new Year(2002), new Integer(302002)); } catch (SeriesException e) { System.err.println("Problem creating series."); } } /** * Sets the flag to indicate that a {@link SeriesChangeEvent} has been * received. * * @param event the event. */ public void seriesChanged(SeriesChangeEvent event) { this.gotSeriesChangeEvent = true; } /** * Check that cloning works. */ public void testClone() { TimeSeries series = new TimeSeries("Test Series"); RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002); try { series.add(jan1st2002, new Integer(42)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } TimeSeries clone = null; try { clone = (TimeSeries) series.clone(); clone.setKey("Clone Series"); try { clone.update(jan1st2002, new Integer(10)); } catch (SeriesException e) { e.printStackTrace(); } } catch (CloneNotSupportedException e) { assertTrue(false); } int seriesValue = series.getValue(jan1st2002).intValue(); int cloneValue = Integer.MAX_VALUE; if (clone != null) { cloneValue = clone.getValue(jan1st2002).intValue(); } assertEquals(42, seriesValue); assertEquals(10, cloneValue); assertEquals("Test Series", series.getKey()); if (clone != null) { assertEquals("Clone Series", clone.getKey()); } else { assertTrue(false); } } /** * Another test of the clone() method. */ public void testClone2() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2007), 100.0); s1.add(new Year(2008), null); s1.add(new Year(2009), 200.0); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); // check independence s2.addOrUpdate(new Year(2009), 300.0); assertFalse(s1.equals(s2)); s1.addOrUpdate(new Year(2009), 300.0); assertTrue(s1.equals(s2)); } /** * Add a value to series A for 1999. It should be added at index 0. */ public void testAddValue() { try { this.seriesA.add(new Year(1999), new Integer(1)); } catch (SeriesException e) { System.err.println("Problem adding to series."); } int value = this.seriesA.getValue(0).intValue(); assertEquals(1, value); } /** * Tests the retrieval of values. */ public void testGetValue() { Number value1 = this.seriesA.getValue(new Year(1999)); assertNull(value1); int value2 = this.seriesA.getValue(new Year(2000)).intValue(); assertEquals(102000, value2); } /** * Tests the deletion of values. */ public void testDelete() { this.seriesA.delete(0, 0); assertEquals(5, this.seriesA.getItemCount()); Number value = this.seriesA.getValue(new Year(2000)); assertNull(value); } /** * Basic tests for the delete() method. */ public void testDelete2() { TimeSeries s1 = new TimeSeries("Series", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.addChangeListener(this); this.gotSeriesChangeEvent = false; s1.delete(new Year(2001)); assertTrue(this.gotSeriesChangeEvent); assertEquals(2, s1.getItemCount()); assertEquals(null, s1.getValue(new Year(2001))); // try deleting a time period that doesn't exist... this.gotSeriesChangeEvent = false; s1.delete(new Year(2006)); assertFalse(this.gotSeriesChangeEvent); // try deleting null try { s1.delete(null); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException e) { // expected } } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(s1.equals(s2)); } /** * Tests the equals method. */ public void testEquals() { TimeSeries s1 = new TimeSeries("Time Series 1"); TimeSeries s2 = new TimeSeries("Time Series 2"); boolean b1 = s1.equals(s2); assertFalse("b1", b1); s2.setKey("Time Series 1"); boolean b2 = s1.equals(s2); assertTrue("b2", b2); RegularTimePeriod p1 = new Day(); RegularTimePeriod p2 = p1.next(); s1.add(p1, 100.0); s1.add(p2, 200.0); boolean b3 = s1.equals(s2); assertFalse("b3", b3); s2.add(p1, 100.0); s2.add(p2, 200.0); boolean b4 = s1.equals(s2); assertTrue("b4", b4); s1.setMaximumItemCount(100); boolean b5 = s1.equals(s2); assertFalse("b5", b5); s2.setMaximumItemCount(100); boolean b6 = s1.equals(s2); assertTrue("b6", b6); s1.setMaximumItemAge(100); boolean b7 = s1.equals(s2); assertFalse("b7", b7); s2.setMaximumItemAge(100); boolean b8 = s1.equals(s2); assertTrue("b8", b8); } /** * Tests a specific bug report where null arguments in the constructor * cause the equals() method to fail. Fixed for 0.9.21. */ public void testEquals2() { TimeSeries s1 = new TimeSeries("Series", null, null, Day.class); TimeSeries s2 = new TimeSeries("Series", null, null, Day.class); assertTrue(s1.equals(s2)); } /** * Some tests to ensure that the createCopy(RegularTimePeriod, * RegularTimePeriod) method is functioning correctly. */ public void testCreateCopy1() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy a range before the start of the series data... TimeSeries result1 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2002)); assertEquals(0, result1.getItemCount()); // copy a range that includes only the first item in the series... TimeSeries result2 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result2.getItemCount()); // copy a range that begins before and ends in the middle of the // series... TimeSeries result3 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result3.getItemCount()); TimeSeries result4 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result4.getItemCount()); TimeSeries result5 = series.createCopy( new Month(MonthConstants.NOVEMBER, 2002), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result5.getItemCount()); TimeSeries result6 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.JANUARY, 2003)); assertEquals(1, result6.getItemCount()); TimeSeries result7 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.APRIL, 2003)); assertEquals(2, result7.getItemCount()); TimeSeries result8 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(5, result8.getItemCount()); TimeSeries result9 = series.createCopy( new Month(MonthConstants.JANUARY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(5, result9.getItemCount()); TimeSeries result10 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(3, result10.getItemCount()); TimeSeries result11 = series.createCopy( new Month(MonthConstants.MAY, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(3, result11.getItemCount()); TimeSeries result12 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.DECEMBER, 2003)); assertEquals(1, result12.getItemCount()); TimeSeries result13 = series.createCopy( new Month(MonthConstants.DECEMBER, 2003), new Month(MonthConstants.MARCH, 2004)); assertEquals(1, result13.getItemCount()); TimeSeries result14 = series.createCopy( new Month(MonthConstants.JANUARY, 2004), new Month(MonthConstants.MARCH, 2004)); assertEquals(0, result14.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Some tests to ensure that the createCopy(int, int) method is * functioning correctly. */ public void testCreateCopy2() { TimeSeries series = new TimeSeries("Series", Month.class); series.add(new Month(MonthConstants.JANUARY, 2003), 45.0); series.add(new Month(MonthConstants.FEBRUARY, 2003), 55.0); series.add(new Month(MonthConstants.JUNE, 2003), 35.0); series.add(new Month(MonthConstants.NOVEMBER, 2003), 85.0); series.add(new Month(MonthConstants.DECEMBER, 2003), 75.0); try { // copy just the first item... TimeSeries result1 = series.createCopy(0, 0); assertEquals(new Month(1, 2003), result1.getTimePeriod(0)); // copy the first two items... result1 = series.createCopy(0, 1); assertEquals(new Month(2, 2003), result1.getTimePeriod(1)); // copy the middle three items... result1 = series.createCopy(1, 3); assertEquals(new Month(2, 2003), result1.getTimePeriod(0)); assertEquals(new Month(11, 2003), result1.getTimePeriod(2)); // copy the last two items... result1 = series.createCopy(3, 4); assertEquals(new Month(11, 2003), result1.getTimePeriod(0)); assertEquals(new Month(12, 2003), result1.getTimePeriod(1)); // copy the last item... result1 = series.createCopy(4, 4); assertEquals(new Month(12, 2003), result1.getTimePeriod(0)); } catch (CloneNotSupportedException e) { assertTrue(false); } // check negative first argument boolean pass = false; try { /* TimeSeries result = */ series.createCopy(-1, 1); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); // check second argument less than first argument pass = false; try { /* TimeSeries result = */ series.createCopy(1, 0); } catch (IllegalArgumentException e) { pass = true; } catch (CloneNotSupportedException e) { pass = false; } assertTrue(pass); TimeSeries series2 = new TimeSeries("Series 2"); try { TimeSeries series3 = series2.createCopy(99, 999); assertEquals(0, series3.getItemCount()); } catch (CloneNotSupportedException e) { assertTrue(false); } } /** * Test the setMaximumItemCount() method to ensure that it removes items * from the series if necessary. */ public void testSetMaximumItemCount() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); assertTrue(s1.getItemCount() == 5); s1.setMaximumItemCount(3); assertTrue(s1.getItemCount() == 3); TimeSeriesDataItem item = s1.getDataItem(0); assertTrue(item.getPeriod().equals(new Year(2002))); } /** * Some checks for the addOrUpdate() method. */ public void testAddOrUpdate() { TimeSeries s1 = new TimeSeries("S1", Year.class); s1.setMaximumItemCount(2); s1.addOrUpdate(new Year(2000), 100.0); assertEquals(1, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 101.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2001), 102.0); assertEquals(2, s1.getItemCount()); s1.addOrUpdate(new Year(2002), 103.0); assertEquals(2, s1.getItemCount()); } /** * A test for the bug report 1075255. */ public void testBug1075255() { TimeSeries ts = new TimeSeries("dummy", FixedMillisecond.class); ts.add(new FixedMillisecond(0L), 0.0); TimeSeries ts2 = new TimeSeries("dummy2", FixedMillisecond.class); ts2.add(new FixedMillisecond(0L), 1.0); try { ts.addAndOrUpdate(ts2); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } assertEquals(1, ts.getItemCount()); } /** * A test for bug 1832432. */ public void testBug1832432() { TimeSeries s1 = new TimeSeries("Series"); TimeSeries s2 = null; try { s2 = (TimeSeries) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); // test independence s1.add(new Day(1, 1, 2007), 100.0); assertFalse(s1.equals(s2)); } /** * Some checks for the getIndex() method. */ public void testGetIndex() { TimeSeries series = new TimeSeries("Series", Month.class); assertEquals(-1, series.getIndex(new Month(1, 2003))); series.add(new Month(1, 2003), 45.0); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(-2, series.getIndex(new Month(2, 2003))); series.add(new Month(3, 2003), 55.0); assertEquals(-1, series.getIndex(new Month(12, 2002))); assertEquals(0, series.getIndex(new Month(1, 2003))); assertEquals(-2, series.getIndex(new Month(2, 2003))); assertEquals(1, series.getIndex(new Month(3, 2003))); assertEquals(-3, series.getIndex(new Month(4, 2003))); } /** * Some checks for the getDataItem(int) method. */ public void testGetDataItem1() { TimeSeries series = new TimeSeries("S", Year.class); // can't get anything yet...just an exception boolean pass = false; try { /*TimeSeriesDataItem item =*/ series.getDataItem(0); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); series.add(new Year(2006), 100.0); TimeSeriesDataItem item = series.getDataItem(0); assertEquals(new Year(2006), item.getPeriod()); pass = false; try { /*item = */series.getDataItem(-1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); pass = false; try { /*item = */series.getDataItem(1); } catch (IndexOutOfBoundsException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getDataItem(RegularTimePeriod) method. */ public void testGetDataItem2() { TimeSeries series = new TimeSeries("S", Year.class); assertNull(series.getDataItem(new Year(2006))); // try a null argument boolean pass = false; try { /* TimeSeriesDataItem item = */ series.getDataItem(null); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the removeAgedItems() method. */ public void testRemoveAgedItems() { TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with one item series.add(new Year(1999), 1.0); series.setMaximumItemAge(0); this.gotSeriesChangeEvent = false; series.removeAgedItems(true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test series with two items series.setMaximumItemAge(10); series.add(new Year(2001), 2.0); this.gotSeriesChangeEvent = false; series.setMaximumItemAge(2); assertEquals(2, series.getItemCount()); assertEquals(0, series.getIndex(new Year(1999))); assertFalse(this.gotSeriesChangeEvent); series.setMaximumItemAge(1); assertEquals(1, series.getItemCount()); assertEquals(0, series.getIndex(new Year(2001))); assertTrue(this.gotSeriesChangeEvent); } /** * Some checks for the removeAgedItems(long, boolean) method. */ public void testRemoveAgedItems2() { long y2006 = 1157087372534L; // milliseconds somewhere in 2006 TimeSeries series = new TimeSeries("Test Series", Year.class); series.addChangeListener(this); assertEquals(Long.MAX_VALUE, series.getMaximumItemAge()); assertEquals(Integer.MAX_VALUE, series.getMaximumItemCount()); this.gotSeriesChangeEvent = false; // test empty series series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); // test a series with 1 item series.add(new Year(2004), 1.0); series.setMaximumItemAge(1); this.gotSeriesChangeEvent = false; series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(1, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(0, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); // test a series with two items series.setMaximumItemAge(2); series.add(new Year(2003), 1.0); series.add(new Year(2005), 2.0); assertEquals(2, series.getItemCount()); this.gotSeriesChangeEvent = false; assertEquals(2, series.getItemCount()); series.removeAgedItems(new Year(2005).getMiddleMillisecond(), true); assertEquals(2, series.getItemCount()); assertFalse(this.gotSeriesChangeEvent); series.removeAgedItems(y2006, true); assertEquals(1, series.getItemCount()); assertTrue(this.gotSeriesChangeEvent); } /** * Some simple checks for the hashCode() method. */ public void testHashCode() { TimeSeries s1 = new TimeSeries("Test"); TimeSeries s2 = new TimeSeries("Test"); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(1, 1, 2007), 500.0); s2.add(new Day(1, 1, 2007), 500.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(2, 1, 2007), null); s2.add(new Day(2, 1, 2007), null); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(5, 1, 2007), 111.0); s2.add(new Day(5, 1, 2007), 111.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); s1.add(new Day(9, 1, 2007), 1.0); s2.add(new Day(9, 1, 2007), 1.0); assertEquals(s1, s2); assertEquals(s1.hashCode(), s2.hashCode()); } }
public void testFormatErrorSpaceEndOfLine1() throws Exception { JSError error = JSError.make("javascript/complex.js", 1, 10, FOO_TYPE); LightweightMessageFormatter formatter = formatter("assert (1;"); assertEquals("javascript/complex.js:1: ERROR - error description here\n" + "assert (1;\n" + " ^\n", formatter.formatError(error)); }
com.google.javascript.jscomp.LightweightMessageFormatterTest::testFormatErrorSpaceEndOfLine1
test/com/google/javascript/jscomp/LightweightMessageFormatterTest.java
93
test/com/google/javascript/jscomp/LightweightMessageFormatterTest.java
testFormatErrorSpaceEndOfLine1
/* * 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 static com.google.javascript.jscomp.LightweightMessageFormatter.LineNumberingFormatter; import com.google.javascript.rhino.Node; import junit.framework.TestCase; public class LightweightMessageFormatterTest extends TestCase { private static final DiagnosticType FOO_TYPE = DiagnosticType.error("TEST_FOO", "error description here"); public void testNull() throws Exception { assertNull(format(null)); } public void testOneLineRegion() throws Exception { assertEquals(" 5| hello world", format(region(5, 5, "hello world"))); } public void testTwoLineRegion() throws Exception { assertEquals(" 5| hello world\n" + " 6| foo bar", format(region(5, 6, "hello world\nfoo bar"))); } public void testThreeLineRegionAcrossNumberRange() throws Exception { String region = format(region(9, 11, "hello world\nfoo bar\nanother one")); assertEquals(" 9| hello world\n" + " 10| foo bar\n" + " 11| another one", region); } public void testThreeLineRegionEmptyLine() throws Exception { String region = format(region(7, 9, "hello world\n\nanother one")); assertEquals(" 7| hello world\n" + " 8| \n" + " 9| another one", region); } public void testOnlyOneEmptyLine() throws Exception { assertNull(format(region(7, 7, ""))); } public void testTwoEmptyLines() throws Exception { assertEquals(" 7| ", format(region(7, 8, "\n"))); } public void testThreeLineRemoveLastEmptyLine() throws Exception { String region = format(region(7, 9, "hello world\nfoobar\n")); assertEquals(" 7| hello world\n" + " 8| foobar", region); } public void testFormatErrorSpaces() throws Exception { JSError error = JSError.make("javascript/complex.js", Node.newString("foobar", 5, 8), FOO_TYPE); LightweightMessageFormatter formatter = formatter(" if (foobar) {"); assertEquals("javascript/complex.js:5: ERROR - error description here\n" + " if (foobar) {\n" + " ^\n", formatter.formatError(error)); } public void testFormatErrorTabs() throws Exception { JSError error = JSError.make("javascript/complex.js", Node.newString("foobar", 5, 6), FOO_TYPE); LightweightMessageFormatter formatter = formatter("\t\tif (foobar) {"); assertEquals("javascript/complex.js:5: ERROR - error description here\n" + "\t\tif (foobar) {\n" + "\t\t ^\n", formatter.formatError(error)); } public void testFormatErrorSpaceEndOfLine1() throws Exception { JSError error = JSError.make("javascript/complex.js", 1, 10, FOO_TYPE); LightweightMessageFormatter formatter = formatter("assert (1;"); assertEquals("javascript/complex.js:1: ERROR - error description here\n" + "assert (1;\n" + " ^\n", formatter.formatError(error)); } public void testFormatErrorSpaceEndOfLine2() throws Exception { JSError error = JSError.make("javascript/complex.js", 6, 7, FOO_TYPE); LightweightMessageFormatter formatter = formatter("if (foo"); assertEquals("javascript/complex.js:6: ERROR - error description here\n" + "if (foo\n" + " ^\n", formatter.formatError(error)); } private LightweightMessageFormatter formatter(String string) { return new LightweightMessageFormatter(source(string)); } private SourceExcerptProvider source(final String source) { return new SourceExcerptProvider() { public String getSourceLine(String sourceName, int lineNumber) { return source; } public Region getSourceRegion(String sourceName, int lineNumber) { throw new UnsupportedOperationException(); } }; } private String format(Region region) { return new LineNumberingFormatter().formatRegion(region); } private Region region(final int startLine, final int endLine, final String source) { return new SimpleRegion(startLine, endLine, source); } }
// You are a professional Java test case writer, please create a test case named `testFormatErrorSpaceEndOfLine1` for the issue `Closure-487`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-487 // // ## Issue-Title: // Column-indicating caret is sometimes not in error output // // ## Issue-Description: // For some reason, the caret doesn't always show up in the output when there are errors. // // When test.js looks like this: // // // >alert(1; // // // , the output is this: // // // >java -jar compiler.jar --js test.js // test.js:1: ERROR - Parse error. missing ) after argument list // // 1 error(s), 0 warning(s) // // // However, when test.js looks like this (notice the line break after the semicolon): // // // >alert(1; // > // // // , the output is this: // // // >java -jar compiler.jar --js test.js // test.js:1: ERROR - Parse error. missing ) after argument list // alert(1; // ^ // // 1 error(s), 0 warning(s) // // // That's the simplest reproduction of the problem that I could come up with, but I just encountered the problem in a file with ~100 LOC in it. This is the first time I believe I've run into the problem, but when it happens, my error parser fails and it becomes a pain to track down the raw output to find the actual problem. // // Tested against r1171, committed 6/10 08:06. The problem is present going back to at least r1000, so this isn't a new issue. // // public void testFormatErrorSpaceEndOfLine1() throws Exception {
93
62
86
test/com/google/javascript/jscomp/LightweightMessageFormatterTest.java
test
```markdown ## Issue-ID: Closure-487 ## Issue-Title: Column-indicating caret is sometimes not in error output ## Issue-Description: For some reason, the caret doesn't always show up in the output when there are errors. When test.js looks like this: >alert(1; , the output is this: >java -jar compiler.jar --js test.js test.js:1: ERROR - Parse error. missing ) after argument list 1 error(s), 0 warning(s) However, when test.js looks like this (notice the line break after the semicolon): >alert(1; > , the output is this: >java -jar compiler.jar --js test.js test.js:1: ERROR - Parse error. missing ) after argument list alert(1; ^ 1 error(s), 0 warning(s) That's the simplest reproduction of the problem that I could come up with, but I just encountered the problem in a file with ~100 LOC in it. This is the first time I believe I've run into the problem, but when it happens, my error parser fails and it becomes a pain to track down the raw output to find the actual problem. Tested against r1171, committed 6/10 08:06. The problem is present going back to at least r1000, so this isn't a new issue. ``` You are a professional Java test case writer, please create a test case named `testFormatErrorSpaceEndOfLine1` for the issue `Closure-487`, utilizing the provided issue report information and the following function signature. ```java public void testFormatErrorSpaceEndOfLine1() throws Exception { ```
86
[ "com.google.javascript.jscomp.LightweightMessageFormatter" ]
d749060db16640f7a2f2f590c14d19cd9ae715a727851eda6fdbd34f52826ed6
public void testFormatErrorSpaceEndOfLine1() throws Exception
// You are a professional Java test case writer, please create a test case named `testFormatErrorSpaceEndOfLine1` for the issue `Closure-487`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-487 // // ## Issue-Title: // Column-indicating caret is sometimes not in error output // // ## Issue-Description: // For some reason, the caret doesn't always show up in the output when there are errors. // // When test.js looks like this: // // // >alert(1; // // // , the output is this: // // // >java -jar compiler.jar --js test.js // test.js:1: ERROR - Parse error. missing ) after argument list // // 1 error(s), 0 warning(s) // // // However, when test.js looks like this (notice the line break after the semicolon): // // // >alert(1; // > // // // , the output is this: // // // >java -jar compiler.jar --js test.js // test.js:1: ERROR - Parse error. missing ) after argument list // alert(1; // ^ // // 1 error(s), 0 warning(s) // // // That's the simplest reproduction of the problem that I could come up with, but I just encountered the problem in a file with ~100 LOC in it. This is the first time I believe I've run into the problem, but when it happens, my error parser fails and it becomes a pain to track down the raw output to find the actual problem. // // Tested against r1171, committed 6/10 08:06. The problem is present going back to at least r1000, so this isn't a new issue. // //
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 static com.google.javascript.jscomp.LightweightMessageFormatter.LineNumberingFormatter; import com.google.javascript.rhino.Node; import junit.framework.TestCase; public class LightweightMessageFormatterTest extends TestCase { private static final DiagnosticType FOO_TYPE = DiagnosticType.error("TEST_FOO", "error description here"); public void testNull() throws Exception { assertNull(format(null)); } public void testOneLineRegion() throws Exception { assertEquals(" 5| hello world", format(region(5, 5, "hello world"))); } public void testTwoLineRegion() throws Exception { assertEquals(" 5| hello world\n" + " 6| foo bar", format(region(5, 6, "hello world\nfoo bar"))); } public void testThreeLineRegionAcrossNumberRange() throws Exception { String region = format(region(9, 11, "hello world\nfoo bar\nanother one")); assertEquals(" 9| hello world\n" + " 10| foo bar\n" + " 11| another one", region); } public void testThreeLineRegionEmptyLine() throws Exception { String region = format(region(7, 9, "hello world\n\nanother one")); assertEquals(" 7| hello world\n" + " 8| \n" + " 9| another one", region); } public void testOnlyOneEmptyLine() throws Exception { assertNull(format(region(7, 7, ""))); } public void testTwoEmptyLines() throws Exception { assertEquals(" 7| ", format(region(7, 8, "\n"))); } public void testThreeLineRemoveLastEmptyLine() throws Exception { String region = format(region(7, 9, "hello world\nfoobar\n")); assertEquals(" 7| hello world\n" + " 8| foobar", region); } public void testFormatErrorSpaces() throws Exception { JSError error = JSError.make("javascript/complex.js", Node.newString("foobar", 5, 8), FOO_TYPE); LightweightMessageFormatter formatter = formatter(" if (foobar) {"); assertEquals("javascript/complex.js:5: ERROR - error description here\n" + " if (foobar) {\n" + " ^\n", formatter.formatError(error)); } public void testFormatErrorTabs() throws Exception { JSError error = JSError.make("javascript/complex.js", Node.newString("foobar", 5, 6), FOO_TYPE); LightweightMessageFormatter formatter = formatter("\t\tif (foobar) {"); assertEquals("javascript/complex.js:5: ERROR - error description here\n" + "\t\tif (foobar) {\n" + "\t\t ^\n", formatter.formatError(error)); } public void testFormatErrorSpaceEndOfLine1() throws Exception { JSError error = JSError.make("javascript/complex.js", 1, 10, FOO_TYPE); LightweightMessageFormatter formatter = formatter("assert (1;"); assertEquals("javascript/complex.js:1: ERROR - error description here\n" + "assert (1;\n" + " ^\n", formatter.formatError(error)); } public void testFormatErrorSpaceEndOfLine2() throws Exception { JSError error = JSError.make("javascript/complex.js", 6, 7, FOO_TYPE); LightweightMessageFormatter formatter = formatter("if (foo"); assertEquals("javascript/complex.js:6: ERROR - error description here\n" + "if (foo\n" + " ^\n", formatter.formatError(error)); } private LightweightMessageFormatter formatter(String string) { return new LightweightMessageFormatter(source(string)); } private SourceExcerptProvider source(final String source) { return new SourceExcerptProvider() { public String getSourceLine(String sourceName, int lineNumber) { return source; } public Region getSourceRegion(String sourceName, int lineNumber) { throw new UnsupportedOperationException(); } }; } private String format(Region region) { return new LineNumberingFormatter().formatRegion(region); } private Region region(final int startLine, final int endLine, final String source) { return new SimpleRegion(startLine, endLine, source); } }
public void testNoUndeclaredVarWhenUsingClosurePass() { enableClosurePass(); // We don't want to get goog as an undeclared var here. test("goog.require('namespace.Class1');\n", null, ProcessClosurePrimitives.MISSING_PROVIDE_ERROR); }
com.google.javascript.jscomp.VarCheckTest::testNoUndeclaredVarWhenUsingClosurePass
test/com/google/javascript/jscomp/VarCheckTest.java
372
test/com/google/javascript/jscomp/VarCheckTest.java
testNoUndeclaredVarWhenUsingClosurePass
/* * Copyright 2005 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 static com.google.javascript.jscomp.VarCheck.VAR_MULTIPLY_DECLARED_ERROR; import com.google.common.collect.Lists; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.rhino.Node; public class VarCheckTest extends CompilerTestCase { private static final String EXTERNS = "var window; function alert() {}"; private CheckLevel strictModuleDepErrorLevel; private boolean sanityCheck = false; private CheckLevel externValidationErrorLevel; private boolean declarationCheck; public VarCheckTest() { super(EXTERNS); } @Override protected void setUp() throws Exception { super.setUp(); // Setup value set by individual tests to the appropriate defaults. super.allowExternsChanges(true); super.enableAstValidation(true); strictModuleDepErrorLevel = CheckLevel.OFF; externValidationErrorLevel = null; sanityCheck = false; declarationCheck = false; } @Override protected CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.setWarningLevel(DiagnosticGroups.STRICT_MODULE_DEP_CHECK, strictModuleDepErrorLevel); if (externValidationErrorLevel != null) { options.setWarningLevel(DiagnosticGroups.EXTERNS_VALIDATION, externValidationErrorLevel); } return options; } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { new VarCheck(compiler, sanityCheck).process(externs, root); if (sanityCheck == false && !compiler.hasErrors()) { new VarCheck(compiler, true).process(externs, root); } if (declarationCheck) { new VariableTestCheck(compiler).process(externs, root); } } }; } @Override protected int getNumRepetitions() { // Because we synthesize externs, the second pass won't emit a warning. return 1; } public void testBreak() { testSame("a: while(1) break a;"); } public void testContinue() { testSame("a: while(1) continue a;"); } public void testReferencedVarNotDefined() { test("x = 0;", null, VarCheck.UNDEFINED_VAR_ERROR); } public void testReferencedVarDefined1() { testSame("var x, y; x=1;"); } public void testReferencedVarDefined2() { testSame("var x; function y() {x=1;}"); } public void testReferencedVarsExternallyDefined() { testSame("var x = window; alert(x);"); } public void testMultiplyDeclaredVars1() { test("var x = 1; var x = 2;", null, VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testMultiplyDeclaredVars2() { test("var y; try { y=1 } catch (x) {}" + "try { y=1 } catch (x) {}", "var y;try{y=1}catch(x){}try{y=1}catch(x){}"); } public void testMultiplyDeclaredVars3() { test("try { var x = 1; x *=2; } catch (x) {}", null, VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testMultiplyDeclaredVars4() { testSame("x;", "var x = 1; var x = 2;", VarCheck.VAR_MULTIPLY_DECLARED_ERROR, true); } public void testVarReferenceInExterns() { testSame("asdf;", "var asdf;", VarCheck.NAME_REFERENCE_IN_EXTERNS_ERROR); } public void testCallInExterns() { testSame("yz();", "function yz() {}", VarCheck.NAME_REFERENCE_IN_EXTERNS_ERROR); } public void testPropReferenceInExterns1() { testSame("asdf.foo;", "var asdf;", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); } public void testPropReferenceInExterns2() { testSame("asdf.foo;", "", VarCheck.UNDEFINED_VAR_ERROR, true); } public void testPropReferenceInExterns3() { testSame("asdf.foo;", "var asdf;", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); externValidationErrorLevel = CheckLevel.ERROR; test( "asdf.foo;", "var asdf;", "", VarCheck.UNDEFINED_EXTERN_VAR_ERROR, null); externValidationErrorLevel = CheckLevel.OFF; test("asdf.foo;", "var asdf;", "var asdf;", null, null); } public void testVarInWithBlock() { test("var a = {b:5}; with (a){b;}", null, VarCheck.UNDEFINED_VAR_ERROR); } public void testValidFunctionExpr() { testSame("(function() {});"); } public void testRecursiveFunction() { testSame("(function a() { return a(); })();"); } public void testRecursiveFunction2() { testSame("var a = 3; (function a() { return a(); })();"); } public void testLegalVarReferenceBetweenModules() { testDependentModules("var x = 10;", "var y = x++;", null); } public void testMissingModuleDependencyDefault() { testIndependentModules("var x = 10;", "var y = x++;", null, VarCheck.MISSING_MODULE_DEP_ERROR); } public void testViolatedModuleDependencyDefault() { testDependentModules("var y = x++;", "var x = 10;", VarCheck.VIOLATED_MODULE_DEP_ERROR); } public void testMissingModuleDependencySkipNonStrict() { sanityCheck = true; testIndependentModules("var x = 10;", "var y = x++;", null, null); } public void testViolatedModuleDependencySkipNonStrict() { sanityCheck = true; testDependentModules("var y = x++;", "var x = 10;", null); } public void testMissingModuleDependencySkipNonStrictNotPromoted() { sanityCheck = true; strictModuleDepErrorLevel = CheckLevel.ERROR; testIndependentModules("var x = 10;", "var y = x++;", null, null); } public void testViolatedModuleDependencyNonStrictNotPromoted() { sanityCheck = true; strictModuleDepErrorLevel = CheckLevel.ERROR; testDependentModules("var y = x++;", "var x = 10;", null); } public void testDependentStrictModuleDependencyCheck() { strictModuleDepErrorLevel = CheckLevel.ERROR; testDependentModules("var f = function() {return new B();};", "var B = function() {}", VarCheck.STRICT_MODULE_DEP_ERROR); } public void testIndependentStrictModuleDependencyCheck() { strictModuleDepErrorLevel = CheckLevel.ERROR; testIndependentModules("var f = function() {return new B();};", "var B = function() {}", VarCheck.STRICT_MODULE_DEP_ERROR, null); } public void testStarStrictModuleDependencyCheck() { strictModuleDepErrorLevel = CheckLevel.WARNING; testSame(createModuleStar("function a() {}", "function b() { a(); c(); }", "function c() { a(); }"), VarCheck.STRICT_MODULE_DEP_ERROR); } public void testForwardVarReferenceInLocalScope1() { testDependentModules("var x = 10; function a() {y++;}", "var y = 11; a();", null); } public void testForwardVarReferenceInLocalScope2() { // It would be nice if this pass could use a call graph to flag this case // as an error, but it currently doesn't. testDependentModules("var x = 10; function a() {y++;} a();", "var y = 11;", null); } private void testDependentModules(String code1, String code2, DiagnosticType error) { testDependentModules(code1, code2, error, null); } private void testDependentModules(String code1, String code2, DiagnosticType error, DiagnosticType warning) { testTwoModules(code1, code2, true, error, warning); } private void testIndependentModules(String code1, String code2, DiagnosticType error, DiagnosticType warning) { testTwoModules(code1, code2, false, error, warning); } private void testTwoModules(String code1, String code2, boolean m2DependsOnm1, DiagnosticType error, DiagnosticType warning) { JSModule m1 = new JSModule("m1"); m1.add(SourceFile.fromCode("input1", code1)); JSModule m2 = new JSModule("m2"); m2.add(SourceFile.fromCode("input2", code2)); if (m2DependsOnm1) { m2.addDependency(m1); } test(new JSModule[] { m1, m2 }, new String[] { code1, code2 }, error, warning); } ////////////////////////////////////////////////////////////////////////////// // Test synthesis of externs public void testSimple() { checkSynthesizedExtern("x", "var x;"); checkSynthesizedExtern("var x", ""); } public void testSimpleSanityCheck() { sanityCheck = true; try { checkSynthesizedExtern("x", ""); } catch (RuntimeException e) { assertTrue(e.getMessage().indexOf("Unexpected variable x") != -1); } } public void testParameter() { checkSynthesizedExtern("function f(x){}", ""); } public void testLocalVar() { checkSynthesizedExtern("function f(){x}", "var x"); } public void testTwoLocalVars() { checkSynthesizedExtern("function f(){x}function g() {x}", "var x"); } public void testInnerFunctionLocalVar() { checkSynthesizedExtern("function f(){function g() {x}}", "var x"); } public void testNoCreateVarsForLabels() { checkSynthesizedExtern("x:var y", ""); } public void testVariableInNormalCodeUsedInExterns1() { checkSynthesizedExtern( "x.foo;", "var x;", "var x; x.foo;"); } public void testVariableInNormalCodeUsedInExterns2() { checkSynthesizedExtern( "x;", "var x;", "var x; x;"); } public void testVariableInNormalCodeUsedInExterns3() { checkSynthesizedExtern( "x.foo;", "function x() {}", "var x; x.foo; "); } public void testVariableInNormalCodeUsedInExterns4() { checkSynthesizedExtern( "x;", "function x() {}", "var x; x; "); } public void testRedeclaration1() { String js = "var a; var a;"; test(js, null, VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testRedeclaration2() { String js = "var a; /** @suppress {duplicate} */ var a;"; testSame(js); } public void testRedeclaration3() { String js = " /** @suppress {duplicate} */ var a; var a; "; testSame(js); } public void testDuplicateVar() { test("/** @define {boolean} */ var DEF = false; var DEF = true;", null, VAR_MULTIPLY_DECLARED_ERROR); } public void testFunctionScopeArguments() { // A var declaration doesn't mask arguments testSame("function f() {var arguments}"); test("var f = function arguments() {}", null, VarCheck.VAR_ARGUMENTS_SHADOWED_ERROR); test("var f = function (arguments) {}", null, VarCheck.VAR_ARGUMENTS_SHADOWED_ERROR); test("function f() {try {} catch(arguments) {}}", null, VarCheck.VAR_ARGUMENTS_SHADOWED_ERROR); } public void testNoUndeclaredVarWhenUsingClosurePass() { enableClosurePass(); // We don't want to get goog as an undeclared var here. test("goog.require('namespace.Class1');\n", null, ProcessClosurePrimitives.MISSING_PROVIDE_ERROR); } private final static class VariableTestCheck implements CompilerPass { final AbstractCompiler compiler; VariableTestCheck(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { NodeTraversal.traverseRoots(compiler, Lists.newArrayList(externs, root), new AbstractPostOrderCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName() && !parent.isFunction() && !parent.isLabel()) { assertTrue("Variable " + n.getString() + " should have be declared", t.getScope().isDeclared(n.getString(), true)); } } }); } } public void checkSynthesizedExtern( String input, String expectedExtern) { checkSynthesizedExtern("", input, expectedExtern); } public void checkSynthesizedExtern( String extern, String input, String expectedExtern) { declarationCheck = !sanityCheck; testExternChanges(extern, input, expectedExtern); } }
// You are a professional Java test case writer, please create a test case named `testNoUndeclaredVarWhenUsingClosurePass` for the issue `Closure-1079`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1079 // // ## Issue-Title: // Bug in require calls processing // // ## Issue-Description: // The Problem // // ProcessClosurePrimitives pass has a bug in processRequireCall method. // The method processes goog.require calls. If a require symbol is invalid i.e is not provided anywhere, the method collects it for further error reporting. If the require symbol is valid, the method removes it from the ast. // // All invalid require calls must be left for further using/checking of the code! The related comment in the code confirms this. // // Nevertheless, the second condition (requiresLevel.isOn() -> see source code) is invalid and always causes removing of the requires when we want to check these requires. // // In any case, the method should not use the requiresLevel to decide if we need removing. The requiresLevel should be used to check if we need error reporting. // // The Solution // // Remove the condition. // Please see the attached patch. // // public void testNoUndeclaredVarWhenUsingClosurePass() {
372
113
367
test/com/google/javascript/jscomp/VarCheckTest.java
test
```markdown ## Issue-ID: Closure-1079 ## Issue-Title: Bug in require calls processing ## Issue-Description: The Problem ProcessClosurePrimitives pass has a bug in processRequireCall method. The method processes goog.require calls. If a require symbol is invalid i.e is not provided anywhere, the method collects it for further error reporting. If the require symbol is valid, the method removes it from the ast. All invalid require calls must be left for further using/checking of the code! The related comment in the code confirms this. Nevertheless, the second condition (requiresLevel.isOn() -> see source code) is invalid and always causes removing of the requires when we want to check these requires. In any case, the method should not use the requiresLevel to decide if we need removing. The requiresLevel should be used to check if we need error reporting. The Solution Remove the condition. Please see the attached patch. ``` You are a professional Java test case writer, please create a test case named `testNoUndeclaredVarWhenUsingClosurePass` for the issue `Closure-1079`, utilizing the provided issue report information and the following function signature. ```java public void testNoUndeclaredVarWhenUsingClosurePass() { ```
367
[ "com.google.javascript.jscomp.ProcessClosurePrimitives" ]
d772e11b423ed011df2dcee692e6074fd58891f571cedb0a7e4338c43a03c897
public void testNoUndeclaredVarWhenUsingClosurePass()
// You are a professional Java test case writer, please create a test case named `testNoUndeclaredVarWhenUsingClosurePass` for the issue `Closure-1079`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1079 // // ## Issue-Title: // Bug in require calls processing // // ## Issue-Description: // The Problem // // ProcessClosurePrimitives pass has a bug in processRequireCall method. // The method processes goog.require calls. If a require symbol is invalid i.e is not provided anywhere, the method collects it for further error reporting. If the require symbol is valid, the method removes it from the ast. // // All invalid require calls must be left for further using/checking of the code! The related comment in the code confirms this. // // Nevertheless, the second condition (requiresLevel.isOn() -> see source code) is invalid and always causes removing of the requires when we want to check these requires. // // In any case, the method should not use the requiresLevel to decide if we need removing. The requiresLevel should be used to check if we need error reporting. // // The Solution // // Remove the condition. // Please see the attached patch. // //
Closure
/* * Copyright 2005 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 static com.google.javascript.jscomp.VarCheck.VAR_MULTIPLY_DECLARED_ERROR; import com.google.common.collect.Lists; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.rhino.Node; public class VarCheckTest extends CompilerTestCase { private static final String EXTERNS = "var window; function alert() {}"; private CheckLevel strictModuleDepErrorLevel; private boolean sanityCheck = false; private CheckLevel externValidationErrorLevel; private boolean declarationCheck; public VarCheckTest() { super(EXTERNS); } @Override protected void setUp() throws Exception { super.setUp(); // Setup value set by individual tests to the appropriate defaults. super.allowExternsChanges(true); super.enableAstValidation(true); strictModuleDepErrorLevel = CheckLevel.OFF; externValidationErrorLevel = null; sanityCheck = false; declarationCheck = false; } @Override protected CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); options.setWarningLevel(DiagnosticGroups.STRICT_MODULE_DEP_CHECK, strictModuleDepErrorLevel); if (externValidationErrorLevel != null) { options.setWarningLevel(DiagnosticGroups.EXTERNS_VALIDATION, externValidationErrorLevel); } return options; } @Override protected CompilerPass getProcessor(final Compiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { new VarCheck(compiler, sanityCheck).process(externs, root); if (sanityCheck == false && !compiler.hasErrors()) { new VarCheck(compiler, true).process(externs, root); } if (declarationCheck) { new VariableTestCheck(compiler).process(externs, root); } } }; } @Override protected int getNumRepetitions() { // Because we synthesize externs, the second pass won't emit a warning. return 1; } public void testBreak() { testSame("a: while(1) break a;"); } public void testContinue() { testSame("a: while(1) continue a;"); } public void testReferencedVarNotDefined() { test("x = 0;", null, VarCheck.UNDEFINED_VAR_ERROR); } public void testReferencedVarDefined1() { testSame("var x, y; x=1;"); } public void testReferencedVarDefined2() { testSame("var x; function y() {x=1;}"); } public void testReferencedVarsExternallyDefined() { testSame("var x = window; alert(x);"); } public void testMultiplyDeclaredVars1() { test("var x = 1; var x = 2;", null, VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testMultiplyDeclaredVars2() { test("var y; try { y=1 } catch (x) {}" + "try { y=1 } catch (x) {}", "var y;try{y=1}catch(x){}try{y=1}catch(x){}"); } public void testMultiplyDeclaredVars3() { test("try { var x = 1; x *=2; } catch (x) {}", null, VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testMultiplyDeclaredVars4() { testSame("x;", "var x = 1; var x = 2;", VarCheck.VAR_MULTIPLY_DECLARED_ERROR, true); } public void testVarReferenceInExterns() { testSame("asdf;", "var asdf;", VarCheck.NAME_REFERENCE_IN_EXTERNS_ERROR); } public void testCallInExterns() { testSame("yz();", "function yz() {}", VarCheck.NAME_REFERENCE_IN_EXTERNS_ERROR); } public void testPropReferenceInExterns1() { testSame("asdf.foo;", "var asdf;", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); } public void testPropReferenceInExterns2() { testSame("asdf.foo;", "", VarCheck.UNDEFINED_VAR_ERROR, true); } public void testPropReferenceInExterns3() { testSame("asdf.foo;", "var asdf;", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); externValidationErrorLevel = CheckLevel.ERROR; test( "asdf.foo;", "var asdf;", "", VarCheck.UNDEFINED_EXTERN_VAR_ERROR, null); externValidationErrorLevel = CheckLevel.OFF; test("asdf.foo;", "var asdf;", "var asdf;", null, null); } public void testVarInWithBlock() { test("var a = {b:5}; with (a){b;}", null, VarCheck.UNDEFINED_VAR_ERROR); } public void testValidFunctionExpr() { testSame("(function() {});"); } public void testRecursiveFunction() { testSame("(function a() { return a(); })();"); } public void testRecursiveFunction2() { testSame("var a = 3; (function a() { return a(); })();"); } public void testLegalVarReferenceBetweenModules() { testDependentModules("var x = 10;", "var y = x++;", null); } public void testMissingModuleDependencyDefault() { testIndependentModules("var x = 10;", "var y = x++;", null, VarCheck.MISSING_MODULE_DEP_ERROR); } public void testViolatedModuleDependencyDefault() { testDependentModules("var y = x++;", "var x = 10;", VarCheck.VIOLATED_MODULE_DEP_ERROR); } public void testMissingModuleDependencySkipNonStrict() { sanityCheck = true; testIndependentModules("var x = 10;", "var y = x++;", null, null); } public void testViolatedModuleDependencySkipNonStrict() { sanityCheck = true; testDependentModules("var y = x++;", "var x = 10;", null); } public void testMissingModuleDependencySkipNonStrictNotPromoted() { sanityCheck = true; strictModuleDepErrorLevel = CheckLevel.ERROR; testIndependentModules("var x = 10;", "var y = x++;", null, null); } public void testViolatedModuleDependencyNonStrictNotPromoted() { sanityCheck = true; strictModuleDepErrorLevel = CheckLevel.ERROR; testDependentModules("var y = x++;", "var x = 10;", null); } public void testDependentStrictModuleDependencyCheck() { strictModuleDepErrorLevel = CheckLevel.ERROR; testDependentModules("var f = function() {return new B();};", "var B = function() {}", VarCheck.STRICT_MODULE_DEP_ERROR); } public void testIndependentStrictModuleDependencyCheck() { strictModuleDepErrorLevel = CheckLevel.ERROR; testIndependentModules("var f = function() {return new B();};", "var B = function() {}", VarCheck.STRICT_MODULE_DEP_ERROR, null); } public void testStarStrictModuleDependencyCheck() { strictModuleDepErrorLevel = CheckLevel.WARNING; testSame(createModuleStar("function a() {}", "function b() { a(); c(); }", "function c() { a(); }"), VarCheck.STRICT_MODULE_DEP_ERROR); } public void testForwardVarReferenceInLocalScope1() { testDependentModules("var x = 10; function a() {y++;}", "var y = 11; a();", null); } public void testForwardVarReferenceInLocalScope2() { // It would be nice if this pass could use a call graph to flag this case // as an error, but it currently doesn't. testDependentModules("var x = 10; function a() {y++;} a();", "var y = 11;", null); } private void testDependentModules(String code1, String code2, DiagnosticType error) { testDependentModules(code1, code2, error, null); } private void testDependentModules(String code1, String code2, DiagnosticType error, DiagnosticType warning) { testTwoModules(code1, code2, true, error, warning); } private void testIndependentModules(String code1, String code2, DiagnosticType error, DiagnosticType warning) { testTwoModules(code1, code2, false, error, warning); } private void testTwoModules(String code1, String code2, boolean m2DependsOnm1, DiagnosticType error, DiagnosticType warning) { JSModule m1 = new JSModule("m1"); m1.add(SourceFile.fromCode("input1", code1)); JSModule m2 = new JSModule("m2"); m2.add(SourceFile.fromCode("input2", code2)); if (m2DependsOnm1) { m2.addDependency(m1); } test(new JSModule[] { m1, m2 }, new String[] { code1, code2 }, error, warning); } ////////////////////////////////////////////////////////////////////////////// // Test synthesis of externs public void testSimple() { checkSynthesizedExtern("x", "var x;"); checkSynthesizedExtern("var x", ""); } public void testSimpleSanityCheck() { sanityCheck = true; try { checkSynthesizedExtern("x", ""); } catch (RuntimeException e) { assertTrue(e.getMessage().indexOf("Unexpected variable x") != -1); } } public void testParameter() { checkSynthesizedExtern("function f(x){}", ""); } public void testLocalVar() { checkSynthesizedExtern("function f(){x}", "var x"); } public void testTwoLocalVars() { checkSynthesizedExtern("function f(){x}function g() {x}", "var x"); } public void testInnerFunctionLocalVar() { checkSynthesizedExtern("function f(){function g() {x}}", "var x"); } public void testNoCreateVarsForLabels() { checkSynthesizedExtern("x:var y", ""); } public void testVariableInNormalCodeUsedInExterns1() { checkSynthesizedExtern( "x.foo;", "var x;", "var x; x.foo;"); } public void testVariableInNormalCodeUsedInExterns2() { checkSynthesizedExtern( "x;", "var x;", "var x; x;"); } public void testVariableInNormalCodeUsedInExterns3() { checkSynthesizedExtern( "x.foo;", "function x() {}", "var x; x.foo; "); } public void testVariableInNormalCodeUsedInExterns4() { checkSynthesizedExtern( "x;", "function x() {}", "var x; x; "); } public void testRedeclaration1() { String js = "var a; var a;"; test(js, null, VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testRedeclaration2() { String js = "var a; /** @suppress {duplicate} */ var a;"; testSame(js); } public void testRedeclaration3() { String js = " /** @suppress {duplicate} */ var a; var a; "; testSame(js); } public void testDuplicateVar() { test("/** @define {boolean} */ var DEF = false; var DEF = true;", null, VAR_MULTIPLY_DECLARED_ERROR); } public void testFunctionScopeArguments() { // A var declaration doesn't mask arguments testSame("function f() {var arguments}"); test("var f = function arguments() {}", null, VarCheck.VAR_ARGUMENTS_SHADOWED_ERROR); test("var f = function (arguments) {}", null, VarCheck.VAR_ARGUMENTS_SHADOWED_ERROR); test("function f() {try {} catch(arguments) {}}", null, VarCheck.VAR_ARGUMENTS_SHADOWED_ERROR); } public void testNoUndeclaredVarWhenUsingClosurePass() { enableClosurePass(); // We don't want to get goog as an undeclared var here. test("goog.require('namespace.Class1');\n", null, ProcessClosurePrimitives.MISSING_PROVIDE_ERROR); } private final static class VariableTestCheck implements CompilerPass { final AbstractCompiler compiler; VariableTestCheck(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { NodeTraversal.traverseRoots(compiler, Lists.newArrayList(externs, root), new AbstractPostOrderCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName() && !parent.isFunction() && !parent.isLabel()) { assertTrue("Variable " + n.getString() + " should have be declared", t.getScope().isDeclared(n.getString(), true)); } } }); } } public void checkSynthesizedExtern( String input, String expectedExtern) { checkSynthesizedExtern("", input, expectedExtern); } public void checkSynthesizedExtern( String extern, String input, String expectedExtern) { declarationCheck = !sanityCheck; testExternChanges(extern, input, expectedExtern); } }
@Test public void testMultiply() { test(field.newDfp("1").multiply(field.newDfp("1")), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #1"); test(field.newDfp("1").multiply(1), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #2"); test(field.newDfp("-1").multiply(field.newDfp("1")), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #3"); test(field.newDfp("-1").multiply(1), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #4"); // basic tests with integers test(field.newDfp("2").multiply(field.newDfp("3")), field.newDfp("6"), 0, "Multiply #5"); test(field.newDfp("2").multiply(3), field.newDfp("6"), 0, "Multiply #6"); test(field.newDfp("-2").multiply(field.newDfp("3")), field.newDfp("-6"), 0, "Multiply #7"); test(field.newDfp("-2").multiply(3), field.newDfp("-6"), 0, "Multiply #8"); test(field.newDfp("2").multiply(field.newDfp("-3")), field.newDfp("-6"), 0, "Multiply #9"); test(field.newDfp("-2").multiply(field.newDfp("-3")), field.newDfp("6"), 0, "Multiply #10"); //multiply by zero test(field.newDfp("-2").multiply(field.newDfp("0")), field.newDfp("-0"), 0, "Multiply #11"); test(field.newDfp("-2").multiply(0), field.newDfp("-0"), 0, "Multiply #12"); test(field.newDfp("2").multiply(field.newDfp("0")), field.newDfp("0"), 0, "Multiply #13"); test(field.newDfp("2").multiply(0), field.newDfp("0"), 0, "Multiply #14"); test(field.newDfp("2").multiply(pinf), pinf, 0, "Multiply #15"); test(field.newDfp("2").multiply(ninf), ninf, 0, "Multiply #16"); test(field.newDfp("-2").multiply(pinf), ninf, 0, "Multiply #17"); test(field.newDfp("-2").multiply(ninf), pinf, 0, "Multiply #18"); test(ninf.multiply(field.newDfp("-2")), pinf, 0, "Multiply #18.1"); test(field.newDfp("5e131071").multiply(2), pinf, DfpField.FLAG_OVERFLOW, "Multiply #19"); test(field.newDfp("5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("9.9999999999999950000e131071"), 0, "Multiply #20"); test(field.newDfp("-5e131071").multiply(2), ninf, DfpField.FLAG_OVERFLOW, "Multiply #22"); test(field.newDfp("-5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("-9.9999999999999950000e131071"), 0, "Multiply #23"); test(field.newDfp("1e-65539").multiply(field.newDfp("1e-65539")), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "Multiply #24"); test(field.newDfp("1").multiply(nan), nan, 0, "Multiply #25"); test(nan.multiply(field.newDfp("1")), nan, 0, "Multiply #26"); test(nan.multiply(pinf), nan, 0, "Multiply #27"); test(pinf.multiply(nan), nan, 0, "Multiply #27"); test(pinf.multiply(field.newDfp("0")), nan, DfpField.FLAG_INVALID, "Multiply #28"); test(field.newDfp("0").multiply(pinf), nan, DfpField.FLAG_INVALID, "Multiply #29"); test(pinf.multiply(pinf), pinf, 0, "Multiply #30"); test(ninf.multiply(pinf), ninf, 0, "Multiply #31"); test(pinf.multiply(ninf), ninf, 0, "Multiply #32"); test(ninf.multiply(ninf), pinf, 0, "Multiply #33"); test(pinf.multiply(1), pinf, 0, "Multiply #34"); test(pinf.multiply(0), nan, DfpField.FLAG_INVALID, "Multiply #35"); test(nan.multiply(1), nan, 0, "Multiply #36"); test(field.newDfp("1").multiply(10000), field.newDfp("10000"), 0, "Multiply #37"); test(field.newDfp("2").multiply(1000000), field.newDfp("2000000"), 0, "Multiply #38"); test(field.newDfp("1").multiply(-1), field.newDfp("-1"), 0, "Multiply #39"); }
org.apache.commons.math3.dfp.DfpTest::testMultiply
src/test/java/org/apache/commons/math3/dfp/DfpTest.java
919
src/test/java/org/apache/commons/math3/dfp/DfpTest.java
testMultiply
/* * 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.dfp; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DfpTest { private DfpField field; private Dfp pinf; private Dfp ninf; private Dfp nan; private Dfp snan; private Dfp qnan; @Before public void setUp() { // Some basic setup. Define some constants and clear the status flags field = new DfpField(20); pinf = field.newDfp("1").divide(field.newDfp("0")); ninf = field.newDfp("-1").divide(field.newDfp("0")); nan = field.newDfp("0").divide(field.newDfp("0")); snan = field.newDfp((byte)1, Dfp.SNAN); qnan = field.newDfp((byte)1, Dfp.QNAN); ninf.getField().clearIEEEFlags(); } @After public void tearDown() { field = null; pinf = null; ninf = null; nan = null; snan = null; qnan = null; } // Generic test function. Takes params x and y and tests them for // equality. Then checks the status flags against the flags argument. // If the test fail, it prints the desc string private void test(Dfp x, Dfp y, int flags, String desc) { boolean b = x.equals(y); if (!x.equals(y) && !x.unequal(y)) // NaNs involved b = (x.toString().equals(y.toString())); if (x.equals(field.newDfp("0"))) // distinguish +/- zero b = (b && (x.toString().equals(y.toString()))); b = (b && x.getField().getIEEEFlags() == flags); if (!b) Assert.assertTrue("assersion failed "+desc+" x = "+x.toString()+" flags = "+x.getField().getIEEEFlags(), b); x.getField().clearIEEEFlags(); } @Test public void testByteConstructor() { Assert.assertEquals("0.", new Dfp(field, (byte) 0).toString()); Assert.assertEquals("1.", new Dfp(field, (byte) 1).toString()); Assert.assertEquals("-1.", new Dfp(field, (byte) -1).toString()); Assert.assertEquals("-128.", new Dfp(field, Byte.MIN_VALUE).toString()); Assert.assertEquals("127.", new Dfp(field, Byte.MAX_VALUE).toString()); } @Test public void testIntConstructor() { Assert.assertEquals("0.", new Dfp(field, 0).toString()); Assert.assertEquals("1.", new Dfp(field, 1).toString()); Assert.assertEquals("-1.", new Dfp(field, -1).toString()); Assert.assertEquals("1234567890.", new Dfp(field, 1234567890).toString()); Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890).toString()); Assert.assertEquals("-2147483648.", new Dfp(field, Integer.MIN_VALUE).toString()); Assert.assertEquals("2147483647.", new Dfp(field, Integer.MAX_VALUE).toString()); } @Test public void testLongConstructor() { Assert.assertEquals("0.", new Dfp(field, 0l).toString()); Assert.assertEquals("1.", new Dfp(field, 1l).toString()); Assert.assertEquals("-1.", new Dfp(field, -1l).toString()); Assert.assertEquals("1234567890.", new Dfp(field, 1234567890l).toString()); Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890l).toString()); Assert.assertEquals("-9223372036854775808.", new Dfp(field, Long.MIN_VALUE).toString()); Assert.assertEquals("9223372036854775807.", new Dfp(field, Long.MAX_VALUE).toString()); } /* * Test addition */ @Test public void testAdd() { test(field.newDfp("1").add(field.newDfp("1")), // Basic tests 1+1 = 2 field.newDfp("2"), 0, "Add #1"); test(field.newDfp("1").add(field.newDfp("-1")), // 1 + (-1) = 0 field.newDfp("0"), 0, "Add #2"); test(field.newDfp("-1").add(field.newDfp("1")), // (-1) + 1 = 0 field.newDfp("0"), 0, "Add #3"); test(field.newDfp("-1").add(field.newDfp("-1")), // (-1) + (-1) = -2 field.newDfp("-2"), 0, "Add #4"); // rounding mode is round half even test(field.newDfp("1").add(field.newDfp("1e-16")), // rounding on add field.newDfp("1.0000000000000001"), 0, "Add #5"); test(field.newDfp("1").add(field.newDfp("1e-17")), // rounding on add field.newDfp("1"), DfpField.FLAG_INEXACT, "Add #6"); test(field.newDfp("0.90999999999999999999").add(field.newDfp("0.1")), // rounding on add field.newDfp("1.01"), DfpField.FLAG_INEXACT, "Add #7"); test(field.newDfp(".10000000000000005000").add(field.newDfp(".9")), // rounding on add field.newDfp("1."), DfpField.FLAG_INEXACT, "Add #8"); test(field.newDfp(".10000000000000015000").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000002"), DfpField.FLAG_INEXACT, "Add #9"); test(field.newDfp(".10000000000000014999").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000001"), DfpField.FLAG_INEXACT, "Add #10"); test(field.newDfp(".10000000000000015001").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000002"), DfpField.FLAG_INEXACT, "Add #11"); test(field.newDfp(".11111111111111111111").add(field.newDfp("11.1111111111111111")), // rounding on add field.newDfp("11.22222222222222222222"), DfpField.FLAG_INEXACT, "Add #12"); test(field.newDfp(".11111111111111111111").add(field.newDfp("1111111111111111.1111")), // rounding on add field.newDfp("1111111111111111.2222"), DfpField.FLAG_INEXACT, "Add #13"); test(field.newDfp(".11111111111111111111").add(field.newDfp("11111111111111111111")), // rounding on add field.newDfp("11111111111111111111"), DfpField.FLAG_INEXACT, "Add #14"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("-1e131052")), // overflow on add field.newDfp("9.9999999999999999998e131071"), 0, "Add #15"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("1e131052")), // overflow on add pinf, DfpField.FLAG_OVERFLOW, "Add #16"); test(field.newDfp("-9.9999999999999999999e131071").add(field.newDfp("-1e131052")), // overflow on add ninf, DfpField.FLAG_OVERFLOW, "Add #17"); test(field.newDfp("-9.9999999999999999999e131071").add(field.newDfp("1e131052")), // overflow on add field.newDfp("-9.9999999999999999998e131071"), 0, "Add #18"); test(field.newDfp("1e-131072").add(field.newDfp("1e-131072")), // underflow on add field.newDfp("2e-131072"), 0, "Add #19"); test(field.newDfp("1.0000000000000001e-131057").add(field.newDfp("-1e-131057")), // underflow on add field.newDfp("1e-131073"), DfpField.FLAG_UNDERFLOW, "Add #20"); test(field.newDfp("1.1e-131072").add(field.newDfp("-1e-131072")), // underflow on add field.newDfp("1e-131073"), DfpField.FLAG_UNDERFLOW, "Add #21"); test(field.newDfp("1.0000000000000001e-131072").add(field.newDfp("-1e-131072")), // underflow on add field.newDfp("1e-131088"), DfpField.FLAG_UNDERFLOW, "Add #22"); test(field.newDfp("1.0000000000000001e-131078").add(field.newDfp("-1e-131078")), // underflow on add field.newDfp("0"), DfpField.FLAG_UNDERFLOW, "Add #23"); test(field.newDfp("1.0").add(field.newDfp("-1e-20")), // loss of precision on alignment? field.newDfp("0.99999999999999999999"), 0, "Add #23.1"); test(field.newDfp("-0.99999999999999999999").add(field.newDfp("1")), // proper normalization? field.newDfp("0.00000000000000000001"), 0, "Add #23.2"); test(field.newDfp("1").add(field.newDfp("0")), // adding zeros field.newDfp("1"), 0, "Add #24"); test(field.newDfp("0").add(field.newDfp("0")), // adding zeros field.newDfp("0"), 0, "Add #25"); test(field.newDfp("-0").add(field.newDfp("0")), // adding zeros field.newDfp("0"), 0, "Add #26"); test(field.newDfp("0").add(field.newDfp("-0")), // adding zeros field.newDfp("0"), 0, "Add #27"); test(field.newDfp("-0").add(field.newDfp("-0")), // adding zeros field.newDfp("-0"), 0, "Add #28"); test(field.newDfp("1e-20").add(field.newDfp("0")), // adding zeros field.newDfp("1e-20"), 0, "Add #29"); test(field.newDfp("1e-40").add(field.newDfp("0")), // adding zeros field.newDfp("1e-40"), 0, "Add #30"); test(pinf.add(ninf), // adding infinities nan, DfpField.FLAG_INVALID, "Add #31"); test(ninf.add(pinf), // adding infinities nan, DfpField.FLAG_INVALID, "Add #32"); test(ninf.add(ninf), // adding infinities ninf, 0, "Add #33"); test(pinf.add(pinf), // adding infinities pinf, 0, "Add #34"); test(pinf.add(field.newDfp("0")), // adding infinities pinf, 0, "Add #35"); test(pinf.add(field.newDfp("-1e131071")), // adding infinities pinf, 0, "Add #36"); test(pinf.add(field.newDfp("1e131071")), // adding infinities pinf, 0, "Add #37"); test(field.newDfp("0").add(pinf), // adding infinities pinf, 0, "Add #38"); test(field.newDfp("-1e131071").add(pinf), // adding infinities pinf, 0, "Add #39"); test(field.newDfp("1e131071").add(pinf), // adding infinities pinf, 0, "Add #40"); test(ninf.add(field.newDfp("0")), // adding infinities ninf, 0, "Add #41"); test(ninf.add(field.newDfp("-1e131071")), // adding infinities ninf, 0, "Add #42"); test(ninf.add(field.newDfp("1e131071")), // adding infinities ninf, 0, "Add #43"); test(field.newDfp("0").add(ninf), // adding infinities ninf, 0, "Add #44"); test(field.newDfp("-1e131071").add(ninf), // adding infinities ninf, 0, "Add #45"); test(field.newDfp("1e131071").add(ninf), // adding infinities ninf, 0, "Add #46"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("5e131051")), // overflow pinf, DfpField.FLAG_OVERFLOW, "Add #47"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("4.9999999999999999999e131051")), // overflow field.newDfp("9.9999999999999999999e131071"), DfpField.FLAG_INEXACT, "Add #48"); test(nan.add(field.newDfp("1")), nan, 0, "Add #49"); test(field.newDfp("1").add(nan), nan, 0, "Add #50"); test(field.newDfp("12345678123456781234").add(field.newDfp("0.12345678123456781234")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #51"); test(field.newDfp("12345678123456781234").add(field.newDfp("123.45678123456781234")), field.newDfp("12345678123456781357"), DfpField.FLAG_INEXACT, "Add #52"); test(field.newDfp("123.45678123456781234").add(field.newDfp("12345678123456781234")), field.newDfp("12345678123456781357"), DfpField.FLAG_INEXACT, "Add #53"); test(field.newDfp("12345678123456781234").add(field.newDfp(".00001234567812345678")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #54"); test(field.newDfp("12345678123456781234").add(field.newDfp(".00000000123456781234")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #55"); test(field.newDfp("-0").add(field.newDfp("-0")), field.newDfp("-0"), 0, "Add #56"); test(field.newDfp("0").add(field.newDfp("-0")), field.newDfp("0"), 0, "Add #57"); test(field.newDfp("-0").add(field.newDfp("0")), field.newDfp("0"), 0, "Add #58"); test(field.newDfp("0").add(field.newDfp("0")), field.newDfp("0"), 0, "Add #59"); } //////////////////////////////////////////////////////////////////////////////////////////////////////// // Test comparisons // utility function to help test comparisons private void cmptst(Dfp a, Dfp b, String op, boolean result, double num) { if (op == "equal") if (a.equals(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "unequal") if (a.unequal(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "lessThan") if (a.lessThan(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "greaterThan") if (a.greaterThan(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); } @Test public void testCompare() { // test equal() comparison // check zero vs. zero field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("0"), "equal", true, 1); // 0 == 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "equal", true, 2); // 0 == -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "equal", true, 3); // -0 == -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "equal", true, 4); // -0 == 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "equal", false, 5); // 0 == 1 cmptst(field.newDfp("1"), field.newDfp("0"), "equal", false, 6); // 1 == 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "equal", false, 7); // -1 == 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "equal", false, 8); // 0 == -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "equal", false, 9); // 0 == 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "equal", false, 10); // 0 == 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "equal", false, 11); // 0 == 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "equal", false, 12); // 0 == pinf cmptst(field.newDfp("0"), ninf, "equal", false, 13); // 0 == ninf cmptst(field.newDfp("-0"), pinf, "equal", false, 14); // -0 == pinf cmptst(field.newDfp("-0"), ninf, "equal", false, 15); // -0 == ninf cmptst(pinf, field.newDfp("0"), "equal", false, 16); // pinf == 0 cmptst(ninf, field.newDfp("0"), "equal", false, 17); // ninf == 0 cmptst(pinf, field.newDfp("-0"), "equal", false, 18); // pinf == -0 cmptst(ninf, field.newDfp("-0"), "equal", false, 19); // ninf == -0 cmptst(ninf, pinf, "equal", false, 19.10); // ninf == pinf cmptst(pinf, ninf, "equal", false, 19.11); // pinf == ninf cmptst(pinf, pinf, "equal", true, 19.12); // pinf == pinf cmptst(ninf, ninf, "equal", true, 19.13); // ninf == ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "equal", true, 20); // 1 == 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "equal", false, 21); // 1 == -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "equal", true, 22); // -1 == -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "equal", false, 23); // 1 == 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 == 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "equal", false, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "equal", true, 25); // check some nans -- nans shouldnt equal anything cmptst(snan, snan, "equal", false, 27); cmptst(qnan, qnan, "equal", false, 28); cmptst(snan, qnan, "equal", false, 29); cmptst(qnan, snan, "equal", false, 30); cmptst(qnan, field.newDfp("0"), "equal", false, 31); cmptst(snan, field.newDfp("0"), "equal", false, 32); cmptst(field.newDfp("0"), snan, "equal", false, 33); cmptst(field.newDfp("0"), qnan, "equal", false, 34); cmptst(qnan, pinf, "equal", false, 35); cmptst(snan, pinf, "equal", false, 36); cmptst(pinf, snan, "equal", false, 37); cmptst(pinf, qnan, "equal", false, 38); cmptst(qnan, ninf, "equal", false, 39); cmptst(snan, ninf, "equal", false, 40); cmptst(ninf, snan, "equal", false, 41); cmptst(ninf, qnan, "equal", false, 42); cmptst(qnan, field.newDfp("-1"), "equal", false, 43); cmptst(snan, field.newDfp("-1"), "equal", false, 44); cmptst(field.newDfp("-1"), snan, "equal", false, 45); cmptst(field.newDfp("-1"), qnan, "equal", false, 46); cmptst(qnan, field.newDfp("1"), "equal", false, 47); cmptst(snan, field.newDfp("1"), "equal", false, 48); cmptst(field.newDfp("1"), snan, "equal", false, 49); cmptst(field.newDfp("1"), qnan, "equal", false, 50); cmptst(snan.negate(), snan, "equal", false, 51); cmptst(qnan.negate(), qnan, "equal", false, 52); // // Tests for un equal -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "unequal", false, 1); // 0 == 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "unequal", false, 2); // 0 == -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "unequal", false, 3); // -0 == -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "unequal", false, 4); // -0 == 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "unequal", true, 5); // 0 == 1 cmptst(field.newDfp("1"), field.newDfp("0"), "unequal", true, 6); // 1 == 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "unequal", true, 7); // -1 == 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "unequal", true, 8); // 0 == -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "unequal", true, 9); // 0 == 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "unequal", true, 10); // 0 == 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "unequal", true, 11); // 0 == 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "unequal", true, 12); // 0 == pinf cmptst(field.newDfp("0"), ninf, "unequal", true, 13); // 0 == ninf cmptst(field.newDfp("-0"), pinf, "unequal", true, 14); // -0 == pinf cmptst(field.newDfp("-0"), ninf, "unequal", true, 15); // -0 == ninf cmptst(pinf, field.newDfp("0"), "unequal", true, 16); // pinf == 0 cmptst(ninf, field.newDfp("0"), "unequal", true, 17); // ninf == 0 cmptst(pinf, field.newDfp("-0"), "unequal", true, 18); // pinf == -0 cmptst(ninf, field.newDfp("-0"), "unequal", true, 19); // ninf == -0 cmptst(ninf, pinf, "unequal", true, 19.10); // ninf == pinf cmptst(pinf, ninf, "unequal", true, 19.11); // pinf == ninf cmptst(pinf, pinf, "unequal", false, 19.12); // pinf == pinf cmptst(ninf, ninf, "unequal", false, 19.13); // ninf == ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "unequal", false, 20); // 1 == 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "unequal", true, 21); // 1 == -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "unequal", false, 22); // -1 == -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "unequal", true, 23); // 1 == 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 == 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "unequal", true, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "unequal", false, 25); // check some nans -- nans shouldnt be unequal to anything cmptst(snan, snan, "unequal", false, 27); cmptst(qnan, qnan, "unequal", false, 28); cmptst(snan, qnan, "unequal", false, 29); cmptst(qnan, snan, "unequal", false, 30); cmptst(qnan, field.newDfp("0"), "unequal", false, 31); cmptst(snan, field.newDfp("0"), "unequal", false, 32); cmptst(field.newDfp("0"), snan, "unequal", false, 33); cmptst(field.newDfp("0"), qnan, "unequal", false, 34); cmptst(qnan, pinf, "unequal", false, 35); cmptst(snan, pinf, "unequal", false, 36); cmptst(pinf, snan, "unequal", false, 37); cmptst(pinf, qnan, "unequal", false, 38); cmptst(qnan, ninf, "unequal", false, 39); cmptst(snan, ninf, "unequal", false, 40); cmptst(ninf, snan, "unequal", false, 41); cmptst(ninf, qnan, "unequal", false, 42); cmptst(qnan, field.newDfp("-1"), "unequal", false, 43); cmptst(snan, field.newDfp("-1"), "unequal", false, 44); cmptst(field.newDfp("-1"), snan, "unequal", false, 45); cmptst(field.newDfp("-1"), qnan, "unequal", false, 46); cmptst(qnan, field.newDfp("1"), "unequal", false, 47); cmptst(snan, field.newDfp("1"), "unequal", false, 48); cmptst(field.newDfp("1"), snan, "unequal", false, 49); cmptst(field.newDfp("1"), qnan, "unequal", false, 50); cmptst(snan.negate(), snan, "unequal", false, 51); cmptst(qnan.negate(), qnan, "unequal", false, 52); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare unequal flags = "+field.getIEEEFlags()); // // Tests for lessThan -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "lessThan", false, 1); // 0 < 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "lessThan", false, 2); // 0 < -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "lessThan", false, 3); // -0 < -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "lessThan", false, 4); // -0 < 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "lessThan", true, 5); // 0 < 1 cmptst(field.newDfp("1"), field.newDfp("0"), "lessThan", false, 6); // 1 < 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "lessThan", true, 7); // -1 < 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "lessThan", false, 8); // 0 < -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "lessThan", true, 9); // 0 < 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "lessThan", true, 10); // 0 < 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "lessThan", true, 11); // 0 < 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "lessThan", true, 12); // 0 < pinf cmptst(field.newDfp("0"), ninf, "lessThan", false, 13); // 0 < ninf cmptst(field.newDfp("-0"), pinf, "lessThan", true, 14); // -0 < pinf cmptst(field.newDfp("-0"), ninf, "lessThan", false, 15); // -0 < ninf cmptst(pinf, field.newDfp("0"), "lessThan", false, 16); // pinf < 0 cmptst(ninf, field.newDfp("0"), "lessThan", true, 17); // ninf < 0 cmptst(pinf, field.newDfp("-0"), "lessThan", false, 18); // pinf < -0 cmptst(ninf, field.newDfp("-0"), "lessThan", true, 19); // ninf < -0 cmptst(ninf, pinf, "lessThan", true, 19.10); // ninf < pinf cmptst(pinf, ninf, "lessThan", false, 19.11); // pinf < ninf cmptst(pinf, pinf, "lessThan", false, 19.12); // pinf < pinf cmptst(ninf, ninf, "lessThan", false, 19.13); // ninf < ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "lessThan", false, 20); // 1 < 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "lessThan", false, 21); // 1 < -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "lessThan", false, 22); // -1 < -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "lessThan", true, 23); // 1 < 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 < 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "lessThan", false, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "lessThan", false, 25); // check some nans -- nans shouldnt be lessThan to anything cmptst(snan, snan, "lessThan", false, 27); cmptst(qnan, qnan, "lessThan", false, 28); cmptst(snan, qnan, "lessThan", false, 29); cmptst(qnan, snan, "lessThan", false, 30); cmptst(qnan, field.newDfp("0"), "lessThan", false, 31); cmptst(snan, field.newDfp("0"), "lessThan", false, 32); cmptst(field.newDfp("0"), snan, "lessThan", false, 33); cmptst(field.newDfp("0"), qnan, "lessThan", false, 34); cmptst(qnan, pinf, "lessThan", false, 35); cmptst(snan, pinf, "lessThan", false, 36); cmptst(pinf, snan, "lessThan", false, 37); cmptst(pinf, qnan, "lessThan", false, 38); cmptst(qnan, ninf, "lessThan", false, 39); cmptst(snan, ninf, "lessThan", false, 40); cmptst(ninf, snan, "lessThan", false, 41); cmptst(ninf, qnan, "lessThan", false, 42); cmptst(qnan, field.newDfp("-1"), "lessThan", false, 43); cmptst(snan, field.newDfp("-1"), "lessThan", false, 44); cmptst(field.newDfp("-1"), snan, "lessThan", false, 45); cmptst(field.newDfp("-1"), qnan, "lessThan", false, 46); cmptst(qnan, field.newDfp("1"), "lessThan", false, 47); cmptst(snan, field.newDfp("1"), "lessThan", false, 48); cmptst(field.newDfp("1"), snan, "lessThan", false, 49); cmptst(field.newDfp("1"), qnan, "lessThan", false, 50); cmptst(snan.negate(), snan, "lessThan", false, 51); cmptst(qnan.negate(), qnan, "lessThan", false, 52); //lessThan compares with nans should raise FLAG_INVALID if (field.getIEEEFlags() != DfpField.FLAG_INVALID) Assert.fail("assersion failed. compare lessThan flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); // // Tests for greaterThan -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "greaterThan", false, 1); // 0 > 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "greaterThan", false, 2); // 0 > -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "greaterThan", false, 3); // -0 > -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "greaterThan", false, 4); // -0 > 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "greaterThan", false, 5); // 0 > 1 cmptst(field.newDfp("1"), field.newDfp("0"), "greaterThan", true, 6); // 1 > 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "greaterThan", false, 7); // -1 > 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "greaterThan", true, 8); // 0 > -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "greaterThan", false, 9); // 0 > 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "greaterThan", false, 10); // 0 > 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "greaterThan", false, 11); // 0 > 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "greaterThan", false, 12); // 0 > pinf cmptst(field.newDfp("0"), ninf, "greaterThan", true, 13); // 0 > ninf cmptst(field.newDfp("-0"), pinf, "greaterThan", false, 14); // -0 > pinf cmptst(field.newDfp("-0"), ninf, "greaterThan", true, 15); // -0 > ninf cmptst(pinf, field.newDfp("0"), "greaterThan", true, 16); // pinf > 0 cmptst(ninf, field.newDfp("0"), "greaterThan", false, 17); // ninf > 0 cmptst(pinf, field.newDfp("-0"), "greaterThan", true, 18); // pinf > -0 cmptst(ninf, field.newDfp("-0"), "greaterThan", false, 19); // ninf > -0 cmptst(ninf, pinf, "greaterThan", false, 19.10); // ninf > pinf cmptst(pinf, ninf, "greaterThan", true, 19.11); // pinf > ninf cmptst(pinf, pinf, "greaterThan", false, 19.12); // pinf > pinf cmptst(ninf, ninf, "greaterThan", false, 19.13); // ninf > ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "greaterThan", false, 20); // 1 > 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "greaterThan", true, 21); // 1 > -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "greaterThan", false, 22); // -1 > -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "greaterThan", false, 23); // 1 > 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 > 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "greaterThan", true, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "greaterThan", false, 25); // check some nans -- nans shouldnt be greaterThan to anything cmptst(snan, snan, "greaterThan", false, 27); cmptst(qnan, qnan, "greaterThan", false, 28); cmptst(snan, qnan, "greaterThan", false, 29); cmptst(qnan, snan, "greaterThan", false, 30); cmptst(qnan, field.newDfp("0"), "greaterThan", false, 31); cmptst(snan, field.newDfp("0"), "greaterThan", false, 32); cmptst(field.newDfp("0"), snan, "greaterThan", false, 33); cmptst(field.newDfp("0"), qnan, "greaterThan", false, 34); cmptst(qnan, pinf, "greaterThan", false, 35); cmptst(snan, pinf, "greaterThan", false, 36); cmptst(pinf, snan, "greaterThan", false, 37); cmptst(pinf, qnan, "greaterThan", false, 38); cmptst(qnan, ninf, "greaterThan", false, 39); cmptst(snan, ninf, "greaterThan", false, 40); cmptst(ninf, snan, "greaterThan", false, 41); cmptst(ninf, qnan, "greaterThan", false, 42); cmptst(qnan, field.newDfp("-1"), "greaterThan", false, 43); cmptst(snan, field.newDfp("-1"), "greaterThan", false, 44); cmptst(field.newDfp("-1"), snan, "greaterThan", false, 45); cmptst(field.newDfp("-1"), qnan, "greaterThan", false, 46); cmptst(qnan, field.newDfp("1"), "greaterThan", false, 47); cmptst(snan, field.newDfp("1"), "greaterThan", false, 48); cmptst(field.newDfp("1"), snan, "greaterThan", false, 49); cmptst(field.newDfp("1"), qnan, "greaterThan", false, 50); cmptst(snan.negate(), snan, "greaterThan", false, 51); cmptst(qnan.negate(), qnan, "greaterThan", false, 52); //greaterThan compares with nans should raise FLAG_INVALID if (field.getIEEEFlags() != DfpField.FLAG_INVALID) Assert.fail("assersion failed. compare greaterThan flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); } // // Test multiplication // @Test public void testMultiply() { test(field.newDfp("1").multiply(field.newDfp("1")), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #1"); test(field.newDfp("1").multiply(1), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #2"); test(field.newDfp("-1").multiply(field.newDfp("1")), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #3"); test(field.newDfp("-1").multiply(1), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #4"); // basic tests with integers test(field.newDfp("2").multiply(field.newDfp("3")), field.newDfp("6"), 0, "Multiply #5"); test(field.newDfp("2").multiply(3), field.newDfp("6"), 0, "Multiply #6"); test(field.newDfp("-2").multiply(field.newDfp("3")), field.newDfp("-6"), 0, "Multiply #7"); test(field.newDfp("-2").multiply(3), field.newDfp("-6"), 0, "Multiply #8"); test(field.newDfp("2").multiply(field.newDfp("-3")), field.newDfp("-6"), 0, "Multiply #9"); test(field.newDfp("-2").multiply(field.newDfp("-3")), field.newDfp("6"), 0, "Multiply #10"); //multiply by zero test(field.newDfp("-2").multiply(field.newDfp("0")), field.newDfp("-0"), 0, "Multiply #11"); test(field.newDfp("-2").multiply(0), field.newDfp("-0"), 0, "Multiply #12"); test(field.newDfp("2").multiply(field.newDfp("0")), field.newDfp("0"), 0, "Multiply #13"); test(field.newDfp("2").multiply(0), field.newDfp("0"), 0, "Multiply #14"); test(field.newDfp("2").multiply(pinf), pinf, 0, "Multiply #15"); test(field.newDfp("2").multiply(ninf), ninf, 0, "Multiply #16"); test(field.newDfp("-2").multiply(pinf), ninf, 0, "Multiply #17"); test(field.newDfp("-2").multiply(ninf), pinf, 0, "Multiply #18"); test(ninf.multiply(field.newDfp("-2")), pinf, 0, "Multiply #18.1"); test(field.newDfp("5e131071").multiply(2), pinf, DfpField.FLAG_OVERFLOW, "Multiply #19"); test(field.newDfp("5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("9.9999999999999950000e131071"), 0, "Multiply #20"); test(field.newDfp("-5e131071").multiply(2), ninf, DfpField.FLAG_OVERFLOW, "Multiply #22"); test(field.newDfp("-5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("-9.9999999999999950000e131071"), 0, "Multiply #23"); test(field.newDfp("1e-65539").multiply(field.newDfp("1e-65539")), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "Multiply #24"); test(field.newDfp("1").multiply(nan), nan, 0, "Multiply #25"); test(nan.multiply(field.newDfp("1")), nan, 0, "Multiply #26"); test(nan.multiply(pinf), nan, 0, "Multiply #27"); test(pinf.multiply(nan), nan, 0, "Multiply #27"); test(pinf.multiply(field.newDfp("0")), nan, DfpField.FLAG_INVALID, "Multiply #28"); test(field.newDfp("0").multiply(pinf), nan, DfpField.FLAG_INVALID, "Multiply #29"); test(pinf.multiply(pinf), pinf, 0, "Multiply #30"); test(ninf.multiply(pinf), ninf, 0, "Multiply #31"); test(pinf.multiply(ninf), ninf, 0, "Multiply #32"); test(ninf.multiply(ninf), pinf, 0, "Multiply #33"); test(pinf.multiply(1), pinf, 0, "Multiply #34"); test(pinf.multiply(0), nan, DfpField.FLAG_INVALID, "Multiply #35"); test(nan.multiply(1), nan, 0, "Multiply #36"); test(field.newDfp("1").multiply(10000), field.newDfp("10000"), 0, "Multiply #37"); test(field.newDfp("2").multiply(1000000), field.newDfp("2000000"), 0, "Multiply #38"); test(field.newDfp("1").multiply(-1), field.newDfp("-1"), 0, "Multiply #39"); } @Test public void testDivide() { test(field.newDfp("1").divide(nan), // divide by NaN = NaN nan, 0, "Divide #1"); test(nan.divide(field.newDfp("1")), // NaN / number = NaN nan, 0, "Divide #2"); test(pinf.divide(field.newDfp("1")), pinf, 0, "Divide #3"); test(pinf.divide(field.newDfp("-1")), ninf, 0, "Divide #4"); test(pinf.divide(pinf), nan, DfpField.FLAG_INVALID, "Divide #5"); test(ninf.divide(pinf), nan, DfpField.FLAG_INVALID, "Divide #6"); test(pinf.divide(ninf), nan, DfpField.FLAG_INVALID, "Divide #7"); test(ninf.divide(ninf), nan, DfpField.FLAG_INVALID, "Divide #8"); test(field.newDfp("0").divide(field.newDfp("0")), nan, DfpField.FLAG_DIV_ZERO, "Divide #9"); test(field.newDfp("1").divide(field.newDfp("0")), pinf, DfpField.FLAG_DIV_ZERO, "Divide #10"); test(field.newDfp("1").divide(field.newDfp("-0")), ninf, DfpField.FLAG_DIV_ZERO, "Divide #11"); test(field.newDfp("-1").divide(field.newDfp("0")), ninf, DfpField.FLAG_DIV_ZERO, "Divide #12"); test(field.newDfp("-1").divide(field.newDfp("-0")), pinf, DfpField.FLAG_DIV_ZERO, "Divide #13"); test(field.newDfp("1").divide(field.newDfp("3")), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "Divide #14"); test(field.newDfp("1").divide(field.newDfp("6")), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "Divide #15"); test(field.newDfp("10").divide(field.newDfp("6")), field.newDfp("1.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #16"); test(field.newDfp("100").divide(field.newDfp("6")), field.newDfp("16.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #17"); test(field.newDfp("1000").divide(field.newDfp("6")), field.newDfp("166.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #18"); test(field.newDfp("10000").divide(field.newDfp("6")), field.newDfp("1666.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #19"); test(field.newDfp("1").divide(field.newDfp("1")), field.newDfp("1"), 0, "Divide #20"); test(field.newDfp("1").divide(field.newDfp("-1")), field.newDfp("-1"), 0, "Divide #21"); test(field.newDfp("-1").divide(field.newDfp("1")), field.newDfp("-1"), 0, "Divide #22"); test(field.newDfp("-1").divide(field.newDfp("-1")), field.newDfp("1"), 0, "Divide #23"); test(field.newDfp("1e-65539").divide(field.newDfp("1e65539")), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "Divide #24"); test(field.newDfp("1e65539").divide(field.newDfp("1e-65539")), pinf, DfpField.FLAG_OVERFLOW, "Divide #24"); test(field.newDfp("2").divide(field.newDfp("1.5")), // test trial-divisor too high field.newDfp("1.3333333333333333"), DfpField.FLAG_INEXACT, "Divide #25"); test(field.newDfp("2").divide(pinf), field.newDfp("0"), 0, "Divide #26"); test(field.newDfp("2").divide(ninf), field.newDfp("-0"), 0, "Divide #27"); test(field.newDfp("0").divide(field.newDfp("1")), field.newDfp("0"), 0, "Divide #28"); } @Test public void testReciprocal() { test(nan.reciprocal(), nan, 0, "Reciprocal #1"); test(field.newDfp("0").reciprocal(), pinf, DfpField.FLAG_DIV_ZERO, "Reciprocal #2"); test(field.newDfp("-0").reciprocal(), ninf, DfpField.FLAG_DIV_ZERO, "Reciprocal #3"); test(field.newDfp("3").reciprocal(), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "Reciprocal #4"); test(field.newDfp("6").reciprocal(), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "Reciprocal #5"); test(field.newDfp("1").reciprocal(), field.newDfp("1"), 0, "Reciprocal #6"); test(field.newDfp("-1").reciprocal(), field.newDfp("-1"), 0, "Reciprocal #7"); test(pinf.reciprocal(), field.newDfp("0"), 0, "Reciprocal #8"); test(ninf.reciprocal(), field.newDfp("-0"), 0, "Reciprocal #9"); } @Test public void testDivideInt() { test(nan.divide(1), // NaN / number = NaN nan, 0, "DivideInt #1"); test(pinf.divide(1), pinf, 0, "DivideInt #2"); test(field.newDfp("0").divide(0), nan, DfpField.FLAG_DIV_ZERO, "DivideInt #3"); test(field.newDfp("1").divide(0), pinf, DfpField.FLAG_DIV_ZERO, "DivideInt #4"); test(field.newDfp("-1").divide(0), ninf, DfpField.FLAG_DIV_ZERO, "DivideInt #5"); test(field.newDfp("1").divide(3), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "DivideInt #6"); test(field.newDfp("1").divide(6), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #7"); test(field.newDfp("10").divide(6), field.newDfp("1.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #8"); test(field.newDfp("100").divide(6), field.newDfp("16.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #9"); test(field.newDfp("1000").divide(6), field.newDfp("166.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #10"); test(field.newDfp("10000").divide(6), field.newDfp("1666.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #20"); test(field.newDfp("1").divide(1), field.newDfp("1"), 0, "DivideInt #21"); test(field.newDfp("1e-131077").divide(10), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "DivideInt #22"); test(field.newDfp("0").divide(1), field.newDfp("0"), 0, "DivideInt #23"); test(field.newDfp("1").divide(10000), nan, DfpField.FLAG_INVALID, "DivideInt #24"); test(field.newDfp("1").divide(-1), nan, DfpField.FLAG_INVALID, "DivideInt #25"); } @Test public void testNextAfter() { test(field.newDfp("1").nextAfter(pinf), field.newDfp("1.0000000000000001"), 0, "NextAfter #1"); test(field.newDfp("1.0000000000000001").nextAfter(ninf), field.newDfp("1"), 0, "NextAfter #1.5"); test(field.newDfp("1").nextAfter(ninf), field.newDfp("0.99999999999999999999"), 0, "NextAfter #2"); test(field.newDfp("0.99999999999999999999").nextAfter(field.newDfp("2")), field.newDfp("1"), 0, "NextAfter #3"); test(field.newDfp("-1").nextAfter(ninf), field.newDfp("-1.0000000000000001"), 0, "NextAfter #4"); test(field.newDfp("-1").nextAfter(pinf), field.newDfp("-0.99999999999999999999"), 0, "NextAfter #5"); test(field.newDfp("-0.99999999999999999999").nextAfter(field.newDfp("-2")), field.newDfp("-1"), 0, "NextAfter #6"); test(field.newDfp("2").nextAfter(field.newDfp("2")), field.newDfp("2"), 0, "NextAfter #7"); test(field.newDfp("0").nextAfter(field.newDfp("0")), field.newDfp("0"), 0, "NextAfter #8"); test(field.newDfp("-2").nextAfter(field.newDfp("-2")), field.newDfp("-2"), 0, "NextAfter #9"); test(field.newDfp("0").nextAfter(field.newDfp("1")), field.newDfp("1e-131092"), DfpField.FLAG_UNDERFLOW, "NextAfter #10"); test(field.newDfp("0").nextAfter(field.newDfp("-1")), field.newDfp("-1e-131092"), DfpField.FLAG_UNDERFLOW, "NextAfter #11"); test(field.newDfp("-1e-131092").nextAfter(pinf), field.newDfp("-0"), DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #12"); test(field.newDfp("1e-131092").nextAfter(ninf), field.newDfp("0"), DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #13"); test(field.newDfp("9.9999999999999999999e131078").nextAfter(pinf), pinf, DfpField.FLAG_OVERFLOW|DfpField.FLAG_INEXACT, "Next After #14"); } @Test public void testToString() { Assert.assertEquals("toString #1", "Infinity", pinf.toString()); Assert.assertEquals("toString #2", "-Infinity", ninf.toString()); Assert.assertEquals("toString #3", "NaN", nan.toString()); Assert.assertEquals("toString #4", "NaN", field.newDfp((byte) 1, Dfp.QNAN).toString()); Assert.assertEquals("toString #5", "NaN", field.newDfp((byte) 1, Dfp.SNAN).toString()); Assert.assertEquals("toString #6", "1.2300000000000000e100", field.newDfp("1.23e100").toString()); Assert.assertEquals("toString #7", "-1.2300000000000000e100", field.newDfp("-1.23e100").toString()); Assert.assertEquals("toString #8", "12345678.1234", field.newDfp("12345678.1234").toString()); Assert.assertEquals("toString #9", "0.00001234", field.newDfp("0.00001234").toString()); } @Test public void testRound() { field.setRoundingMode(DfpField.RoundingMode.ROUND_DOWN); // Round down test(field.newDfp("12345678901234567890").add(field.newDfp("0.9")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #1"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.99999999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #2"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.99999999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #3"); field.setRoundingMode(DfpField.RoundingMode.ROUND_UP); // Round up test(field.newDfp("12345678901234567890").add(field.newDfp("0.1")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #4"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.0001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #5"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.1")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #6"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.0001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #7"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_UP); // Round half up test(field.newDfp("12345678901234567890").add(field.newDfp("0.4999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #8"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #9"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.4999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #10"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #11"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_DOWN); // Round half down test(field.newDfp("12345678901234567890").add(field.newDfp("0.5001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #12"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #13"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #14"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #15"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_ODD); // Round half odd test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #16"); test(field.newDfp("12345678901234567891").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #17"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #18"); test(field.newDfp("-12345678901234567891").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #19"); field.setRoundingMode(DfpField.RoundingMode.ROUND_CEIL); // Round ceil test(field.newDfp("12345678901234567890").add(field.newDfp("0.0001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #20"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.9999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #21"); field.setRoundingMode(DfpField.RoundingMode.ROUND_FLOOR); // Round floor test(field.newDfp("12345678901234567890").add(field.newDfp("0.9999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #22"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.0001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #23"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_EVEN); // reset } @Test public void testCeil() { test(field.newDfp("1234.0000000000000001").ceil(), field.newDfp("1235"), DfpField.FLAG_INEXACT, "Ceil #1"); } @Test public void testFloor() { test(field.newDfp("1234.9999999999999999").floor(), field.newDfp("1234"), DfpField.FLAG_INEXACT, "Floor #1"); } @Test public void testRint() { test(field.newDfp("1234.50000000001").rint(), field.newDfp("1235"), DfpField.FLAG_INEXACT, "Rint #1"); test(field.newDfp("1234.5000").rint(), field.newDfp("1234"), DfpField.FLAG_INEXACT, "Rint #2"); test(field.newDfp("1235.5000").rint(), field.newDfp("1236"), DfpField.FLAG_INEXACT, "Rint #3"); } @Test public void testCopySign() { test(Dfp.copysign(field.newDfp("1234."), field.newDfp("-1")), field.newDfp("-1234"), 0, "CopySign #1"); test(Dfp.copysign(field.newDfp("-1234."), field.newDfp("-1")), field.newDfp("-1234"), 0, "CopySign #2"); test(Dfp.copysign(field.newDfp("-1234."), field.newDfp("1")), field.newDfp("1234"), 0, "CopySign #3"); test(Dfp.copysign(field.newDfp("1234."), field.newDfp("1")), field.newDfp("1234"), 0, "CopySign #4"); } @Test public void testIntValue() { Assert.assertEquals("intValue #1", 1234, field.newDfp("1234").intValue()); Assert.assertEquals("intValue #2", -1234, field.newDfp("-1234").intValue()); Assert.assertEquals("intValue #3", 1234, field.newDfp("1234.5").intValue()); Assert.assertEquals("intValue #4", 1235, field.newDfp("1234.500001").intValue()); Assert.assertEquals("intValue #5", 2147483647, field.newDfp("1e1000").intValue()); Assert.assertEquals("intValue #6", -2147483648, field.newDfp("-1e1000").intValue()); } @Test public void testLog10K() { Assert.assertEquals("log10K #1", 1, field.newDfp("123456").log10K()); Assert.assertEquals("log10K #2", 2, field.newDfp("123456789").log10K()); Assert.assertEquals("log10K #3", 0, field.newDfp("2").log10K()); Assert.assertEquals("log10K #3", 0, field.newDfp("1").log10K()); Assert.assertEquals("log10K #4", -1, field.newDfp("0.1").log10K()); } @Test public void testPower10K() { Dfp d = field.newDfp(); test(d.power10K(0), field.newDfp("1"), 0, "Power10 #1"); test(d.power10K(1), field.newDfp("10000"), 0, "Power10 #2"); test(d.power10K(2), field.newDfp("100000000"), 0, "Power10 #3"); test(d.power10K(-1), field.newDfp("0.0001"), 0, "Power10 #4"); test(d.power10K(-2), field.newDfp("0.00000001"), 0, "Power10 #5"); test(d.power10K(-3), field.newDfp("0.000000000001"), 0, "Power10 #6"); } @Test public void testLog10() { Assert.assertEquals("log10 #1", 1, field.newDfp("12").log10()); Assert.assertEquals("log10 #2", 2, field.newDfp("123").log10()); Assert.assertEquals("log10 #3", 3, field.newDfp("1234").log10()); Assert.assertEquals("log10 #4", 4, field.newDfp("12345").log10()); Assert.assertEquals("log10 #5", 5, field.newDfp("123456").log10()); Assert.assertEquals("log10 #6", 6, field.newDfp("1234567").log10()); Assert.assertEquals("log10 #6", 7, field.newDfp("12345678").log10()); Assert.assertEquals("log10 #7", 8, field.newDfp("123456789").log10()); Assert.assertEquals("log10 #8", 9, field.newDfp("1234567890").log10()); Assert.assertEquals("log10 #9", 10, field.newDfp("12345678901").log10()); Assert.assertEquals("log10 #10", 11, field.newDfp("123456789012").log10()); Assert.assertEquals("log10 #11", 12, field.newDfp("1234567890123").log10()); Assert.assertEquals("log10 #12", 0, field.newDfp("2").log10()); Assert.assertEquals("log10 #13", 0, field.newDfp("1").log10()); Assert.assertEquals("log10 #14", -1, field.newDfp("0.12").log10()); Assert.assertEquals("log10 #15", -2, field.newDfp("0.012").log10()); } @Test public void testPower10() { Dfp d = field.newDfp(); test(d.power10(0), field.newDfp("1"), 0, "Power10 #1"); test(d.power10(1), field.newDfp("10"), 0, "Power10 #2"); test(d.power10(2), field.newDfp("100"), 0, "Power10 #3"); test(d.power10(3), field.newDfp("1000"), 0, "Power10 #4"); test(d.power10(4), field.newDfp("10000"), 0, "Power10 #5"); test(d.power10(5), field.newDfp("100000"), 0, "Power10 #6"); test(d.power10(6), field.newDfp("1000000"), 0, "Power10 #7"); test(d.power10(7), field.newDfp("10000000"), 0, "Power10 #8"); test(d.power10(8), field.newDfp("100000000"), 0, "Power10 #9"); test(d.power10(9), field.newDfp("1000000000"), 0, "Power10 #10"); test(d.power10(-1), field.newDfp(".1"), 0, "Power10 #11"); test(d.power10(-2), field.newDfp(".01"), 0, "Power10 #12"); test(d.power10(-3), field.newDfp(".001"), 0, "Power10 #13"); test(d.power10(-4), field.newDfp(".0001"), 0, "Power10 #14"); test(d.power10(-5), field.newDfp(".00001"), 0, "Power10 #15"); test(d.power10(-6), field.newDfp(".000001"), 0, "Power10 #16"); test(d.power10(-7), field.newDfp(".0000001"), 0, "Power10 #17"); test(d.power10(-8), field.newDfp(".00000001"), 0, "Power10 #18"); test(d.power10(-9), field.newDfp(".000000001"), 0, "Power10 #19"); test(d.power10(-10), field.newDfp(".0000000001"), 0, "Power10 #20"); } @Test public void testRemainder() { test(field.newDfp("10").remainder(field.newDfp("3")), field.newDfp("1"), DfpField.FLAG_INEXACT, "Remainder #1"); test(field.newDfp("9").remainder(field.newDfp("3")), field.newDfp("0"), 0, "Remainder #2"); test(field.newDfp("-9").remainder(field.newDfp("3")), field.newDfp("-0"), 0, "Remainder #3"); } @Test public void testSqrt() { test(field.newDfp("0").sqrt(), field.newDfp("0"), 0, "Sqrt #1"); test(field.newDfp("-0").sqrt(), field.newDfp("-0"), 0, "Sqrt #2"); test(field.newDfp("1").sqrt(), field.newDfp("1"), 0, "Sqrt #3"); test(field.newDfp("2").sqrt(), field.newDfp("1.4142135623730950"), DfpField.FLAG_INEXACT, "Sqrt #4"); test(field.newDfp("3").sqrt(), field.newDfp("1.7320508075688773"), DfpField.FLAG_INEXACT, "Sqrt #5"); test(field.newDfp("5").sqrt(), field.newDfp("2.2360679774997897"), DfpField.FLAG_INEXACT, "Sqrt #6"); test(field.newDfp("500").sqrt(), field.newDfp("22.3606797749978970"), DfpField.FLAG_INEXACT, "Sqrt #6.2"); test(field.newDfp("50000").sqrt(), field.newDfp("223.6067977499789696"), DfpField.FLAG_INEXACT, "Sqrt #6.3"); test(field.newDfp("-1").sqrt(), nan, DfpField.FLAG_INVALID, "Sqrt #7"); test(pinf.sqrt(), pinf, 0, "Sqrt #8"); test(field.newDfp((byte) 1, Dfp.QNAN).sqrt(), nan, 0, "Sqrt #9"); test(field.newDfp((byte) 1, Dfp.SNAN).sqrt(), nan, DfpField.FLAG_INVALID, "Sqrt #9"); } @Test public void testIssue567() { DfpField field = new DfpField(100); Assert.assertEquals(0.0, field.getZero().toDouble(), Precision.SAFE_MIN); Assert.assertEquals(0.0, field.newDfp(0.0).toDouble(), Precision.SAFE_MIN); Assert.assertEquals(-1, FastMath.copySign(1, field.newDfp(-0.0).toDouble()), Precision.EPSILON); Assert.assertEquals(+1, FastMath.copySign(1, field.newDfp(+0.0).toDouble()), Precision.EPSILON); } @Test public void testIsZero() { Assert.assertTrue(field.getZero().isZero()); Assert.assertTrue(field.getZero().negate().isZero()); Assert.assertTrue(field.newDfp(+0.0).isZero()); Assert.assertTrue(field.newDfp(-0.0).isZero()); Assert.assertFalse(field.newDfp(1.0e-90).isZero()); Assert.assertFalse(nan.isZero()); Assert.assertFalse(nan.negate().isZero()); Assert.assertFalse(pinf.isZero()); Assert.assertFalse(pinf.negate().isZero()); Assert.assertFalse(ninf.isZero()); Assert.assertFalse(ninf.negate().isZero()); } @Test public void testSignPredicates() { Assert.assertTrue(field.getZero().negativeOrNull()); Assert.assertTrue(field.getZero().positiveOrNull()); Assert.assertFalse(field.getZero().strictlyNegative()); Assert.assertFalse(field.getZero().strictlyPositive()); Assert.assertTrue(field.getZero().negate().negativeOrNull()); Assert.assertTrue(field.getZero().negate().positiveOrNull()); Assert.assertFalse(field.getZero().negate().strictlyNegative()); Assert.assertFalse(field.getZero().negate().strictlyPositive()); Assert.assertFalse(field.getOne().negativeOrNull()); Assert.assertTrue(field.getOne().positiveOrNull()); Assert.assertFalse(field.getOne().strictlyNegative()); Assert.assertTrue(field.getOne().strictlyPositive()); Assert.assertTrue(field.getOne().negate().negativeOrNull()); Assert.assertFalse(field.getOne().negate().positiveOrNull()); Assert.assertTrue(field.getOne().negate().strictlyNegative()); Assert.assertFalse(field.getOne().negate().strictlyPositive()); Assert.assertFalse(nan.negativeOrNull()); Assert.assertFalse(nan.positiveOrNull()); Assert.assertFalse(nan.strictlyNegative()); Assert.assertFalse(nan.strictlyPositive()); Assert.assertFalse(nan.negate().negativeOrNull()); Assert.assertFalse(nan.negate().positiveOrNull()); Assert.assertFalse(nan.negate().strictlyNegative()); Assert.assertFalse(nan.negate().strictlyPositive()); Assert.assertFalse(pinf.negativeOrNull()); Assert.assertTrue(pinf.positiveOrNull()); Assert.assertFalse(pinf.strictlyNegative()); Assert.assertTrue(pinf.strictlyPositive()); Assert.assertTrue(pinf.negate().negativeOrNull()); Assert.assertFalse(pinf.negate().positiveOrNull()); Assert.assertTrue(pinf.negate().strictlyNegative()); Assert.assertFalse(pinf.negate().strictlyPositive()); Assert.assertTrue(ninf.negativeOrNull()); Assert.assertFalse(ninf.positiveOrNull()); Assert.assertTrue(ninf.strictlyNegative()); Assert.assertFalse(ninf.strictlyPositive()); Assert.assertFalse(ninf.negate().negativeOrNull()); Assert.assertTrue(ninf.negate().positiveOrNull()); Assert.assertFalse(ninf.negate().strictlyNegative()); Assert.assertTrue(ninf.negate().strictlyPositive()); } }
// You are a professional Java test case writer, please create a test case named `testMultiply` for the issue `Math-MATH-778`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-778 // // ## Issue-Title: // Dfp Dfp.multiply(int x) does not comply with the general contract FieldElement.multiply(int n) // // ## Issue-Description: // // In class org.apache.commons.math3.Dfp, the method multiply(int n) is limited to 0 <= n <= 9999. This is not consistent with the general contract of FieldElement.multiply(int n), where there should be no limitation on the values of n. // // // // // @Test public void testMultiply() {
919
// // Test multiplication //
17
754
src/test/java/org/apache/commons/math3/dfp/DfpTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-778 ## Issue-Title: Dfp Dfp.multiply(int x) does not comply with the general contract FieldElement.multiply(int n) ## Issue-Description: In class org.apache.commons.math3.Dfp, the method multiply(int n) is limited to 0 <= n <= 9999. This is not consistent with the general contract of FieldElement.multiply(int n), where there should be no limitation on the values of n. ``` You are a professional Java test case writer, please create a test case named `testMultiply` for the issue `Math-MATH-778`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMultiply() { ```
754
[ "org.apache.commons.math3.dfp.Dfp" ]
d77b7a1156c43b7909fe681fde5d9ba690ffab0326dea68c6bbd1c2d5856dbb1
@Test public void testMultiply()
// You are a professional Java test case writer, please create a test case named `testMultiply` for the issue `Math-MATH-778`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-778 // // ## Issue-Title: // Dfp Dfp.multiply(int x) does not comply with the general contract FieldElement.multiply(int n) // // ## Issue-Description: // // In class org.apache.commons.math3.Dfp, the method multiply(int n) is limited to 0 <= n <= 9999. This is not consistent with the general contract of FieldElement.multiply(int n), where there should be no limitation on the values of n. // // // // //
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.dfp; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DfpTest { private DfpField field; private Dfp pinf; private Dfp ninf; private Dfp nan; private Dfp snan; private Dfp qnan; @Before public void setUp() { // Some basic setup. Define some constants and clear the status flags field = new DfpField(20); pinf = field.newDfp("1").divide(field.newDfp("0")); ninf = field.newDfp("-1").divide(field.newDfp("0")); nan = field.newDfp("0").divide(field.newDfp("0")); snan = field.newDfp((byte)1, Dfp.SNAN); qnan = field.newDfp((byte)1, Dfp.QNAN); ninf.getField().clearIEEEFlags(); } @After public void tearDown() { field = null; pinf = null; ninf = null; nan = null; snan = null; qnan = null; } // Generic test function. Takes params x and y and tests them for // equality. Then checks the status flags against the flags argument. // If the test fail, it prints the desc string private void test(Dfp x, Dfp y, int flags, String desc) { boolean b = x.equals(y); if (!x.equals(y) && !x.unequal(y)) // NaNs involved b = (x.toString().equals(y.toString())); if (x.equals(field.newDfp("0"))) // distinguish +/- zero b = (b && (x.toString().equals(y.toString()))); b = (b && x.getField().getIEEEFlags() == flags); if (!b) Assert.assertTrue("assersion failed "+desc+" x = "+x.toString()+" flags = "+x.getField().getIEEEFlags(), b); x.getField().clearIEEEFlags(); } @Test public void testByteConstructor() { Assert.assertEquals("0.", new Dfp(field, (byte) 0).toString()); Assert.assertEquals("1.", new Dfp(field, (byte) 1).toString()); Assert.assertEquals("-1.", new Dfp(field, (byte) -1).toString()); Assert.assertEquals("-128.", new Dfp(field, Byte.MIN_VALUE).toString()); Assert.assertEquals("127.", new Dfp(field, Byte.MAX_VALUE).toString()); } @Test public void testIntConstructor() { Assert.assertEquals("0.", new Dfp(field, 0).toString()); Assert.assertEquals("1.", new Dfp(field, 1).toString()); Assert.assertEquals("-1.", new Dfp(field, -1).toString()); Assert.assertEquals("1234567890.", new Dfp(field, 1234567890).toString()); Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890).toString()); Assert.assertEquals("-2147483648.", new Dfp(field, Integer.MIN_VALUE).toString()); Assert.assertEquals("2147483647.", new Dfp(field, Integer.MAX_VALUE).toString()); } @Test public void testLongConstructor() { Assert.assertEquals("0.", new Dfp(field, 0l).toString()); Assert.assertEquals("1.", new Dfp(field, 1l).toString()); Assert.assertEquals("-1.", new Dfp(field, -1l).toString()); Assert.assertEquals("1234567890.", new Dfp(field, 1234567890l).toString()); Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890l).toString()); Assert.assertEquals("-9223372036854775808.", new Dfp(field, Long.MIN_VALUE).toString()); Assert.assertEquals("9223372036854775807.", new Dfp(field, Long.MAX_VALUE).toString()); } /* * Test addition */ @Test public void testAdd() { test(field.newDfp("1").add(field.newDfp("1")), // Basic tests 1+1 = 2 field.newDfp("2"), 0, "Add #1"); test(field.newDfp("1").add(field.newDfp("-1")), // 1 + (-1) = 0 field.newDfp("0"), 0, "Add #2"); test(field.newDfp("-1").add(field.newDfp("1")), // (-1) + 1 = 0 field.newDfp("0"), 0, "Add #3"); test(field.newDfp("-1").add(field.newDfp("-1")), // (-1) + (-1) = -2 field.newDfp("-2"), 0, "Add #4"); // rounding mode is round half even test(field.newDfp("1").add(field.newDfp("1e-16")), // rounding on add field.newDfp("1.0000000000000001"), 0, "Add #5"); test(field.newDfp("1").add(field.newDfp("1e-17")), // rounding on add field.newDfp("1"), DfpField.FLAG_INEXACT, "Add #6"); test(field.newDfp("0.90999999999999999999").add(field.newDfp("0.1")), // rounding on add field.newDfp("1.01"), DfpField.FLAG_INEXACT, "Add #7"); test(field.newDfp(".10000000000000005000").add(field.newDfp(".9")), // rounding on add field.newDfp("1."), DfpField.FLAG_INEXACT, "Add #8"); test(field.newDfp(".10000000000000015000").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000002"), DfpField.FLAG_INEXACT, "Add #9"); test(field.newDfp(".10000000000000014999").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000001"), DfpField.FLAG_INEXACT, "Add #10"); test(field.newDfp(".10000000000000015001").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000002"), DfpField.FLAG_INEXACT, "Add #11"); test(field.newDfp(".11111111111111111111").add(field.newDfp("11.1111111111111111")), // rounding on add field.newDfp("11.22222222222222222222"), DfpField.FLAG_INEXACT, "Add #12"); test(field.newDfp(".11111111111111111111").add(field.newDfp("1111111111111111.1111")), // rounding on add field.newDfp("1111111111111111.2222"), DfpField.FLAG_INEXACT, "Add #13"); test(field.newDfp(".11111111111111111111").add(field.newDfp("11111111111111111111")), // rounding on add field.newDfp("11111111111111111111"), DfpField.FLAG_INEXACT, "Add #14"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("-1e131052")), // overflow on add field.newDfp("9.9999999999999999998e131071"), 0, "Add #15"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("1e131052")), // overflow on add pinf, DfpField.FLAG_OVERFLOW, "Add #16"); test(field.newDfp("-9.9999999999999999999e131071").add(field.newDfp("-1e131052")), // overflow on add ninf, DfpField.FLAG_OVERFLOW, "Add #17"); test(field.newDfp("-9.9999999999999999999e131071").add(field.newDfp("1e131052")), // overflow on add field.newDfp("-9.9999999999999999998e131071"), 0, "Add #18"); test(field.newDfp("1e-131072").add(field.newDfp("1e-131072")), // underflow on add field.newDfp("2e-131072"), 0, "Add #19"); test(field.newDfp("1.0000000000000001e-131057").add(field.newDfp("-1e-131057")), // underflow on add field.newDfp("1e-131073"), DfpField.FLAG_UNDERFLOW, "Add #20"); test(field.newDfp("1.1e-131072").add(field.newDfp("-1e-131072")), // underflow on add field.newDfp("1e-131073"), DfpField.FLAG_UNDERFLOW, "Add #21"); test(field.newDfp("1.0000000000000001e-131072").add(field.newDfp("-1e-131072")), // underflow on add field.newDfp("1e-131088"), DfpField.FLAG_UNDERFLOW, "Add #22"); test(field.newDfp("1.0000000000000001e-131078").add(field.newDfp("-1e-131078")), // underflow on add field.newDfp("0"), DfpField.FLAG_UNDERFLOW, "Add #23"); test(field.newDfp("1.0").add(field.newDfp("-1e-20")), // loss of precision on alignment? field.newDfp("0.99999999999999999999"), 0, "Add #23.1"); test(field.newDfp("-0.99999999999999999999").add(field.newDfp("1")), // proper normalization? field.newDfp("0.00000000000000000001"), 0, "Add #23.2"); test(field.newDfp("1").add(field.newDfp("0")), // adding zeros field.newDfp("1"), 0, "Add #24"); test(field.newDfp("0").add(field.newDfp("0")), // adding zeros field.newDfp("0"), 0, "Add #25"); test(field.newDfp("-0").add(field.newDfp("0")), // adding zeros field.newDfp("0"), 0, "Add #26"); test(field.newDfp("0").add(field.newDfp("-0")), // adding zeros field.newDfp("0"), 0, "Add #27"); test(field.newDfp("-0").add(field.newDfp("-0")), // adding zeros field.newDfp("-0"), 0, "Add #28"); test(field.newDfp("1e-20").add(field.newDfp("0")), // adding zeros field.newDfp("1e-20"), 0, "Add #29"); test(field.newDfp("1e-40").add(field.newDfp("0")), // adding zeros field.newDfp("1e-40"), 0, "Add #30"); test(pinf.add(ninf), // adding infinities nan, DfpField.FLAG_INVALID, "Add #31"); test(ninf.add(pinf), // adding infinities nan, DfpField.FLAG_INVALID, "Add #32"); test(ninf.add(ninf), // adding infinities ninf, 0, "Add #33"); test(pinf.add(pinf), // adding infinities pinf, 0, "Add #34"); test(pinf.add(field.newDfp("0")), // adding infinities pinf, 0, "Add #35"); test(pinf.add(field.newDfp("-1e131071")), // adding infinities pinf, 0, "Add #36"); test(pinf.add(field.newDfp("1e131071")), // adding infinities pinf, 0, "Add #37"); test(field.newDfp("0").add(pinf), // adding infinities pinf, 0, "Add #38"); test(field.newDfp("-1e131071").add(pinf), // adding infinities pinf, 0, "Add #39"); test(field.newDfp("1e131071").add(pinf), // adding infinities pinf, 0, "Add #40"); test(ninf.add(field.newDfp("0")), // adding infinities ninf, 0, "Add #41"); test(ninf.add(field.newDfp("-1e131071")), // adding infinities ninf, 0, "Add #42"); test(ninf.add(field.newDfp("1e131071")), // adding infinities ninf, 0, "Add #43"); test(field.newDfp("0").add(ninf), // adding infinities ninf, 0, "Add #44"); test(field.newDfp("-1e131071").add(ninf), // adding infinities ninf, 0, "Add #45"); test(field.newDfp("1e131071").add(ninf), // adding infinities ninf, 0, "Add #46"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("5e131051")), // overflow pinf, DfpField.FLAG_OVERFLOW, "Add #47"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("4.9999999999999999999e131051")), // overflow field.newDfp("9.9999999999999999999e131071"), DfpField.FLAG_INEXACT, "Add #48"); test(nan.add(field.newDfp("1")), nan, 0, "Add #49"); test(field.newDfp("1").add(nan), nan, 0, "Add #50"); test(field.newDfp("12345678123456781234").add(field.newDfp("0.12345678123456781234")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #51"); test(field.newDfp("12345678123456781234").add(field.newDfp("123.45678123456781234")), field.newDfp("12345678123456781357"), DfpField.FLAG_INEXACT, "Add #52"); test(field.newDfp("123.45678123456781234").add(field.newDfp("12345678123456781234")), field.newDfp("12345678123456781357"), DfpField.FLAG_INEXACT, "Add #53"); test(field.newDfp("12345678123456781234").add(field.newDfp(".00001234567812345678")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #54"); test(field.newDfp("12345678123456781234").add(field.newDfp(".00000000123456781234")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #55"); test(field.newDfp("-0").add(field.newDfp("-0")), field.newDfp("-0"), 0, "Add #56"); test(field.newDfp("0").add(field.newDfp("-0")), field.newDfp("0"), 0, "Add #57"); test(field.newDfp("-0").add(field.newDfp("0")), field.newDfp("0"), 0, "Add #58"); test(field.newDfp("0").add(field.newDfp("0")), field.newDfp("0"), 0, "Add #59"); } //////////////////////////////////////////////////////////////////////////////////////////////////////// // Test comparisons // utility function to help test comparisons private void cmptst(Dfp a, Dfp b, String op, boolean result, double num) { if (op == "equal") if (a.equals(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "unequal") if (a.unequal(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "lessThan") if (a.lessThan(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "greaterThan") if (a.greaterThan(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); } @Test public void testCompare() { // test equal() comparison // check zero vs. zero field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("0"), "equal", true, 1); // 0 == 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "equal", true, 2); // 0 == -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "equal", true, 3); // -0 == -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "equal", true, 4); // -0 == 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "equal", false, 5); // 0 == 1 cmptst(field.newDfp("1"), field.newDfp("0"), "equal", false, 6); // 1 == 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "equal", false, 7); // -1 == 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "equal", false, 8); // 0 == -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "equal", false, 9); // 0 == 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "equal", false, 10); // 0 == 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "equal", false, 11); // 0 == 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "equal", false, 12); // 0 == pinf cmptst(field.newDfp("0"), ninf, "equal", false, 13); // 0 == ninf cmptst(field.newDfp("-0"), pinf, "equal", false, 14); // -0 == pinf cmptst(field.newDfp("-0"), ninf, "equal", false, 15); // -0 == ninf cmptst(pinf, field.newDfp("0"), "equal", false, 16); // pinf == 0 cmptst(ninf, field.newDfp("0"), "equal", false, 17); // ninf == 0 cmptst(pinf, field.newDfp("-0"), "equal", false, 18); // pinf == -0 cmptst(ninf, field.newDfp("-0"), "equal", false, 19); // ninf == -0 cmptst(ninf, pinf, "equal", false, 19.10); // ninf == pinf cmptst(pinf, ninf, "equal", false, 19.11); // pinf == ninf cmptst(pinf, pinf, "equal", true, 19.12); // pinf == pinf cmptst(ninf, ninf, "equal", true, 19.13); // ninf == ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "equal", true, 20); // 1 == 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "equal", false, 21); // 1 == -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "equal", true, 22); // -1 == -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "equal", false, 23); // 1 == 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 == 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "equal", false, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "equal", true, 25); // check some nans -- nans shouldnt equal anything cmptst(snan, snan, "equal", false, 27); cmptst(qnan, qnan, "equal", false, 28); cmptst(snan, qnan, "equal", false, 29); cmptst(qnan, snan, "equal", false, 30); cmptst(qnan, field.newDfp("0"), "equal", false, 31); cmptst(snan, field.newDfp("0"), "equal", false, 32); cmptst(field.newDfp("0"), snan, "equal", false, 33); cmptst(field.newDfp("0"), qnan, "equal", false, 34); cmptst(qnan, pinf, "equal", false, 35); cmptst(snan, pinf, "equal", false, 36); cmptst(pinf, snan, "equal", false, 37); cmptst(pinf, qnan, "equal", false, 38); cmptst(qnan, ninf, "equal", false, 39); cmptst(snan, ninf, "equal", false, 40); cmptst(ninf, snan, "equal", false, 41); cmptst(ninf, qnan, "equal", false, 42); cmptst(qnan, field.newDfp("-1"), "equal", false, 43); cmptst(snan, field.newDfp("-1"), "equal", false, 44); cmptst(field.newDfp("-1"), snan, "equal", false, 45); cmptst(field.newDfp("-1"), qnan, "equal", false, 46); cmptst(qnan, field.newDfp("1"), "equal", false, 47); cmptst(snan, field.newDfp("1"), "equal", false, 48); cmptst(field.newDfp("1"), snan, "equal", false, 49); cmptst(field.newDfp("1"), qnan, "equal", false, 50); cmptst(snan.negate(), snan, "equal", false, 51); cmptst(qnan.negate(), qnan, "equal", false, 52); // // Tests for un equal -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "unequal", false, 1); // 0 == 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "unequal", false, 2); // 0 == -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "unequal", false, 3); // -0 == -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "unequal", false, 4); // -0 == 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "unequal", true, 5); // 0 == 1 cmptst(field.newDfp("1"), field.newDfp("0"), "unequal", true, 6); // 1 == 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "unequal", true, 7); // -1 == 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "unequal", true, 8); // 0 == -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "unequal", true, 9); // 0 == 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "unequal", true, 10); // 0 == 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "unequal", true, 11); // 0 == 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "unequal", true, 12); // 0 == pinf cmptst(field.newDfp("0"), ninf, "unequal", true, 13); // 0 == ninf cmptst(field.newDfp("-0"), pinf, "unequal", true, 14); // -0 == pinf cmptst(field.newDfp("-0"), ninf, "unequal", true, 15); // -0 == ninf cmptst(pinf, field.newDfp("0"), "unequal", true, 16); // pinf == 0 cmptst(ninf, field.newDfp("0"), "unequal", true, 17); // ninf == 0 cmptst(pinf, field.newDfp("-0"), "unequal", true, 18); // pinf == -0 cmptst(ninf, field.newDfp("-0"), "unequal", true, 19); // ninf == -0 cmptst(ninf, pinf, "unequal", true, 19.10); // ninf == pinf cmptst(pinf, ninf, "unequal", true, 19.11); // pinf == ninf cmptst(pinf, pinf, "unequal", false, 19.12); // pinf == pinf cmptst(ninf, ninf, "unequal", false, 19.13); // ninf == ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "unequal", false, 20); // 1 == 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "unequal", true, 21); // 1 == -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "unequal", false, 22); // -1 == -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "unequal", true, 23); // 1 == 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 == 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "unequal", true, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "unequal", false, 25); // check some nans -- nans shouldnt be unequal to anything cmptst(snan, snan, "unequal", false, 27); cmptst(qnan, qnan, "unequal", false, 28); cmptst(snan, qnan, "unequal", false, 29); cmptst(qnan, snan, "unequal", false, 30); cmptst(qnan, field.newDfp("0"), "unequal", false, 31); cmptst(snan, field.newDfp("0"), "unequal", false, 32); cmptst(field.newDfp("0"), snan, "unequal", false, 33); cmptst(field.newDfp("0"), qnan, "unequal", false, 34); cmptst(qnan, pinf, "unequal", false, 35); cmptst(snan, pinf, "unequal", false, 36); cmptst(pinf, snan, "unequal", false, 37); cmptst(pinf, qnan, "unequal", false, 38); cmptst(qnan, ninf, "unequal", false, 39); cmptst(snan, ninf, "unequal", false, 40); cmptst(ninf, snan, "unequal", false, 41); cmptst(ninf, qnan, "unequal", false, 42); cmptst(qnan, field.newDfp("-1"), "unequal", false, 43); cmptst(snan, field.newDfp("-1"), "unequal", false, 44); cmptst(field.newDfp("-1"), snan, "unequal", false, 45); cmptst(field.newDfp("-1"), qnan, "unequal", false, 46); cmptst(qnan, field.newDfp("1"), "unequal", false, 47); cmptst(snan, field.newDfp("1"), "unequal", false, 48); cmptst(field.newDfp("1"), snan, "unequal", false, 49); cmptst(field.newDfp("1"), qnan, "unequal", false, 50); cmptst(snan.negate(), snan, "unequal", false, 51); cmptst(qnan.negate(), qnan, "unequal", false, 52); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare unequal flags = "+field.getIEEEFlags()); // // Tests for lessThan -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "lessThan", false, 1); // 0 < 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "lessThan", false, 2); // 0 < -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "lessThan", false, 3); // -0 < -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "lessThan", false, 4); // -0 < 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "lessThan", true, 5); // 0 < 1 cmptst(field.newDfp("1"), field.newDfp("0"), "lessThan", false, 6); // 1 < 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "lessThan", true, 7); // -1 < 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "lessThan", false, 8); // 0 < -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "lessThan", true, 9); // 0 < 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "lessThan", true, 10); // 0 < 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "lessThan", true, 11); // 0 < 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "lessThan", true, 12); // 0 < pinf cmptst(field.newDfp("0"), ninf, "lessThan", false, 13); // 0 < ninf cmptst(field.newDfp("-0"), pinf, "lessThan", true, 14); // -0 < pinf cmptst(field.newDfp("-0"), ninf, "lessThan", false, 15); // -0 < ninf cmptst(pinf, field.newDfp("0"), "lessThan", false, 16); // pinf < 0 cmptst(ninf, field.newDfp("0"), "lessThan", true, 17); // ninf < 0 cmptst(pinf, field.newDfp("-0"), "lessThan", false, 18); // pinf < -0 cmptst(ninf, field.newDfp("-0"), "lessThan", true, 19); // ninf < -0 cmptst(ninf, pinf, "lessThan", true, 19.10); // ninf < pinf cmptst(pinf, ninf, "lessThan", false, 19.11); // pinf < ninf cmptst(pinf, pinf, "lessThan", false, 19.12); // pinf < pinf cmptst(ninf, ninf, "lessThan", false, 19.13); // ninf < ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "lessThan", false, 20); // 1 < 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "lessThan", false, 21); // 1 < -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "lessThan", false, 22); // -1 < -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "lessThan", true, 23); // 1 < 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 < 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "lessThan", false, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "lessThan", false, 25); // check some nans -- nans shouldnt be lessThan to anything cmptst(snan, snan, "lessThan", false, 27); cmptst(qnan, qnan, "lessThan", false, 28); cmptst(snan, qnan, "lessThan", false, 29); cmptst(qnan, snan, "lessThan", false, 30); cmptst(qnan, field.newDfp("0"), "lessThan", false, 31); cmptst(snan, field.newDfp("0"), "lessThan", false, 32); cmptst(field.newDfp("0"), snan, "lessThan", false, 33); cmptst(field.newDfp("0"), qnan, "lessThan", false, 34); cmptst(qnan, pinf, "lessThan", false, 35); cmptst(snan, pinf, "lessThan", false, 36); cmptst(pinf, snan, "lessThan", false, 37); cmptst(pinf, qnan, "lessThan", false, 38); cmptst(qnan, ninf, "lessThan", false, 39); cmptst(snan, ninf, "lessThan", false, 40); cmptst(ninf, snan, "lessThan", false, 41); cmptst(ninf, qnan, "lessThan", false, 42); cmptst(qnan, field.newDfp("-1"), "lessThan", false, 43); cmptst(snan, field.newDfp("-1"), "lessThan", false, 44); cmptst(field.newDfp("-1"), snan, "lessThan", false, 45); cmptst(field.newDfp("-1"), qnan, "lessThan", false, 46); cmptst(qnan, field.newDfp("1"), "lessThan", false, 47); cmptst(snan, field.newDfp("1"), "lessThan", false, 48); cmptst(field.newDfp("1"), snan, "lessThan", false, 49); cmptst(field.newDfp("1"), qnan, "lessThan", false, 50); cmptst(snan.negate(), snan, "lessThan", false, 51); cmptst(qnan.negate(), qnan, "lessThan", false, 52); //lessThan compares with nans should raise FLAG_INVALID if (field.getIEEEFlags() != DfpField.FLAG_INVALID) Assert.fail("assersion failed. compare lessThan flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); // // Tests for greaterThan -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "greaterThan", false, 1); // 0 > 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "greaterThan", false, 2); // 0 > -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "greaterThan", false, 3); // -0 > -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "greaterThan", false, 4); // -0 > 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "greaterThan", false, 5); // 0 > 1 cmptst(field.newDfp("1"), field.newDfp("0"), "greaterThan", true, 6); // 1 > 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "greaterThan", false, 7); // -1 > 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "greaterThan", true, 8); // 0 > -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "greaterThan", false, 9); // 0 > 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "greaterThan", false, 10); // 0 > 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "greaterThan", false, 11); // 0 > 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "greaterThan", false, 12); // 0 > pinf cmptst(field.newDfp("0"), ninf, "greaterThan", true, 13); // 0 > ninf cmptst(field.newDfp("-0"), pinf, "greaterThan", false, 14); // -0 > pinf cmptst(field.newDfp("-0"), ninf, "greaterThan", true, 15); // -0 > ninf cmptst(pinf, field.newDfp("0"), "greaterThan", true, 16); // pinf > 0 cmptst(ninf, field.newDfp("0"), "greaterThan", false, 17); // ninf > 0 cmptst(pinf, field.newDfp("-0"), "greaterThan", true, 18); // pinf > -0 cmptst(ninf, field.newDfp("-0"), "greaterThan", false, 19); // ninf > -0 cmptst(ninf, pinf, "greaterThan", false, 19.10); // ninf > pinf cmptst(pinf, ninf, "greaterThan", true, 19.11); // pinf > ninf cmptst(pinf, pinf, "greaterThan", false, 19.12); // pinf > pinf cmptst(ninf, ninf, "greaterThan", false, 19.13); // ninf > ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "greaterThan", false, 20); // 1 > 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "greaterThan", true, 21); // 1 > -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "greaterThan", false, 22); // -1 > -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "greaterThan", false, 23); // 1 > 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 > 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "greaterThan", true, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "greaterThan", false, 25); // check some nans -- nans shouldnt be greaterThan to anything cmptst(snan, snan, "greaterThan", false, 27); cmptst(qnan, qnan, "greaterThan", false, 28); cmptst(snan, qnan, "greaterThan", false, 29); cmptst(qnan, snan, "greaterThan", false, 30); cmptst(qnan, field.newDfp("0"), "greaterThan", false, 31); cmptst(snan, field.newDfp("0"), "greaterThan", false, 32); cmptst(field.newDfp("0"), snan, "greaterThan", false, 33); cmptst(field.newDfp("0"), qnan, "greaterThan", false, 34); cmptst(qnan, pinf, "greaterThan", false, 35); cmptst(snan, pinf, "greaterThan", false, 36); cmptst(pinf, snan, "greaterThan", false, 37); cmptst(pinf, qnan, "greaterThan", false, 38); cmptst(qnan, ninf, "greaterThan", false, 39); cmptst(snan, ninf, "greaterThan", false, 40); cmptst(ninf, snan, "greaterThan", false, 41); cmptst(ninf, qnan, "greaterThan", false, 42); cmptst(qnan, field.newDfp("-1"), "greaterThan", false, 43); cmptst(snan, field.newDfp("-1"), "greaterThan", false, 44); cmptst(field.newDfp("-1"), snan, "greaterThan", false, 45); cmptst(field.newDfp("-1"), qnan, "greaterThan", false, 46); cmptst(qnan, field.newDfp("1"), "greaterThan", false, 47); cmptst(snan, field.newDfp("1"), "greaterThan", false, 48); cmptst(field.newDfp("1"), snan, "greaterThan", false, 49); cmptst(field.newDfp("1"), qnan, "greaterThan", false, 50); cmptst(snan.negate(), snan, "greaterThan", false, 51); cmptst(qnan.negate(), qnan, "greaterThan", false, 52); //greaterThan compares with nans should raise FLAG_INVALID if (field.getIEEEFlags() != DfpField.FLAG_INVALID) Assert.fail("assersion failed. compare greaterThan flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); } // // Test multiplication // @Test public void testMultiply() { test(field.newDfp("1").multiply(field.newDfp("1")), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #1"); test(field.newDfp("1").multiply(1), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #2"); test(field.newDfp("-1").multiply(field.newDfp("1")), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #3"); test(field.newDfp("-1").multiply(1), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #4"); // basic tests with integers test(field.newDfp("2").multiply(field.newDfp("3")), field.newDfp("6"), 0, "Multiply #5"); test(field.newDfp("2").multiply(3), field.newDfp("6"), 0, "Multiply #6"); test(field.newDfp("-2").multiply(field.newDfp("3")), field.newDfp("-6"), 0, "Multiply #7"); test(field.newDfp("-2").multiply(3), field.newDfp("-6"), 0, "Multiply #8"); test(field.newDfp("2").multiply(field.newDfp("-3")), field.newDfp("-6"), 0, "Multiply #9"); test(field.newDfp("-2").multiply(field.newDfp("-3")), field.newDfp("6"), 0, "Multiply #10"); //multiply by zero test(field.newDfp("-2").multiply(field.newDfp("0")), field.newDfp("-0"), 0, "Multiply #11"); test(field.newDfp("-2").multiply(0), field.newDfp("-0"), 0, "Multiply #12"); test(field.newDfp("2").multiply(field.newDfp("0")), field.newDfp("0"), 0, "Multiply #13"); test(field.newDfp("2").multiply(0), field.newDfp("0"), 0, "Multiply #14"); test(field.newDfp("2").multiply(pinf), pinf, 0, "Multiply #15"); test(field.newDfp("2").multiply(ninf), ninf, 0, "Multiply #16"); test(field.newDfp("-2").multiply(pinf), ninf, 0, "Multiply #17"); test(field.newDfp("-2").multiply(ninf), pinf, 0, "Multiply #18"); test(ninf.multiply(field.newDfp("-2")), pinf, 0, "Multiply #18.1"); test(field.newDfp("5e131071").multiply(2), pinf, DfpField.FLAG_OVERFLOW, "Multiply #19"); test(field.newDfp("5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("9.9999999999999950000e131071"), 0, "Multiply #20"); test(field.newDfp("-5e131071").multiply(2), ninf, DfpField.FLAG_OVERFLOW, "Multiply #22"); test(field.newDfp("-5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("-9.9999999999999950000e131071"), 0, "Multiply #23"); test(field.newDfp("1e-65539").multiply(field.newDfp("1e-65539")), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "Multiply #24"); test(field.newDfp("1").multiply(nan), nan, 0, "Multiply #25"); test(nan.multiply(field.newDfp("1")), nan, 0, "Multiply #26"); test(nan.multiply(pinf), nan, 0, "Multiply #27"); test(pinf.multiply(nan), nan, 0, "Multiply #27"); test(pinf.multiply(field.newDfp("0")), nan, DfpField.FLAG_INVALID, "Multiply #28"); test(field.newDfp("0").multiply(pinf), nan, DfpField.FLAG_INVALID, "Multiply #29"); test(pinf.multiply(pinf), pinf, 0, "Multiply #30"); test(ninf.multiply(pinf), ninf, 0, "Multiply #31"); test(pinf.multiply(ninf), ninf, 0, "Multiply #32"); test(ninf.multiply(ninf), pinf, 0, "Multiply #33"); test(pinf.multiply(1), pinf, 0, "Multiply #34"); test(pinf.multiply(0), nan, DfpField.FLAG_INVALID, "Multiply #35"); test(nan.multiply(1), nan, 0, "Multiply #36"); test(field.newDfp("1").multiply(10000), field.newDfp("10000"), 0, "Multiply #37"); test(field.newDfp("2").multiply(1000000), field.newDfp("2000000"), 0, "Multiply #38"); test(field.newDfp("1").multiply(-1), field.newDfp("-1"), 0, "Multiply #39"); } @Test public void testDivide() { test(field.newDfp("1").divide(nan), // divide by NaN = NaN nan, 0, "Divide #1"); test(nan.divide(field.newDfp("1")), // NaN / number = NaN nan, 0, "Divide #2"); test(pinf.divide(field.newDfp("1")), pinf, 0, "Divide #3"); test(pinf.divide(field.newDfp("-1")), ninf, 0, "Divide #4"); test(pinf.divide(pinf), nan, DfpField.FLAG_INVALID, "Divide #5"); test(ninf.divide(pinf), nan, DfpField.FLAG_INVALID, "Divide #6"); test(pinf.divide(ninf), nan, DfpField.FLAG_INVALID, "Divide #7"); test(ninf.divide(ninf), nan, DfpField.FLAG_INVALID, "Divide #8"); test(field.newDfp("0").divide(field.newDfp("0")), nan, DfpField.FLAG_DIV_ZERO, "Divide #9"); test(field.newDfp("1").divide(field.newDfp("0")), pinf, DfpField.FLAG_DIV_ZERO, "Divide #10"); test(field.newDfp("1").divide(field.newDfp("-0")), ninf, DfpField.FLAG_DIV_ZERO, "Divide #11"); test(field.newDfp("-1").divide(field.newDfp("0")), ninf, DfpField.FLAG_DIV_ZERO, "Divide #12"); test(field.newDfp("-1").divide(field.newDfp("-0")), pinf, DfpField.FLAG_DIV_ZERO, "Divide #13"); test(field.newDfp("1").divide(field.newDfp("3")), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "Divide #14"); test(field.newDfp("1").divide(field.newDfp("6")), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "Divide #15"); test(field.newDfp("10").divide(field.newDfp("6")), field.newDfp("1.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #16"); test(field.newDfp("100").divide(field.newDfp("6")), field.newDfp("16.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #17"); test(field.newDfp("1000").divide(field.newDfp("6")), field.newDfp("166.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #18"); test(field.newDfp("10000").divide(field.newDfp("6")), field.newDfp("1666.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #19"); test(field.newDfp("1").divide(field.newDfp("1")), field.newDfp("1"), 0, "Divide #20"); test(field.newDfp("1").divide(field.newDfp("-1")), field.newDfp("-1"), 0, "Divide #21"); test(field.newDfp("-1").divide(field.newDfp("1")), field.newDfp("-1"), 0, "Divide #22"); test(field.newDfp("-1").divide(field.newDfp("-1")), field.newDfp("1"), 0, "Divide #23"); test(field.newDfp("1e-65539").divide(field.newDfp("1e65539")), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "Divide #24"); test(field.newDfp("1e65539").divide(field.newDfp("1e-65539")), pinf, DfpField.FLAG_OVERFLOW, "Divide #24"); test(field.newDfp("2").divide(field.newDfp("1.5")), // test trial-divisor too high field.newDfp("1.3333333333333333"), DfpField.FLAG_INEXACT, "Divide #25"); test(field.newDfp("2").divide(pinf), field.newDfp("0"), 0, "Divide #26"); test(field.newDfp("2").divide(ninf), field.newDfp("-0"), 0, "Divide #27"); test(field.newDfp("0").divide(field.newDfp("1")), field.newDfp("0"), 0, "Divide #28"); } @Test public void testReciprocal() { test(nan.reciprocal(), nan, 0, "Reciprocal #1"); test(field.newDfp("0").reciprocal(), pinf, DfpField.FLAG_DIV_ZERO, "Reciprocal #2"); test(field.newDfp("-0").reciprocal(), ninf, DfpField.FLAG_DIV_ZERO, "Reciprocal #3"); test(field.newDfp("3").reciprocal(), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "Reciprocal #4"); test(field.newDfp("6").reciprocal(), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "Reciprocal #5"); test(field.newDfp("1").reciprocal(), field.newDfp("1"), 0, "Reciprocal #6"); test(field.newDfp("-1").reciprocal(), field.newDfp("-1"), 0, "Reciprocal #7"); test(pinf.reciprocal(), field.newDfp("0"), 0, "Reciprocal #8"); test(ninf.reciprocal(), field.newDfp("-0"), 0, "Reciprocal #9"); } @Test public void testDivideInt() { test(nan.divide(1), // NaN / number = NaN nan, 0, "DivideInt #1"); test(pinf.divide(1), pinf, 0, "DivideInt #2"); test(field.newDfp("0").divide(0), nan, DfpField.FLAG_DIV_ZERO, "DivideInt #3"); test(field.newDfp("1").divide(0), pinf, DfpField.FLAG_DIV_ZERO, "DivideInt #4"); test(field.newDfp("-1").divide(0), ninf, DfpField.FLAG_DIV_ZERO, "DivideInt #5"); test(field.newDfp("1").divide(3), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "DivideInt #6"); test(field.newDfp("1").divide(6), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #7"); test(field.newDfp("10").divide(6), field.newDfp("1.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #8"); test(field.newDfp("100").divide(6), field.newDfp("16.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #9"); test(field.newDfp("1000").divide(6), field.newDfp("166.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #10"); test(field.newDfp("10000").divide(6), field.newDfp("1666.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #20"); test(field.newDfp("1").divide(1), field.newDfp("1"), 0, "DivideInt #21"); test(field.newDfp("1e-131077").divide(10), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "DivideInt #22"); test(field.newDfp("0").divide(1), field.newDfp("0"), 0, "DivideInt #23"); test(field.newDfp("1").divide(10000), nan, DfpField.FLAG_INVALID, "DivideInt #24"); test(field.newDfp("1").divide(-1), nan, DfpField.FLAG_INVALID, "DivideInt #25"); } @Test public void testNextAfter() { test(field.newDfp("1").nextAfter(pinf), field.newDfp("1.0000000000000001"), 0, "NextAfter #1"); test(field.newDfp("1.0000000000000001").nextAfter(ninf), field.newDfp("1"), 0, "NextAfter #1.5"); test(field.newDfp("1").nextAfter(ninf), field.newDfp("0.99999999999999999999"), 0, "NextAfter #2"); test(field.newDfp("0.99999999999999999999").nextAfter(field.newDfp("2")), field.newDfp("1"), 0, "NextAfter #3"); test(field.newDfp("-1").nextAfter(ninf), field.newDfp("-1.0000000000000001"), 0, "NextAfter #4"); test(field.newDfp("-1").nextAfter(pinf), field.newDfp("-0.99999999999999999999"), 0, "NextAfter #5"); test(field.newDfp("-0.99999999999999999999").nextAfter(field.newDfp("-2")), field.newDfp("-1"), 0, "NextAfter #6"); test(field.newDfp("2").nextAfter(field.newDfp("2")), field.newDfp("2"), 0, "NextAfter #7"); test(field.newDfp("0").nextAfter(field.newDfp("0")), field.newDfp("0"), 0, "NextAfter #8"); test(field.newDfp("-2").nextAfter(field.newDfp("-2")), field.newDfp("-2"), 0, "NextAfter #9"); test(field.newDfp("0").nextAfter(field.newDfp("1")), field.newDfp("1e-131092"), DfpField.FLAG_UNDERFLOW, "NextAfter #10"); test(field.newDfp("0").nextAfter(field.newDfp("-1")), field.newDfp("-1e-131092"), DfpField.FLAG_UNDERFLOW, "NextAfter #11"); test(field.newDfp("-1e-131092").nextAfter(pinf), field.newDfp("-0"), DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #12"); test(field.newDfp("1e-131092").nextAfter(ninf), field.newDfp("0"), DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #13"); test(field.newDfp("9.9999999999999999999e131078").nextAfter(pinf), pinf, DfpField.FLAG_OVERFLOW|DfpField.FLAG_INEXACT, "Next After #14"); } @Test public void testToString() { Assert.assertEquals("toString #1", "Infinity", pinf.toString()); Assert.assertEquals("toString #2", "-Infinity", ninf.toString()); Assert.assertEquals("toString #3", "NaN", nan.toString()); Assert.assertEquals("toString #4", "NaN", field.newDfp((byte) 1, Dfp.QNAN).toString()); Assert.assertEquals("toString #5", "NaN", field.newDfp((byte) 1, Dfp.SNAN).toString()); Assert.assertEquals("toString #6", "1.2300000000000000e100", field.newDfp("1.23e100").toString()); Assert.assertEquals("toString #7", "-1.2300000000000000e100", field.newDfp("-1.23e100").toString()); Assert.assertEquals("toString #8", "12345678.1234", field.newDfp("12345678.1234").toString()); Assert.assertEquals("toString #9", "0.00001234", field.newDfp("0.00001234").toString()); } @Test public void testRound() { field.setRoundingMode(DfpField.RoundingMode.ROUND_DOWN); // Round down test(field.newDfp("12345678901234567890").add(field.newDfp("0.9")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #1"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.99999999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #2"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.99999999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #3"); field.setRoundingMode(DfpField.RoundingMode.ROUND_UP); // Round up test(field.newDfp("12345678901234567890").add(field.newDfp("0.1")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #4"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.0001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #5"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.1")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #6"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.0001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #7"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_UP); // Round half up test(field.newDfp("12345678901234567890").add(field.newDfp("0.4999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #8"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #9"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.4999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #10"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #11"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_DOWN); // Round half down test(field.newDfp("12345678901234567890").add(field.newDfp("0.5001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #12"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #13"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #14"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #15"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_ODD); // Round half odd test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #16"); test(field.newDfp("12345678901234567891").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #17"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #18"); test(field.newDfp("-12345678901234567891").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #19"); field.setRoundingMode(DfpField.RoundingMode.ROUND_CEIL); // Round ceil test(field.newDfp("12345678901234567890").add(field.newDfp("0.0001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #20"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.9999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #21"); field.setRoundingMode(DfpField.RoundingMode.ROUND_FLOOR); // Round floor test(field.newDfp("12345678901234567890").add(field.newDfp("0.9999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #22"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.0001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #23"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_EVEN); // reset } @Test public void testCeil() { test(field.newDfp("1234.0000000000000001").ceil(), field.newDfp("1235"), DfpField.FLAG_INEXACT, "Ceil #1"); } @Test public void testFloor() { test(field.newDfp("1234.9999999999999999").floor(), field.newDfp("1234"), DfpField.FLAG_INEXACT, "Floor #1"); } @Test public void testRint() { test(field.newDfp("1234.50000000001").rint(), field.newDfp("1235"), DfpField.FLAG_INEXACT, "Rint #1"); test(field.newDfp("1234.5000").rint(), field.newDfp("1234"), DfpField.FLAG_INEXACT, "Rint #2"); test(field.newDfp("1235.5000").rint(), field.newDfp("1236"), DfpField.FLAG_INEXACT, "Rint #3"); } @Test public void testCopySign() { test(Dfp.copysign(field.newDfp("1234."), field.newDfp("-1")), field.newDfp("-1234"), 0, "CopySign #1"); test(Dfp.copysign(field.newDfp("-1234."), field.newDfp("-1")), field.newDfp("-1234"), 0, "CopySign #2"); test(Dfp.copysign(field.newDfp("-1234."), field.newDfp("1")), field.newDfp("1234"), 0, "CopySign #3"); test(Dfp.copysign(field.newDfp("1234."), field.newDfp("1")), field.newDfp("1234"), 0, "CopySign #4"); } @Test public void testIntValue() { Assert.assertEquals("intValue #1", 1234, field.newDfp("1234").intValue()); Assert.assertEquals("intValue #2", -1234, field.newDfp("-1234").intValue()); Assert.assertEquals("intValue #3", 1234, field.newDfp("1234.5").intValue()); Assert.assertEquals("intValue #4", 1235, field.newDfp("1234.500001").intValue()); Assert.assertEquals("intValue #5", 2147483647, field.newDfp("1e1000").intValue()); Assert.assertEquals("intValue #6", -2147483648, field.newDfp("-1e1000").intValue()); } @Test public void testLog10K() { Assert.assertEquals("log10K #1", 1, field.newDfp("123456").log10K()); Assert.assertEquals("log10K #2", 2, field.newDfp("123456789").log10K()); Assert.assertEquals("log10K #3", 0, field.newDfp("2").log10K()); Assert.assertEquals("log10K #3", 0, field.newDfp("1").log10K()); Assert.assertEquals("log10K #4", -1, field.newDfp("0.1").log10K()); } @Test public void testPower10K() { Dfp d = field.newDfp(); test(d.power10K(0), field.newDfp("1"), 0, "Power10 #1"); test(d.power10K(1), field.newDfp("10000"), 0, "Power10 #2"); test(d.power10K(2), field.newDfp("100000000"), 0, "Power10 #3"); test(d.power10K(-1), field.newDfp("0.0001"), 0, "Power10 #4"); test(d.power10K(-2), field.newDfp("0.00000001"), 0, "Power10 #5"); test(d.power10K(-3), field.newDfp("0.000000000001"), 0, "Power10 #6"); } @Test public void testLog10() { Assert.assertEquals("log10 #1", 1, field.newDfp("12").log10()); Assert.assertEquals("log10 #2", 2, field.newDfp("123").log10()); Assert.assertEquals("log10 #3", 3, field.newDfp("1234").log10()); Assert.assertEquals("log10 #4", 4, field.newDfp("12345").log10()); Assert.assertEquals("log10 #5", 5, field.newDfp("123456").log10()); Assert.assertEquals("log10 #6", 6, field.newDfp("1234567").log10()); Assert.assertEquals("log10 #6", 7, field.newDfp("12345678").log10()); Assert.assertEquals("log10 #7", 8, field.newDfp("123456789").log10()); Assert.assertEquals("log10 #8", 9, field.newDfp("1234567890").log10()); Assert.assertEquals("log10 #9", 10, field.newDfp("12345678901").log10()); Assert.assertEquals("log10 #10", 11, field.newDfp("123456789012").log10()); Assert.assertEquals("log10 #11", 12, field.newDfp("1234567890123").log10()); Assert.assertEquals("log10 #12", 0, field.newDfp("2").log10()); Assert.assertEquals("log10 #13", 0, field.newDfp("1").log10()); Assert.assertEquals("log10 #14", -1, field.newDfp("0.12").log10()); Assert.assertEquals("log10 #15", -2, field.newDfp("0.012").log10()); } @Test public void testPower10() { Dfp d = field.newDfp(); test(d.power10(0), field.newDfp("1"), 0, "Power10 #1"); test(d.power10(1), field.newDfp("10"), 0, "Power10 #2"); test(d.power10(2), field.newDfp("100"), 0, "Power10 #3"); test(d.power10(3), field.newDfp("1000"), 0, "Power10 #4"); test(d.power10(4), field.newDfp("10000"), 0, "Power10 #5"); test(d.power10(5), field.newDfp("100000"), 0, "Power10 #6"); test(d.power10(6), field.newDfp("1000000"), 0, "Power10 #7"); test(d.power10(7), field.newDfp("10000000"), 0, "Power10 #8"); test(d.power10(8), field.newDfp("100000000"), 0, "Power10 #9"); test(d.power10(9), field.newDfp("1000000000"), 0, "Power10 #10"); test(d.power10(-1), field.newDfp(".1"), 0, "Power10 #11"); test(d.power10(-2), field.newDfp(".01"), 0, "Power10 #12"); test(d.power10(-3), field.newDfp(".001"), 0, "Power10 #13"); test(d.power10(-4), field.newDfp(".0001"), 0, "Power10 #14"); test(d.power10(-5), field.newDfp(".00001"), 0, "Power10 #15"); test(d.power10(-6), field.newDfp(".000001"), 0, "Power10 #16"); test(d.power10(-7), field.newDfp(".0000001"), 0, "Power10 #17"); test(d.power10(-8), field.newDfp(".00000001"), 0, "Power10 #18"); test(d.power10(-9), field.newDfp(".000000001"), 0, "Power10 #19"); test(d.power10(-10), field.newDfp(".0000000001"), 0, "Power10 #20"); } @Test public void testRemainder() { test(field.newDfp("10").remainder(field.newDfp("3")), field.newDfp("1"), DfpField.FLAG_INEXACT, "Remainder #1"); test(field.newDfp("9").remainder(field.newDfp("3")), field.newDfp("0"), 0, "Remainder #2"); test(field.newDfp("-9").remainder(field.newDfp("3")), field.newDfp("-0"), 0, "Remainder #3"); } @Test public void testSqrt() { test(field.newDfp("0").sqrt(), field.newDfp("0"), 0, "Sqrt #1"); test(field.newDfp("-0").sqrt(), field.newDfp("-0"), 0, "Sqrt #2"); test(field.newDfp("1").sqrt(), field.newDfp("1"), 0, "Sqrt #3"); test(field.newDfp("2").sqrt(), field.newDfp("1.4142135623730950"), DfpField.FLAG_INEXACT, "Sqrt #4"); test(field.newDfp("3").sqrt(), field.newDfp("1.7320508075688773"), DfpField.FLAG_INEXACT, "Sqrt #5"); test(field.newDfp("5").sqrt(), field.newDfp("2.2360679774997897"), DfpField.FLAG_INEXACT, "Sqrt #6"); test(field.newDfp("500").sqrt(), field.newDfp("22.3606797749978970"), DfpField.FLAG_INEXACT, "Sqrt #6.2"); test(field.newDfp("50000").sqrt(), field.newDfp("223.6067977499789696"), DfpField.FLAG_INEXACT, "Sqrt #6.3"); test(field.newDfp("-1").sqrt(), nan, DfpField.FLAG_INVALID, "Sqrt #7"); test(pinf.sqrt(), pinf, 0, "Sqrt #8"); test(field.newDfp((byte) 1, Dfp.QNAN).sqrt(), nan, 0, "Sqrt #9"); test(field.newDfp((byte) 1, Dfp.SNAN).sqrt(), nan, DfpField.FLAG_INVALID, "Sqrt #9"); } @Test public void testIssue567() { DfpField field = new DfpField(100); Assert.assertEquals(0.0, field.getZero().toDouble(), Precision.SAFE_MIN); Assert.assertEquals(0.0, field.newDfp(0.0).toDouble(), Precision.SAFE_MIN); Assert.assertEquals(-1, FastMath.copySign(1, field.newDfp(-0.0).toDouble()), Precision.EPSILON); Assert.assertEquals(+1, FastMath.copySign(1, field.newDfp(+0.0).toDouble()), Precision.EPSILON); } @Test public void testIsZero() { Assert.assertTrue(field.getZero().isZero()); Assert.assertTrue(field.getZero().negate().isZero()); Assert.assertTrue(field.newDfp(+0.0).isZero()); Assert.assertTrue(field.newDfp(-0.0).isZero()); Assert.assertFalse(field.newDfp(1.0e-90).isZero()); Assert.assertFalse(nan.isZero()); Assert.assertFalse(nan.negate().isZero()); Assert.assertFalse(pinf.isZero()); Assert.assertFalse(pinf.negate().isZero()); Assert.assertFalse(ninf.isZero()); Assert.assertFalse(ninf.negate().isZero()); } @Test public void testSignPredicates() { Assert.assertTrue(field.getZero().negativeOrNull()); Assert.assertTrue(field.getZero().positiveOrNull()); Assert.assertFalse(field.getZero().strictlyNegative()); Assert.assertFalse(field.getZero().strictlyPositive()); Assert.assertTrue(field.getZero().negate().negativeOrNull()); Assert.assertTrue(field.getZero().negate().positiveOrNull()); Assert.assertFalse(field.getZero().negate().strictlyNegative()); Assert.assertFalse(field.getZero().negate().strictlyPositive()); Assert.assertFalse(field.getOne().negativeOrNull()); Assert.assertTrue(field.getOne().positiveOrNull()); Assert.assertFalse(field.getOne().strictlyNegative()); Assert.assertTrue(field.getOne().strictlyPositive()); Assert.assertTrue(field.getOne().negate().negativeOrNull()); Assert.assertFalse(field.getOne().negate().positiveOrNull()); Assert.assertTrue(field.getOne().negate().strictlyNegative()); Assert.assertFalse(field.getOne().negate().strictlyPositive()); Assert.assertFalse(nan.negativeOrNull()); Assert.assertFalse(nan.positiveOrNull()); Assert.assertFalse(nan.strictlyNegative()); Assert.assertFalse(nan.strictlyPositive()); Assert.assertFalse(nan.negate().negativeOrNull()); Assert.assertFalse(nan.negate().positiveOrNull()); Assert.assertFalse(nan.negate().strictlyNegative()); Assert.assertFalse(nan.negate().strictlyPositive()); Assert.assertFalse(pinf.negativeOrNull()); Assert.assertTrue(pinf.positiveOrNull()); Assert.assertFalse(pinf.strictlyNegative()); Assert.assertTrue(pinf.strictlyPositive()); Assert.assertTrue(pinf.negate().negativeOrNull()); Assert.assertFalse(pinf.negate().positiveOrNull()); Assert.assertTrue(pinf.negate().strictlyNegative()); Assert.assertFalse(pinf.negate().strictlyPositive()); Assert.assertTrue(ninf.negativeOrNull()); Assert.assertFalse(ninf.positiveOrNull()); Assert.assertTrue(ninf.strictlyNegative()); Assert.assertFalse(ninf.strictlyPositive()); Assert.assertFalse(ninf.negate().negativeOrNull()); Assert.assertTrue(ninf.negate().positiveOrNull()); Assert.assertFalse(ninf.negate().strictlyNegative()); Assert.assertTrue(ninf.negate().strictlyPositive()); } }
public void testDateTimeCreation_london() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); DateTime base = new DateTime(2011, 10, 30, 1, 15, zone); assertEquals("2011-10-30T01:15:00.000+01:00", base.toString()); assertEquals("2011-10-30T01:15:00.000Z", base.plusHours(1).toString()); }
org.joda.time.TestDateTimeZoneCutover::testDateTimeCreation_london
src/test/java/org/joda/time/TestDateTimeZoneCutover.java
1,267
src/test/java/org/joda/time/TestDateTimeZoneCutover.java
testDateTimeCreation_london
/* * Copyright 2001-2007 Stephen Colebourne * * 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 org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.tz.DateTimeZoneBuilder; /** * This class is a JUnit test for DateTimeZone. * * @author Stephen Colebourne */ public class TestDateTimeZoneCutover extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeZoneCutover.class); } public TestDateTimeZoneCutover(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- // The behaviour of getOffsetFromLocal is defined in its javadoc // However, this definition doesn't work for all DateTimeField operations /** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */ private static long CUTOVER_GAZA = 1175378400000L; private static int OFFSET_GAZA = 7200000; // +02:00 private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600); //----------------------------------------------------------------------- public void test_MockGazaIsCorrect() { DateTime pre = new DateTime(CUTOVER_GAZA - 1L, MOCK_GAZA); assertEquals("2007-03-31T23:59:59.999+02:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_GAZA + 1L, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Gaza() { doTest_getOffsetFromLocal_Gaza(-1, 23, 0, "2007-03-31T23:00:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(-1, 23, 30, "2007-03-31T23:30:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 2, 0, "2007-04-01T02:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 3, 0, "2007-04-01T03:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 4, 0, "2007-04-01T04:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 5, 0, "2007-04-01T05:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 6, 0, "2007-04-01T06:00:00.000+03:00"); } private void doTest_getOffsetFromLocal_Gaza(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_GAZA.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_GAZA); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_roundCeiling_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T20:00:00.000+02:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_setHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_DateTime_minusHour_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000+02:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000+02:00", minus9.toString()); } public void test_DateTime_plusHour_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T16:00:00.000+02:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000+02:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000+02:00", minus2.toString()); } public void test_DateTime_plusDay_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:00:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:30:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000+03:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Gaza() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-30T00:00:00.000+03:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_MutableDateTime_withZoneRetainFields_Gaza() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", dt.toString()); } public void test_LocalDate_new_Gaza() { LocalDate date1 = new LocalDate(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_GAZA - 1, MOCK_GAZA); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Gaza() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Gaza() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Gaza() { new DateTime(2007, 3, 31, 19, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 21, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 22, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_GAZA); } public void test_DateTime_parse_Gaza() { try { new DateTime("2007-04-01T00:00", MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- /** Mock zone simulating America/Grand_Turk cutover at midnight 2007-04-01 */ private static long CUTOVER_TURK = 1175403600000L; private static int OFFSET_TURK = -18000000; // -05:00 private static final DateTimeZone MOCK_TURK = new MockZone(CUTOVER_TURK, OFFSET_TURK, 3600); //----------------------------------------------------------------------- public void test_MockTurkIsCorrect() { DateTime pre = new DateTime(CUTOVER_TURK - 1L, MOCK_TURK); assertEquals("2007-03-31T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_TURK + 1L, MOCK_TURK); assertEquals("2007-04-01T01:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_Turk() { doTest_getOffsetFromLocal_Turk(-1, 23, 0, "2007-03-31T23:00:00.000-05:00"); doTest_getOffsetFromLocal_Turk(-1, 23, 30, "2007-03-31T23:30:00.000-05:00"); doTest_getOffsetFromLocal_Turk(0, 0, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 0, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 2, 0, "2007-04-01T02:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 3, 0, "2007-04-01T03:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 4, 0, "2007-04-01T04:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 5, 0, "2007-04-01T05:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 6, 0, "2007-04-01T06:00:00.000-04:00"); } private void doTest_getOffsetFromLocal_Turk(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_TURK.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_TURK); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloorNotDST_Turk() { DateTime dt = new DateTime(2007, 4, 2, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-02T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_Turk() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T20:00:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_setHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_DateTime_minusHour_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000-04:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000-05:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000-05:00", minus9.toString()); } public void test_DateTime_plusHour_Turk() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T16:00:00.000-05:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000-05:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000-04:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000-04:00", plus9.toString()); } public void test_DateTime_minusDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000-05:00", minus2.toString()); } public void test_DateTime_plusDay_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:30:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000-04:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Turk() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-30T00:00:00.000-04:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Turk() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_MutableDateTime_setZoneRetainFields_Turk() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", dt.toString()); } public void test_LocalDate_new_Turk() { LocalDate date1 = new LocalDate(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_TURK - 1, MOCK_TURK); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Turk() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Turk() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Turk() { new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 4, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 5, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 6, 0, 0, 0, MOCK_TURK); } public void test_DateTime_parse_Turk() { try { new DateTime("2007-04-01T00:00", MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 03:00 on 2007-03-11 */ private static long CUTOVER_NEW_YORK_SPRING = 1173596400000L; // 2007-03-11T03:00:00.000-04:00 private static final DateTimeZone ZONE_NEW_YORK = DateTimeZone.forID("America/New_York"); // DateTime x = new DateTime(2007, 1, 1, 0, 0, 0, 0, ZONE_NEW_YORK); // System.out.println(ZONE_NEW_YORK.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_NEW_YORK.nextTransition(x.getMillis()), ZONE_NEW_YORK); // System.out.println(y); //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Spring() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_SPRING - 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T01:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_SPRING, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_SPRING + 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Spring() { doTest_getOffsetFromLocal(3, 11, 1, 0, "2007-03-11T01:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 1,30, "2007-03-11T01:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 4, 0, "2007-03-11T04:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 5, 0, "2007-03-11T05:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 6, 0, "2007-03-11T06:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 7, 0, "2007-03-11T07:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 8, 0, "2007-03-11T08:00:00.000-04:00", ZONE_NEW_YORK); } public void test_DateTime_setHourAcross_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-11T04:00:00.000-04:00", res.toString()); } public void test_DateTime_setHourForward_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T03:30:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T04:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T03:31:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 01:00 on 2007-11-04 */ private static long CUTOVER_NEW_YORK_AUTUMN = 1194156000000L; // 2007-11-04T01:00:00.000-05:00 //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_AUTUMN - 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:59:59.999-04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_AUTUMN, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.000-05:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_AUTUMN + 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.001-05:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Autumn() { doTest_getOffsetFromLocal(11, 4, 0, 0, "2007-11-04T00:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 0,30, "2007-11-04T00:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1, 0, "2007-11-04T01:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1,30, "2007-11-04T01:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2, 0, "2007-11-04T02:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2,30, "2007-11-04T02:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3, 0, "2007-11-04T03:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3,30, "2007-11-04T03:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 4, 0, "2007-11-04T04:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 5, 0, "2007-11-04T05:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 6, 0, "2007-11-04T06:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 7, 0, "2007-11-04T07:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 8, 0, "2007-11-04T08:00:00.000-05:00", ZONE_NEW_YORK); } public void test_DateTime_constructor_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); } public void test_DateTime_plusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 3, 18, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-03T18:00:00.000-04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-11-04T00:00:00.000-04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-11-04T01:00:00.000-04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-11-04T01:00:00.000-05:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-11-04T02:00:00.000-05:00", plus9.toString()); } public void test_DateTime_minusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T08:00:00.000-05:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-11-04T02:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-11-04T01:00:00.000-05:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-11-04T01:00:00.000-04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-11-04T00:00:00.000-04:00", minus9.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T02:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- /** Europe/Moscow cutover from 01:59 to 03:00 on 2007-03-25 */ private static long CUTOVER_MOSCOW_SPRING = 1174777200000L; // 2007-03-25T03:00:00.000+04:00 private static final DateTimeZone ZONE_MOSCOW = DateTimeZone.forID("Europe/Moscow"); //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Spring() { // DateTime x = new DateTime(2007, 7, 1, 0, 0, 0, 0, ZONE_MOSCOW); // System.out.println(ZONE_MOSCOW.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_MOSCOW.nextTransition(x.getMillis()), ZONE_MOSCOW); // System.out.println(y); DateTime pre = new DateTime(CUTOVER_MOSCOW_SPRING - 1L, ZONE_MOSCOW); assertEquals("2007-03-25T01:59:59.999+03:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_SPRING, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.000+04:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_SPRING + 1L, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.001+04:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Spring() { doTest_getOffsetFromLocal(3, 25, 1, 0, "2007-03-25T01:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 1,30, "2007-03-25T01:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 4, 0, "2007-03-25T04:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 5, 0, "2007-03-25T05:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 6, 0, "2007-03-25T06:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 7, 0, "2007-03-25T07:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 8, 0, "2007-03-25T08:00:00.000+04:00", ZONE_MOSCOW); } public void test_DateTime_setHourAcross_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-25T04:00:00.000+04:00", res.toString()); } public void test_DateTime_setHourForward_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 8, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T08:00:00.000+04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- /** America/New_York cutover from 02:59 to 02:00 on 2007-10-28 */ private static long CUTOVER_MOSCOW_AUTUMN = 1193526000000L; // 2007-10-28T02:00:00.000+03:00 //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_MOSCOW_AUTUMN - 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:59:59.999+04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_AUTUMN, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_AUTUMN + 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Autumn() { doTest_getOffsetFromLocal(10, 28, 0, 0, "2007-10-28T00:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 0,30, "2007-10-28T00:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1, 0, "2007-10-28T01:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1,30, "2007-10-28T01:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2, 0, "2007-10-28T02:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30, "2007-10-28T02:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30,59,999, "2007-10-28T02:30:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,998, "2007-10-28T02:59:59.998+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,999, "2007-10-28T02:59:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3, 0, "2007-10-28T03:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3,30, "2007-10-28T03:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 4, 0, "2007-10-28T04:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 5, 0, "2007-10-28T05:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 6, 0, "2007-10-28T06:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 7, 0, "2007-10-28T07:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 8, 0, "2007-10-28T08:00:00.000+03:00", ZONE_MOSCOW); } public void test_getOffsetFromLocal_Moscow_Autumn_overlap_mins() { for (int min = 0; min < 60; min++) { if (min < 10) { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:0" + min + ":00.000+04:00", ZONE_MOSCOW); } else { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:" + min + ":00.000+04:00", ZONE_MOSCOW); } } } public void test_DateTime_constructor_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 2, 30, ZONE_MOSCOW); assertEquals("2007-10-28T02:30:00.000+04:00", dt.toString()); } public void test_DateTime_plusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 27, 19, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-27T19:00:00.000+04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-10-28T01:00:00.000+04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-10-28T02:00:00.000+04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-10-28T02:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-10-28T03:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 9, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-28T09:00:00.000+03:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-10-28T03:00:00.000+03:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-10-28T02:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-10-28T02:00:00.000+04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-10-28T01:00:00.000+04:00", minus9.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/Guatemala cutover from 23:59 to 23:00 on 2006-09-30 */ private static long CUTOVER_GUATEMALA_AUTUMN = 1159678800000L; // 2006-09-30T23:00:00.000-06:00 private static final DateTimeZone ZONE_GUATEMALA = DateTimeZone.forID("America/Guatemala"); //----------------------------------------------------------------------- public void test_GuatemataIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_GUATEMALA_AUTUMN - 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GUATEMALA_AUTUMN, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.000-06:00", at.toString()); DateTime post = new DateTime(CUTOVER_GUATEMALA_AUTUMN + 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.001-06:00", post.toString()); } public void test_getOffsetFromLocal_Guatemata_Autumn() { doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0, 0, "2006-10-01T00:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0,30, "2006-10-01T00:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1, 0, "2006-10-01T01:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1,30, "2006-10-01T01:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2, 0, "2006-10-01T02:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2,30, "2006-10-01T02:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3, 0, "2006-10-01T03:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3,30, "2006-10-01T03:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4, 0, "2006-10-01T04:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4,30, "2006-10-01T04:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5, 0, "2006-10-01T05:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5,30, "2006-10-01T05:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6, 0, "2006-10-01T06:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6,30, "2006-10-01T06:30:00.000-06:00", ZONE_GUATEMALA); } public void test_DateTime_plusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 9, 30, 20, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-09-30T20:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusHours(1); assertEquals("2006-09-30T21:00:00.000-05:00", plus1.toString()); DateTime plus2 = dt.plusHours(2); assertEquals("2006-09-30T22:00:00.000-05:00", plus2.toString()); DateTime plus3 = dt.plusHours(3); assertEquals("2006-09-30T23:00:00.000-05:00", plus3.toString()); DateTime plus4 = dt.plusHours(4); assertEquals("2006-09-30T23:00:00.000-06:00", plus4.toString()); DateTime plus5 = dt.plusHours(5); assertEquals("2006-10-01T00:00:00.000-06:00", plus5.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2006-10-01T01:00:00.000-06:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2006-10-01T02:00:00.000-06:00", plus7.toString()); } public void test_DateTime_minusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 10, 1, 2, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-10-01T02:00:00.000-06:00", dt.toString()); DateTime minus1 = dt.minusHours(1); assertEquals("2006-10-01T01:00:00.000-06:00", minus1.toString()); DateTime minus2 = dt.minusHours(2); assertEquals("2006-10-01T00:00:00.000-06:00", minus2.toString()); DateTime minus3 = dt.minusHours(3); assertEquals("2006-09-30T23:00:00.000-06:00", minus3.toString()); DateTime minus4 = dt.minusHours(4); assertEquals("2006-09-30T23:00:00.000-05:00", minus4.toString()); DateTime minus5 = dt.minusHours(5); assertEquals("2006-09-30T22:00:00.000-05:00", minus5.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2006-09-30T21:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2006-09-30T20:00:00.000-05:00", minus7.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_DateTime_JustAfterLastEverOverlap() { // based on America/Argentina/Catamarca in file 2009s DateTimeZone zone = new DateTimeZoneBuilder() .setStandardOffset(-3 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("SUMMER", 1 * DateTimeConstants.MILLIS_PER_HOUR, 2000, 2008, 'w', 4, 10, 0, true, 23 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("WINTER", 0, 2000, 2008, 'w', 8, 10, 0, true, 0 * DateTimeConstants.MILLIS_PER_HOUR) .toDateTimeZone("Zone", false); LocalDate date = new LocalDate(2008, 8, 10); assertEquals("2008-08-10", date.toString()); DateTime dt = date.toDateTimeAtStartOfDay(zone); assertEquals("2008-08-10T00:00:00.000-03:00", dt.toString()); } // public void test_toDateMidnight_SaoPaolo() { // // RFE: 1684259 // DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); // LocalDate baseDate = new LocalDate(2006, 11, 5); // DateMidnight dm = baseDate.toDateMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dm.toString()); // DateTime dt = baseDate.toDateTimeAtMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dt.toString()); // } //----------------------------------------------------------------------- private static final DateTimeZone ZONE_PARIS = DateTimeZone.forID("Europe/Paris"); public void testWithMinuteOfHourInDstChange_mockZone() { DateTime cutover = new DateTime(2010, 10, 31, 1, 15, DateTimeZone.forOffsetHoursMinutes(0, 30)); assertEquals("2010-10-31T01:15:00.000+00:30", cutover.toString()); DateTimeZone halfHourZone = new MockZone(cutover.getMillis(), 3600000, -1800); DateTime pre = new DateTime(2010, 10, 31, 1, 0, halfHourZone); assertEquals("2010-10-31T01:00:00.000+01:00", pre.toString()); DateTime post = new DateTime(2010, 10, 31, 1, 59, halfHourZone); assertEquals("2010-10-31T01:59:00.000+00:30", post.toString()); DateTime testPre1 = pre.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+01:00", testPre1.toString()); // retain offset DateTime testPre2 = pre.withMinuteOfHour(50); assertEquals("2010-10-31T01:50:00.000+00:30", testPre2.toString()); DateTime testPost1 = post.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+00:30", testPost1.toString()); // retain offset DateTime testPost2 = post.withMinuteOfHour(10); assertEquals("2010-10-31T01:10:00.000+01:00", testPost2.toString()); } public void testWithHourOfDayInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withHourOfDay(2); assertEquals("2010-10-31T02:30:10.123+02:00", test.toString()); } public void testWithMinuteOfHourInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMinuteOfHour(0); assertEquals("2010-10-31T02:00:10.123+02:00", test.toString()); } public void testWithSecondOfMinuteInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withSecondOfMinute(0); assertEquals("2010-10-31T02:30:00.123+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_summer() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_winter() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+01:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+01:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+01:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_summer() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-04:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-04:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-04:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_winter() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-05:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-05:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-05:00", test.toString()); } public void testPlusMinutesInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMinutes(1); assertEquals("2010-10-31T02:31:10.123+02:00", test.toString()); } public void testPlusSecondsInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusSeconds(1); assertEquals("2010-10-31T02:30:11.123+02:00", test.toString()); } public void testPlusMillisInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMillis(1); assertEquals("2010-10-31T02:30:10.124+02:00", test.toString()); } public void testBug2182444_usCentral() { Chronology chronUSCentral = GregorianChronology.getInstance(DateTimeZone.forID("US/Central")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime usCentralStandardInUTC = new DateTime(2008, 11, 2, 7, 0, 0, 0, chronUTC); DateTime usCentralDaylightInUTC = new DateTime(2008, 11, 2, 6, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronUSCentral.getZone().isStandardOffset(usCentralStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronUSCentral.getZone().isStandardOffset(usCentralDaylightInUTC.getMillis())); DateTime usCentralStandardInUSCentral = usCentralStandardInUTC.toDateTime(chronUSCentral); DateTime usCentralDaylightInUSCentral = usCentralDaylightInUTC.toDateTime(chronUSCentral); assertEquals(1, usCentralStandardInUSCentral.getHourOfDay()); assertEquals(usCentralStandardInUSCentral.getHourOfDay(), usCentralDaylightInUSCentral.getHourOfDay()); assertTrue(usCentralStandardInUSCentral.getMillis() != usCentralDaylightInUSCentral.getMillis()); assertEquals(usCentralStandardInUSCentral, usCentralStandardInUSCentral.withHourOfDay(1)); assertEquals(usCentralStandardInUSCentral.getMillis() + 3, usCentralStandardInUSCentral.withMillisOfSecond(3).getMillis()); assertEquals(usCentralDaylightInUSCentral, usCentralDaylightInUSCentral.withHourOfDay(1)); assertEquals(usCentralDaylightInUSCentral.getMillis() + 3, usCentralDaylightInUSCentral.withMillisOfSecond(3).getMillis()); } public void testBug2182444_ausNSW() { Chronology chronAusNSW = GregorianChronology.getInstance(DateTimeZone.forID("Australia/NSW")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime australiaNSWStandardInUTC = new DateTime(2008, 4, 5, 16, 0, 0, 0, chronUTC); DateTime australiaNSWDaylightInUTC = new DateTime(2008, 4, 5, 15, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronAusNSW.getZone().isStandardOffset(australiaNSWStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronAusNSW.getZone().isStandardOffset(australiaNSWDaylightInUTC.getMillis())); DateTime australiaNSWStandardInAustraliaNSW = australiaNSWStandardInUTC.toDateTime(chronAusNSW); DateTime australiaNSWDaylightInAusraliaNSW = australiaNSWDaylightInUTC.toDateTime(chronAusNSW); assertEquals(2, australiaNSWStandardInAustraliaNSW.getHourOfDay()); assertEquals(australiaNSWStandardInAustraliaNSW.getHourOfDay(), australiaNSWDaylightInAusraliaNSW.getHourOfDay()); assertTrue(australiaNSWStandardInAustraliaNSW.getMillis() != australiaNSWDaylightInAusraliaNSW.getMillis()); assertEquals(australiaNSWStandardInAustraliaNSW, australiaNSWStandardInAustraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWStandardInAustraliaNSW.getMillis() + 3, australiaNSWStandardInAustraliaNSW.withMillisOfSecond(3).getMillis()); assertEquals(australiaNSWDaylightInAusraliaNSW, australiaNSWDaylightInAusraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWDaylightInAusraliaNSW.getMillis() + 3, australiaNSWDaylightInAusraliaNSW.withMillisOfSecond(3).getMillis()); } public void testPeriod() { DateTime a = new DateTime("2010-10-31T02:00:00.000+02:00", ZONE_PARIS); DateTime b = new DateTime("2010-10-31T02:01:00.000+02:00", ZONE_PARIS); Period period = new Period(a, b, PeriodType.standard()); assertEquals("PT1M", period.toString()); } public void testForum4013394_retainOffsetWhenRetainFields_sameOffsetsDifferentZones() { final DateTimeZone fromDTZ = DateTimeZone.forID("Europe/London"); final DateTimeZone toDTZ = DateTimeZone.forID("Europe/Lisbon"); DateTime baseBefore = new DateTime(2007, 10, 28, 1, 15, fromDTZ).minusHours(1); DateTime baseAfter = new DateTime(2007, 10, 28, 1, 15, fromDTZ); DateTime testBefore = baseBefore.withZoneRetainFields(toDTZ); DateTime testAfter = baseAfter.withZoneRetainFields(toDTZ); // toString ignores time-zone but includes offset assertEquals(baseBefore.toString(), testBefore.toString()); assertEquals(baseAfter.toString(), testAfter.toString()); } public void testBug3192457_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2007, 10, 28, 3, 15, zone); DateTime baseBefore = base.minusHours(2); DateTime baseAfter = base.minusHours(1); assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseAfter.withLaterOffsetAtOverlap()); } // ensure Summer time picked //----------------------------------------------------------------------- public void testDateTimeCreation_athens() { DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime base = new DateTime(2011, 10, 30, 3, 15, zone); assertEquals("2011-10-30T03:15:00.000+03:00", base.toString()); assertEquals("2011-10-30T03:15:00.000+02:00", base.plusHours(1).toString()); } public void testDateTimeCreation_paris() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2011, 10, 30, 2, 15, zone); assertEquals("2011-10-30T02:15:00.000+02:00", base.toString()); assertEquals("2011-10-30T02:15:00.000+01:00", base.plusHours(1).toString()); } public void testDateTimeCreation_london() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); DateTime base = new DateTime(2011, 10, 30, 1, 15, zone); assertEquals("2011-10-30T01:15:00.000+01:00", base.toString()); assertEquals("2011-10-30T01:15:00.000Z", base.plusHours(1).toString()); } public void testDateTimeCreation_newYork() { DateTimeZone zone = DateTimeZone.forID("America/New_York"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-04:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-05:00", base.plusHours(1).toString()); } public void testDateTimeCreation_losAngeles() { DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-07:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-08:00", base.plusHours(1).toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, sec, milli, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(year, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { DateTime dt = new DateTime(year, month, day, hour, min, sec, milli, DateTimeZone.UTC); int offset = zone.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, zone); assertEquals(res.toString(), expected, res.toString()); } }
// You are a professional Java test case writer, please create a test case named `testDateTimeCreation_london` for the issue `Time-124`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-124 // // ## Issue-Title: // #124 Inconsistent interpretation of ambiguous time during DST // // // // // // ## Issue-Description: // The inconsistency appears for timezone Europe/London. // // // Consider the following code // // … // // DateTime britishDate = new DateTime(2011, 10, 30, 1, 59, 0, 0, DateTimeZone.forID("Europe/London")); // // DateTime norwDate = new DateTime(2011, 10, 30, 2, 59, 0, 0, DateTimeZone.forID("Europe/Oslo")); // // DateTime finnishDate = new DateTime(2011, 10, 30, 3, 59, 0, 0, DateTimeZone.forID("Europe/Helsinki")); // // // // ``` // System.out.println(britishDate); // System.out.println(norwDate); // System.out.println(finnishDate); // // ``` // // … // // These three DateTime objects should all represent the same moment in time even if they are ambiguous. And using jodatime 1.6.2 this is the case. The code produces the following output: // // 2011-10-30T01:59:00.000Z // // 2011-10-30T02:59:00.000+01:00 // // 2011-10-30T03:59:00.000+02:00 // // // Using jodatime 2.0 however, the output is: // // // 2011-10-30T01:59:00.000Z // // 2011-10-30T02:59:00.000+02:00 // // 2011-10-30T03:59:00.000+03:00 // // // which IMO is wrong for Europe/London. Correct output should have been // // 2011-10-30T01:59:00.000+01:00 // // // The release notes for 2.0 states that: // // "Now, it always returns the earlier instant (summer time) during an overlap. …" // // // // public void testDateTimeCreation_london() {
1,267
19
1,262
src/test/java/org/joda/time/TestDateTimeZoneCutover.java
src/test/java
```markdown ## Issue-ID: Time-124 ## Issue-Title: #124 Inconsistent interpretation of ambiguous time during DST ## Issue-Description: The inconsistency appears for timezone Europe/London. Consider the following code … DateTime britishDate = new DateTime(2011, 10, 30, 1, 59, 0, 0, DateTimeZone.forID("Europe/London")); DateTime norwDate = new DateTime(2011, 10, 30, 2, 59, 0, 0, DateTimeZone.forID("Europe/Oslo")); DateTime finnishDate = new DateTime(2011, 10, 30, 3, 59, 0, 0, DateTimeZone.forID("Europe/Helsinki")); ``` System.out.println(britishDate); System.out.println(norwDate); System.out.println(finnishDate); ``` … These three DateTime objects should all represent the same moment in time even if they are ambiguous. And using jodatime 1.6.2 this is the case. The code produces the following output: 2011-10-30T01:59:00.000Z 2011-10-30T02:59:00.000+01:00 2011-10-30T03:59:00.000+02:00 Using jodatime 2.0 however, the output is: 2011-10-30T01:59:00.000Z 2011-10-30T02:59:00.000+02:00 2011-10-30T03:59:00.000+03:00 which IMO is wrong for Europe/London. Correct output should have been 2011-10-30T01:59:00.000+01:00 The release notes for 2.0 states that: "Now, it always returns the earlier instant (summer time) during an overlap. …" ``` You are a professional Java test case writer, please create a test case named `testDateTimeCreation_london` for the issue `Time-124`, utilizing the provided issue report information and the following function signature. ```java public void testDateTimeCreation_london() { ```
1,262
[ "org.joda.time.DateTimeZone" ]
d99097be93bf90b1284e221dfd4c16e3d720fc073fce85e5c423330f208fec87
public void testDateTimeCreation_london()
// You are a professional Java test case writer, please create a test case named `testDateTimeCreation_london` for the issue `Time-124`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-124 // // ## Issue-Title: // #124 Inconsistent interpretation of ambiguous time during DST // // // // // // ## Issue-Description: // The inconsistency appears for timezone Europe/London. // // // Consider the following code // // … // // DateTime britishDate = new DateTime(2011, 10, 30, 1, 59, 0, 0, DateTimeZone.forID("Europe/London")); // // DateTime norwDate = new DateTime(2011, 10, 30, 2, 59, 0, 0, DateTimeZone.forID("Europe/Oslo")); // // DateTime finnishDate = new DateTime(2011, 10, 30, 3, 59, 0, 0, DateTimeZone.forID("Europe/Helsinki")); // // // // ``` // System.out.println(britishDate); // System.out.println(norwDate); // System.out.println(finnishDate); // // ``` // // … // // These three DateTime objects should all represent the same moment in time even if they are ambiguous. And using jodatime 1.6.2 this is the case. The code produces the following output: // // 2011-10-30T01:59:00.000Z // // 2011-10-30T02:59:00.000+01:00 // // 2011-10-30T03:59:00.000+02:00 // // // Using jodatime 2.0 however, the output is: // // // 2011-10-30T01:59:00.000Z // // 2011-10-30T02:59:00.000+02:00 // // 2011-10-30T03:59:00.000+03:00 // // // which IMO is wrong for Europe/London. Correct output should have been // // 2011-10-30T01:59:00.000+01:00 // // // The release notes for 2.0 states that: // // "Now, it always returns the earlier instant (summer time) during an overlap. …" // // // //
Time
/* * Copyright 2001-2007 Stephen Colebourne * * 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 org.joda.time; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.GregorianChronology; import org.joda.time.tz.DateTimeZoneBuilder; /** * This class is a JUnit test for DateTimeZone. * * @author Stephen Colebourne */ public class TestDateTimeZoneCutover extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeZoneCutover.class); } public TestDateTimeZoneCutover(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- // The behaviour of getOffsetFromLocal is defined in its javadoc // However, this definition doesn't work for all DateTimeField operations /** Mock zone simulating Asia/Gaza cutover at midnight 2007-04-01 */ private static long CUTOVER_GAZA = 1175378400000L; private static int OFFSET_GAZA = 7200000; // +02:00 private static final DateTimeZone MOCK_GAZA = new MockZone(CUTOVER_GAZA, OFFSET_GAZA, 3600); //----------------------------------------------------------------------- public void test_MockGazaIsCorrect() { DateTime pre = new DateTime(CUTOVER_GAZA - 1L, MOCK_GAZA); assertEquals("2007-03-31T23:59:59.999+02:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_GAZA + 1L, MOCK_GAZA); assertEquals("2007-04-01T01:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Gaza() { doTest_getOffsetFromLocal_Gaza(-1, 23, 0, "2007-03-31T23:00:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(-1, 23, 30, "2007-03-31T23:30:00.000+02:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 0, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 0, "2007-04-01T01:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 1, 30, "2007-04-01T01:30:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 2, 0, "2007-04-01T02:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 3, 0, "2007-04-01T03:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 4, 0, "2007-04-01T04:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 5, 0, "2007-04-01T05:00:00.000+03:00"); doTest_getOffsetFromLocal_Gaza(0, 6, 0, "2007-04-01T06:00:00.000+03:00"); } private void doTest_getOffsetFromLocal_Gaza(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_GAZA.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_GAZA); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_roundCeiling_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T20:00:00.000+02:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000+03:00", rounded.toString()); } public void test_DateTime_setHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_DateTime_minusHour_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000+02:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000+02:00", minus9.toString()); } public void test_DateTime_plusHour_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T16:00:00.000+02:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000+02:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusDay_Gaza() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-02T00:00:00.000+03:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000+02:00", minus2.toString()); } public void test_DateTime_plusDay_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:00:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Gaza() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_GAZA); assertEquals("2007-03-31T00:30:00.000+02:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000+03:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000+03:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Gaza() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-30T00:00:00.000+03:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000+03:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000+03:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", res.toString()); } public void test_MutableDateTime_withZoneRetainFields_Gaza() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_GAZA); assertEquals("2007-04-01T01:00:00.000+03:00", dt.toString()); } public void test_LocalDate_new_Gaza() { LocalDate date1 = new LocalDate(CUTOVER_GAZA, MOCK_GAZA); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_GAZA - 1, MOCK_GAZA); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Gaza() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Gaza() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Gaza() { new DateTime(2007, 3, 31, 19, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 21, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 22, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_GAZA); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_GAZA); } public void test_DateTime_parse_Gaza() { try { new DateTime("2007-04-01T00:00", MOCK_GAZA); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //------------------------ Bug [1710316] -------------------------------- //----------------------------------------------------------------------- /** Mock zone simulating America/Grand_Turk cutover at midnight 2007-04-01 */ private static long CUTOVER_TURK = 1175403600000L; private static int OFFSET_TURK = -18000000; // -05:00 private static final DateTimeZone MOCK_TURK = new MockZone(CUTOVER_TURK, OFFSET_TURK, 3600); //----------------------------------------------------------------------- public void test_MockTurkIsCorrect() { DateTime pre = new DateTime(CUTOVER_TURK - 1L, MOCK_TURK); assertEquals("2007-03-31T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_TURK + 1L, MOCK_TURK); assertEquals("2007-04-01T01:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_Turk() { doTest_getOffsetFromLocal_Turk(-1, 23, 0, "2007-03-31T23:00:00.000-05:00"); doTest_getOffsetFromLocal_Turk(-1, 23, 30, "2007-03-31T23:30:00.000-05:00"); doTest_getOffsetFromLocal_Turk(0, 0, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 0, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 0, "2007-04-01T01:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 1, 30, "2007-04-01T01:30:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 2, 0, "2007-04-01T02:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 3, 0, "2007-04-01T03:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 4, 0, "2007-04-01T04:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 5, 0, "2007-04-01T05:00:00.000-04:00"); doTest_getOffsetFromLocal_Turk(0, 6, 0, "2007-04-01T06:00:00.000-04:00"); } private void doTest_getOffsetFromLocal_Turk(int days, int hour, int min, String expected) { DateTime dt = new DateTime(2007, 4, 1, hour, min, 0, 0, DateTimeZone.UTC).plusDays(days); int offset = MOCK_TURK.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, MOCK_TURK); assertEquals(res.toString(), expected, res.toString()); } public void test_DateTime_roundFloor_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloorNotDST_Turk() { DateTime dt = new DateTime(2007, 4, 2, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T08:00:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-04-02T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_Turk() { DateTime dt = new DateTime(2007, 3, 31, 20, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T20:00:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-04-01T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_setHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withHourZero_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_withDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime res = dt.withDayOfMonth(1); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_DateTime_minusHour_Turk() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-01T08:00:00.000-04:00", dt.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-04-01T01:00:00.000-04:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-03-31T23:00:00.000-05:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-03-31T22:00:00.000-05:00", minus9.toString()); } public void test_DateTime_plusHour_Turk() { DateTime dt = new DateTime(2007, 3, 31, 16, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T16:00:00.000-05:00", dt.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-03-31T23:00:00.000-05:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-04-01T01:00:00.000-04:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-04-01T02:00:00.000-04:00", plus9.toString()); } public void test_DateTime_minusDay_Turk() { DateTime dt = new DateTime(2007, 4, 2, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-02T00:00:00.000-04:00", dt.toString()); DateTime minus1 = dt.minusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", minus1.toString()); DateTime minus2 = dt.minusDays(2); assertEquals("2007-03-31T00:00:00.000-05:00", minus2.toString()); } public void test_DateTime_plusDay_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_plusDayMidGap_Turk() { DateTime dt = new DateTime(2007, 3, 31, 0, 30, 0, 0, MOCK_TURK); assertEquals("2007-03-31T00:30:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusDays(1); assertEquals("2007-04-01T01:30:00.000-04:00", plus1.toString()); DateTime plus2 = dt.plusDays(2); assertEquals("2007-04-02T00:30:00.000-04:00", plus2.toString()); } public void test_DateTime_addWrapFieldDay_Turk() { DateTime dt = new DateTime(2007, 4, 30, 0, 0, 0, 0, MOCK_TURK); assertEquals("2007-04-30T00:00:00.000-04:00", dt.toString()); DateTime plus1 = dt.dayOfMonth().addWrapFieldToCopy(1); assertEquals("2007-04-01T01:00:00.000-04:00", plus1.toString()); DateTime plus2 = dt.dayOfMonth().addWrapFieldToCopy(2); assertEquals("2007-04-02T00:00:00.000-04:00", plus2.toString()); } public void test_DateTime_withZoneRetainFields_Turk() { DateTime dt = new DateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); DateTime res = dt.withZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", res.toString()); } public void test_MutableDateTime_setZoneRetainFields_Turk() { MutableDateTime dt = new MutableDateTime(2007, 4, 1, 0, 0, 0, 0, DateTimeZone.UTC); assertEquals("2007-04-01T00:00:00.000Z", dt.toString()); dt.setZoneRetainFields(MOCK_TURK); assertEquals("2007-04-01T01:00:00.000-04:00", dt.toString()); } public void test_LocalDate_new_Turk() { LocalDate date1 = new LocalDate(CUTOVER_TURK, MOCK_TURK); assertEquals("2007-04-01", date1.toString()); LocalDate date2 = new LocalDate(CUTOVER_TURK - 1, MOCK_TURK); assertEquals("2007-03-31", date2.toString()); } public void test_LocalDate_toDateMidnight_Turk() { LocalDate date = new LocalDate(2007, 4, 1); try { date.toDateMidnight(MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().startsWith("Illegal instant due to time zone offset transition")); } } public void test_DateTime_new_Turk() { try { new DateTime(2007, 4, 1, 0, 0, 0, 0, MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } public void test_DateTime_newValid_Turk() { new DateTime(2007, 3, 31, 23, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 1, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 2, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 3, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 4, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 5, 0, 0, 0, MOCK_TURK); new DateTime(2007, 4, 1, 6, 0, 0, 0, MOCK_TURK); } public void test_DateTime_parse_Turk() { try { new DateTime("2007-04-01T00:00", MOCK_TURK); fail(); } catch (IllegalArgumentException ex) { assertEquals(true, ex.getMessage().indexOf("Illegal instant due to time zone offset transition") >= 0); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 03:00 on 2007-03-11 */ private static long CUTOVER_NEW_YORK_SPRING = 1173596400000L; // 2007-03-11T03:00:00.000-04:00 private static final DateTimeZone ZONE_NEW_YORK = DateTimeZone.forID("America/New_York"); // DateTime x = new DateTime(2007, 1, 1, 0, 0, 0, 0, ZONE_NEW_YORK); // System.out.println(ZONE_NEW_YORK.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_NEW_YORK.nextTransition(x.getMillis()), ZONE_NEW_YORK); // System.out.println(y); //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Spring() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_SPRING - 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T01:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_SPRING, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.000-04:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_SPRING + 1L, ZONE_NEW_YORK); assertEquals("2007-03-11T03:00:00.001-04:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Spring() { doTest_getOffsetFromLocal(3, 11, 1, 0, "2007-03-11T01:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 1,30, "2007-03-11T01:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 2,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3, 0, "2007-03-11T03:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 3,30, "2007-03-11T03:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 4, 0, "2007-03-11T04:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 5, 0, "2007-03-11T05:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 6, 0, "2007-03-11T06:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 7, 0, "2007-03-11T07:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(3, 11, 8, 0, "2007-03-11T08:00:00.000-04:00", ZONE_NEW_YORK); } public void test_DateTime_setHourAcross_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-11T04:00:00.000-04:00", res.toString()); } public void test_DateTime_setHourForward_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 0, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T00:00:00.000-05:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_NewYork_Spring() { DateTime dt = new DateTime(2007, 3, 11, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T08:00:00.000-04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-03-11T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-03-11T03:30:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-03-12T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T03:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_hour_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-03-11T04:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_preCutover() { DateTime dt = new DateTime(2007, 3, 11, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minute_NewYork_Spring_postCutover() { DateTime dt = new DateTime(2007, 3, 11, 3, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-03-11T03:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-03-11T03:31:00.000-04:00", rounded.toString()); } //----------------------------------------------------------------------- /** America/New_York cutover from 01:59 to 01:00 on 2007-11-04 */ private static long CUTOVER_NEW_YORK_AUTUMN = 1194156000000L; // 2007-11-04T01:00:00.000-05:00 //----------------------------------------------------------------------- public void test_NewYorkIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_NEW_YORK_AUTUMN - 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:59:59.999-04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_NEW_YORK_AUTUMN, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.000-05:00", at.toString()); DateTime post = new DateTime(CUTOVER_NEW_YORK_AUTUMN + 1L, ZONE_NEW_YORK); assertEquals("2007-11-04T01:00:00.001-05:00", post.toString()); } public void test_getOffsetFromLocal_NewYork_Autumn() { doTest_getOffsetFromLocal(11, 4, 0, 0, "2007-11-04T00:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 0,30, "2007-11-04T00:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1, 0, "2007-11-04T01:00:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 1,30, "2007-11-04T01:30:00.000-04:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2, 0, "2007-11-04T02:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 2,30, "2007-11-04T02:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3, 0, "2007-11-04T03:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 3,30, "2007-11-04T03:30:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 4, 0, "2007-11-04T04:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 5, 0, "2007-11-04T05:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 6, 0, "2007-11-04T06:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 7, 0, "2007-11-04T07:00:00.000-05:00", ZONE_NEW_YORK); doTest_getOffsetFromLocal(11, 4, 8, 0, "2007-11-04T08:00:00.000-05:00", ZONE_NEW_YORK); } public void test_DateTime_constructor_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); } public void test_DateTime_plusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 3, 18, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-03T18:00:00.000-04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-11-04T00:00:00.000-04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-11-04T01:00:00.000-04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-11-04T01:00:00.000-05:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-11-04T02:00:00.000-05:00", plus9.toString()); } public void test_DateTime_minusHour_NewYork_Autumn() { DateTime dt = new DateTime(2007, 11, 4, 8, 0, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T08:00:00.000-05:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-11-04T02:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-11-04T01:00:00.000-05:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-11-04T01:00:00.000-04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-11-04T00:00:00.000-04:00", minus9.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundFloor_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundFloorCopy(); assertEquals("2007-11-04T00:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundFloorCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundFloorCopy(); assertEquals("2007-11-04T01:30:00.000-05:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-04:00", rounded.toString()); } public void test_DateTime_roundFloor_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundFloorCopy(); assertEquals("2007-11-04T01:30:40.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- public void test_DateTime_roundCeiling_day_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_day_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.dayOfMonth().roundCeilingCopy(); assertEquals("2007-11-05T00:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.000-04:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T01:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_hourOfDay_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 0, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:00.000-05:00", dt.toString()); DateTime rounded = dt.hourOfDay().roundCeilingCopy(); assertEquals("2007-11-04T02:00:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.000-04:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_minuteOfHour_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 0, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.000-05:00", dt.toString()); DateTime rounded = dt.minuteOfHour().roundCeilingCopy(); assertEquals("2007-11-04T01:31:00.000-05:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_preCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:40.500-04:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-04:00", rounded.toString()); } public void test_DateTime_roundCeiling_secondOfMinute_NewYork_Autumn_postCutover() { DateTime dt = new DateTime(2007, 11, 4, 1, 30, 40, 500, ZONE_NEW_YORK).plusHours(1); assertEquals("2007-11-04T01:30:40.500-05:00", dt.toString()); DateTime rounded = dt.secondOfMinute().roundCeilingCopy(); assertEquals("2007-11-04T01:30:41.000-05:00", rounded.toString()); } //----------------------------------------------------------------------- /** Europe/Moscow cutover from 01:59 to 03:00 on 2007-03-25 */ private static long CUTOVER_MOSCOW_SPRING = 1174777200000L; // 2007-03-25T03:00:00.000+04:00 private static final DateTimeZone ZONE_MOSCOW = DateTimeZone.forID("Europe/Moscow"); //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Spring() { // DateTime x = new DateTime(2007, 7, 1, 0, 0, 0, 0, ZONE_MOSCOW); // System.out.println(ZONE_MOSCOW.nextTransition(x.getMillis())); // DateTime y = new DateTime(ZONE_MOSCOW.nextTransition(x.getMillis()), ZONE_MOSCOW); // System.out.println(y); DateTime pre = new DateTime(CUTOVER_MOSCOW_SPRING - 1L, ZONE_MOSCOW); assertEquals("2007-03-25T01:59:59.999+03:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_SPRING, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.000+04:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_SPRING + 1L, ZONE_MOSCOW); assertEquals("2007-03-25T03:00:00.001+04:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Spring() { doTest_getOffsetFromLocal(3, 25, 1, 0, "2007-03-25T01:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 1,30, "2007-03-25T01:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 2,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3, 0, "2007-03-25T03:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 3,30, "2007-03-25T03:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 4, 0, "2007-03-25T04:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 5, 0, "2007-03-25T05:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 6, 0, "2007-03-25T06:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 7, 0, "2007-03-25T07:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(3, 25, 8, 0, "2007-03-25T08:00:00.000+04:00", ZONE_MOSCOW); } public void test_DateTime_setHourAcross_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); DateTime res = dt.hourOfDay().setCopy(4); assertEquals("2007-03-25T04:00:00.000+04:00", res.toString()); } public void test_DateTime_setHourForward_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 0, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T00:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } public void test_DateTime_setHourBack_Moscow_Spring() { DateTime dt = new DateTime(2007, 3, 25, 8, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-03-25T08:00:00.000+04:00", dt.toString()); try { dt.hourOfDay().setCopy(2); fail(); } catch (IllegalFieldValueException ex) { // expected } } //----------------------------------------------------------------------- /** America/New_York cutover from 02:59 to 02:00 on 2007-10-28 */ private static long CUTOVER_MOSCOW_AUTUMN = 1193526000000L; // 2007-10-28T02:00:00.000+03:00 //----------------------------------------------------------------------- public void test_MoscowIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_MOSCOW_AUTUMN - 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:59:59.999+04:00", pre.toString()); DateTime at = new DateTime(CUTOVER_MOSCOW_AUTUMN, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.000+03:00", at.toString()); DateTime post = new DateTime(CUTOVER_MOSCOW_AUTUMN + 1L, ZONE_MOSCOW); assertEquals("2007-10-28T02:00:00.001+03:00", post.toString()); } public void test_getOffsetFromLocal_Moscow_Autumn() { doTest_getOffsetFromLocal(10, 28, 0, 0, "2007-10-28T00:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 0,30, "2007-10-28T00:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1, 0, "2007-10-28T01:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 1,30, "2007-10-28T01:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2, 0, "2007-10-28T02:00:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30, "2007-10-28T02:30:00.000+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,30,59,999, "2007-10-28T02:30:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,998, "2007-10-28T02:59:59.998+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 2,59,59,999, "2007-10-28T02:59:59.999+04:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3, 0, "2007-10-28T03:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 3,30, "2007-10-28T03:30:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 4, 0, "2007-10-28T04:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 5, 0, "2007-10-28T05:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 6, 0, "2007-10-28T06:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 7, 0, "2007-10-28T07:00:00.000+03:00", ZONE_MOSCOW); doTest_getOffsetFromLocal(10, 28, 8, 0, "2007-10-28T08:00:00.000+03:00", ZONE_MOSCOW); } public void test_getOffsetFromLocal_Moscow_Autumn_overlap_mins() { for (int min = 0; min < 60; min++) { if (min < 10) { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:0" + min + ":00.000+04:00", ZONE_MOSCOW); } else { doTest_getOffsetFromLocal(10, 28, 2, min, "2007-10-28T02:" + min + ":00.000+04:00", ZONE_MOSCOW); } } } public void test_DateTime_constructor_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 2, 30, ZONE_MOSCOW); assertEquals("2007-10-28T02:30:00.000+04:00", dt.toString()); } public void test_DateTime_plusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 27, 19, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-27T19:00:00.000+04:00", dt.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2007-10-28T01:00:00.000+04:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2007-10-28T02:00:00.000+04:00", plus7.toString()); DateTime plus8 = dt.plusHours(8); assertEquals("2007-10-28T02:00:00.000+03:00", plus8.toString()); DateTime plus9 = dt.plusHours(9); assertEquals("2007-10-28T03:00:00.000+03:00", plus9.toString()); } public void test_DateTime_minusHour_Moscow_Autumn() { DateTime dt = new DateTime(2007, 10, 28, 9, 0, 0, 0, ZONE_MOSCOW); assertEquals("2007-10-28T09:00:00.000+03:00", dt.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2007-10-28T03:00:00.000+03:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2007-10-28T02:00:00.000+03:00", minus7.toString()); DateTime minus8 = dt.minusHours(8); assertEquals("2007-10-28T02:00:00.000+04:00", minus8.toString()); DateTime minus9 = dt.minusHours(9); assertEquals("2007-10-28T01:00:00.000+04:00", minus9.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** America/Guatemala cutover from 23:59 to 23:00 on 2006-09-30 */ private static long CUTOVER_GUATEMALA_AUTUMN = 1159678800000L; // 2006-09-30T23:00:00.000-06:00 private static final DateTimeZone ZONE_GUATEMALA = DateTimeZone.forID("America/Guatemala"); //----------------------------------------------------------------------- public void test_GuatemataIsCorrect_Autumn() { DateTime pre = new DateTime(CUTOVER_GUATEMALA_AUTUMN - 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:59:59.999-05:00", pre.toString()); DateTime at = new DateTime(CUTOVER_GUATEMALA_AUTUMN, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.000-06:00", at.toString()); DateTime post = new DateTime(CUTOVER_GUATEMALA_AUTUMN + 1L, ZONE_GUATEMALA); assertEquals("2006-09-30T23:00:00.001-06:00", post.toString()); } public void test_getOffsetFromLocal_Guatemata_Autumn() { doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23, 0, "2006-09-30T23:00:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006, 9,30,23,30, "2006-09-30T23:30:00.000-05:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0, 0, "2006-10-01T00:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 0,30, "2006-10-01T00:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1, 0, "2006-10-01T01:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 1,30, "2006-10-01T01:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2, 0, "2006-10-01T02:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 2,30, "2006-10-01T02:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3, 0, "2006-10-01T03:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 3,30, "2006-10-01T03:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4, 0, "2006-10-01T04:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 4,30, "2006-10-01T04:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5, 0, "2006-10-01T05:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 5,30, "2006-10-01T05:30:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6, 0, "2006-10-01T06:00:00.000-06:00", ZONE_GUATEMALA); doTest_getOffsetFromLocal( 2006,10, 1, 6,30, "2006-10-01T06:30:00.000-06:00", ZONE_GUATEMALA); } public void test_DateTime_plusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 9, 30, 20, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-09-30T20:00:00.000-05:00", dt.toString()); DateTime plus1 = dt.plusHours(1); assertEquals("2006-09-30T21:00:00.000-05:00", plus1.toString()); DateTime plus2 = dt.plusHours(2); assertEquals("2006-09-30T22:00:00.000-05:00", plus2.toString()); DateTime plus3 = dt.plusHours(3); assertEquals("2006-09-30T23:00:00.000-05:00", plus3.toString()); DateTime plus4 = dt.plusHours(4); assertEquals("2006-09-30T23:00:00.000-06:00", plus4.toString()); DateTime plus5 = dt.plusHours(5); assertEquals("2006-10-01T00:00:00.000-06:00", plus5.toString()); DateTime plus6 = dt.plusHours(6); assertEquals("2006-10-01T01:00:00.000-06:00", plus6.toString()); DateTime plus7 = dt.plusHours(7); assertEquals("2006-10-01T02:00:00.000-06:00", plus7.toString()); } public void test_DateTime_minusHour_Guatemata_Autumn() { DateTime dt = new DateTime(2006, 10, 1, 2, 0, 0, 0, ZONE_GUATEMALA); assertEquals("2006-10-01T02:00:00.000-06:00", dt.toString()); DateTime minus1 = dt.minusHours(1); assertEquals("2006-10-01T01:00:00.000-06:00", minus1.toString()); DateTime minus2 = dt.minusHours(2); assertEquals("2006-10-01T00:00:00.000-06:00", minus2.toString()); DateTime minus3 = dt.minusHours(3); assertEquals("2006-09-30T23:00:00.000-06:00", minus3.toString()); DateTime minus4 = dt.minusHours(4); assertEquals("2006-09-30T23:00:00.000-05:00", minus4.toString()); DateTime minus5 = dt.minusHours(5); assertEquals("2006-09-30T22:00:00.000-05:00", minus5.toString()); DateTime minus6 = dt.minusHours(6); assertEquals("2006-09-30T21:00:00.000-05:00", minus6.toString()); DateTime minus7 = dt.minusHours(7); assertEquals("2006-09-30T20:00:00.000-05:00", minus7.toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_DateTime_JustAfterLastEverOverlap() { // based on America/Argentina/Catamarca in file 2009s DateTimeZone zone = new DateTimeZoneBuilder() .setStandardOffset(-3 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("SUMMER", 1 * DateTimeConstants.MILLIS_PER_HOUR, 2000, 2008, 'w', 4, 10, 0, true, 23 * DateTimeConstants.MILLIS_PER_HOUR) .addRecurringSavings("WINTER", 0, 2000, 2008, 'w', 8, 10, 0, true, 0 * DateTimeConstants.MILLIS_PER_HOUR) .toDateTimeZone("Zone", false); LocalDate date = new LocalDate(2008, 8, 10); assertEquals("2008-08-10", date.toString()); DateTime dt = date.toDateTimeAtStartOfDay(zone); assertEquals("2008-08-10T00:00:00.000-03:00", dt.toString()); } // public void test_toDateMidnight_SaoPaolo() { // // RFE: 1684259 // DateTimeZone zone = DateTimeZone.forID("America/Sao_Paulo"); // LocalDate baseDate = new LocalDate(2006, 11, 5); // DateMidnight dm = baseDate.toDateMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dm.toString()); // DateTime dt = baseDate.toDateTimeAtMidnight(zone); // assertEquals("2006-11-05T00:00:00.000-03:00", dt.toString()); // } //----------------------------------------------------------------------- private static final DateTimeZone ZONE_PARIS = DateTimeZone.forID("Europe/Paris"); public void testWithMinuteOfHourInDstChange_mockZone() { DateTime cutover = new DateTime(2010, 10, 31, 1, 15, DateTimeZone.forOffsetHoursMinutes(0, 30)); assertEquals("2010-10-31T01:15:00.000+00:30", cutover.toString()); DateTimeZone halfHourZone = new MockZone(cutover.getMillis(), 3600000, -1800); DateTime pre = new DateTime(2010, 10, 31, 1, 0, halfHourZone); assertEquals("2010-10-31T01:00:00.000+01:00", pre.toString()); DateTime post = new DateTime(2010, 10, 31, 1, 59, halfHourZone); assertEquals("2010-10-31T01:59:00.000+00:30", post.toString()); DateTime testPre1 = pre.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+01:00", testPre1.toString()); // retain offset DateTime testPre2 = pre.withMinuteOfHour(50); assertEquals("2010-10-31T01:50:00.000+00:30", testPre2.toString()); DateTime testPost1 = post.withMinuteOfHour(30); assertEquals("2010-10-31T01:30:00.000+00:30", testPost1.toString()); // retain offset DateTime testPost2 = post.withMinuteOfHour(10); assertEquals("2010-10-31T01:10:00.000+01:00", testPost2.toString()); } public void testWithHourOfDayInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withHourOfDay(2); assertEquals("2010-10-31T02:30:10.123+02:00", test.toString()); } public void testWithMinuteOfHourInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMinuteOfHour(0); assertEquals("2010-10-31T02:00:10.123+02:00", test.toString()); } public void testWithSecondOfMinuteInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withSecondOfMinute(0); assertEquals("2010-10-31T02:30:00.123+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_summer() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+02:00", test.toString()); } public void testWithMillisOfSecondInDstChange_Paris_winter() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+01:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+01:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2010-10-31T02:30:10.000+01:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_summer() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-04:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-04:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-04:00", test.toString()); } public void testWithMillisOfSecondInDstChange_NewYork_winter() { DateTime dateTime = new DateTime("2007-11-04T01:30:00.123-05:00", ZONE_NEW_YORK); assertEquals("2007-11-04T01:30:00.123-05:00", dateTime.toString()); DateTime test = dateTime.withMillisOfSecond(0); assertEquals("2007-11-04T01:30:00.000-05:00", test.toString()); } public void testPlusMinutesInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMinutes(1); assertEquals("2010-10-31T02:31:10.123+02:00", test.toString()); } public void testPlusSecondsInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusSeconds(1); assertEquals("2010-10-31T02:30:11.123+02:00", test.toString()); } public void testPlusMillisInDstChange() { DateTime dateTime = new DateTime("2010-10-31T02:30:10.123+02:00", ZONE_PARIS); assertEquals("2010-10-31T02:30:10.123+02:00", dateTime.toString()); DateTime test = dateTime.plusMillis(1); assertEquals("2010-10-31T02:30:10.124+02:00", test.toString()); } public void testBug2182444_usCentral() { Chronology chronUSCentral = GregorianChronology.getInstance(DateTimeZone.forID("US/Central")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime usCentralStandardInUTC = new DateTime(2008, 11, 2, 7, 0, 0, 0, chronUTC); DateTime usCentralDaylightInUTC = new DateTime(2008, 11, 2, 6, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronUSCentral.getZone().isStandardOffset(usCentralStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronUSCentral.getZone().isStandardOffset(usCentralDaylightInUTC.getMillis())); DateTime usCentralStandardInUSCentral = usCentralStandardInUTC.toDateTime(chronUSCentral); DateTime usCentralDaylightInUSCentral = usCentralDaylightInUTC.toDateTime(chronUSCentral); assertEquals(1, usCentralStandardInUSCentral.getHourOfDay()); assertEquals(usCentralStandardInUSCentral.getHourOfDay(), usCentralDaylightInUSCentral.getHourOfDay()); assertTrue(usCentralStandardInUSCentral.getMillis() != usCentralDaylightInUSCentral.getMillis()); assertEquals(usCentralStandardInUSCentral, usCentralStandardInUSCentral.withHourOfDay(1)); assertEquals(usCentralStandardInUSCentral.getMillis() + 3, usCentralStandardInUSCentral.withMillisOfSecond(3).getMillis()); assertEquals(usCentralDaylightInUSCentral, usCentralDaylightInUSCentral.withHourOfDay(1)); assertEquals(usCentralDaylightInUSCentral.getMillis() + 3, usCentralDaylightInUSCentral.withMillisOfSecond(3).getMillis()); } public void testBug2182444_ausNSW() { Chronology chronAusNSW = GregorianChronology.getInstance(DateTimeZone.forID("Australia/NSW")); Chronology chronUTC = GregorianChronology.getInstance(DateTimeZone.UTC); DateTime australiaNSWStandardInUTC = new DateTime(2008, 4, 5, 16, 0, 0, 0, chronUTC); DateTime australiaNSWDaylightInUTC = new DateTime(2008, 4, 5, 15, 0, 0, 0, chronUTC); assertTrue("Should be standard time", chronAusNSW.getZone().isStandardOffset(australiaNSWStandardInUTC.getMillis())); assertFalse("Should be daylight time", chronAusNSW.getZone().isStandardOffset(australiaNSWDaylightInUTC.getMillis())); DateTime australiaNSWStandardInAustraliaNSW = australiaNSWStandardInUTC.toDateTime(chronAusNSW); DateTime australiaNSWDaylightInAusraliaNSW = australiaNSWDaylightInUTC.toDateTime(chronAusNSW); assertEquals(2, australiaNSWStandardInAustraliaNSW.getHourOfDay()); assertEquals(australiaNSWStandardInAustraliaNSW.getHourOfDay(), australiaNSWDaylightInAusraliaNSW.getHourOfDay()); assertTrue(australiaNSWStandardInAustraliaNSW.getMillis() != australiaNSWDaylightInAusraliaNSW.getMillis()); assertEquals(australiaNSWStandardInAustraliaNSW, australiaNSWStandardInAustraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWStandardInAustraliaNSW.getMillis() + 3, australiaNSWStandardInAustraliaNSW.withMillisOfSecond(3).getMillis()); assertEquals(australiaNSWDaylightInAusraliaNSW, australiaNSWDaylightInAusraliaNSW.withHourOfDay(2)); assertEquals(australiaNSWDaylightInAusraliaNSW.getMillis() + 3, australiaNSWDaylightInAusraliaNSW.withMillisOfSecond(3).getMillis()); } public void testPeriod() { DateTime a = new DateTime("2010-10-31T02:00:00.000+02:00", ZONE_PARIS); DateTime b = new DateTime("2010-10-31T02:01:00.000+02:00", ZONE_PARIS); Period period = new Period(a, b, PeriodType.standard()); assertEquals("PT1M", period.toString()); } public void testForum4013394_retainOffsetWhenRetainFields_sameOffsetsDifferentZones() { final DateTimeZone fromDTZ = DateTimeZone.forID("Europe/London"); final DateTimeZone toDTZ = DateTimeZone.forID("Europe/Lisbon"); DateTime baseBefore = new DateTime(2007, 10, 28, 1, 15, fromDTZ).minusHours(1); DateTime baseAfter = new DateTime(2007, 10, 28, 1, 15, fromDTZ); DateTime testBefore = baseBefore.withZoneRetainFields(toDTZ); DateTime testAfter = baseAfter.withZoneRetainFields(toDTZ); // toString ignores time-zone but includes offset assertEquals(baseBefore.toString(), testBefore.toString()); assertEquals(baseAfter.toString(), testAfter.toString()); } public void testBug3192457_adjustOffset() { final DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2007, 10, 28, 3, 15, zone); DateTime baseBefore = base.minusHours(2); DateTime baseAfter = base.minusHours(1); assertSame(base, base.withEarlierOffsetAtOverlap()); assertSame(base, base.withLaterOffsetAtOverlap()); assertSame(baseBefore, baseBefore.withEarlierOffsetAtOverlap()); assertSame(baseAfter, baseAfter.withLaterOffsetAtOverlap()); assertEquals(baseBefore, baseAfter.withEarlierOffsetAtOverlap()); assertEquals(baseAfter, baseAfter.withLaterOffsetAtOverlap()); } // ensure Summer time picked //----------------------------------------------------------------------- public void testDateTimeCreation_athens() { DateTimeZone zone = DateTimeZone.forID("Europe/Athens"); DateTime base = new DateTime(2011, 10, 30, 3, 15, zone); assertEquals("2011-10-30T03:15:00.000+03:00", base.toString()); assertEquals("2011-10-30T03:15:00.000+02:00", base.plusHours(1).toString()); } public void testDateTimeCreation_paris() { DateTimeZone zone = DateTimeZone.forID("Europe/Paris"); DateTime base = new DateTime(2011, 10, 30, 2, 15, zone); assertEquals("2011-10-30T02:15:00.000+02:00", base.toString()); assertEquals("2011-10-30T02:15:00.000+01:00", base.plusHours(1).toString()); } public void testDateTimeCreation_london() { DateTimeZone zone = DateTimeZone.forID("Europe/London"); DateTime base = new DateTime(2011, 10, 30, 1, 15, zone); assertEquals("2011-10-30T01:15:00.000+01:00", base.toString()); assertEquals("2011-10-30T01:15:00.000Z", base.plusHours(1).toString()); } public void testDateTimeCreation_newYork() { DateTimeZone zone = DateTimeZone.forID("America/New_York"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-04:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-05:00", base.plusHours(1).toString()); } public void testDateTimeCreation_losAngeles() { DateTimeZone zone = DateTimeZone.forID("America/Los_Angeles"); DateTime base = new DateTime(2010, 11, 7, 1, 15, zone); assertEquals("2010-11-07T01:15:00.000-07:00", base.toString()); assertEquals("2010-11-07T01:15:00.000-08:00", base.plusHours(1).toString()); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(2007, month, day, hour, min, sec, milli, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, String expected, DateTimeZone zone) { doTest_getOffsetFromLocal(year, month, day, hour, min, 0, 0, expected, zone); } private void doTest_getOffsetFromLocal(int year, int month, int day, int hour, int min, int sec, int milli, String expected, DateTimeZone zone) { DateTime dt = new DateTime(year, month, day, hour, min, sec, milli, DateTimeZone.UTC); int offset = zone.getOffsetFromLocal(dt.getMillis()); DateTime res = new DateTime(dt.getMillis() - offset, zone); assertEquals(res.toString(), expected, res.toString()); } }
public void testVersionFlag2() { lastArg = "--version"; testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); }
com.google.javascript.jscomp.CommandLineRunnerTest::testVersionFlag2
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
607
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
testVersionFlag2
/* * 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.Function; import com.google.common.base.Joiner; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author [email protected] (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; // If set, this will be appended to the end of the args list. // For testing args parsing. private String lastArg = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<JSSourceFile> DEFAULT_EXTERNS = ImmutableList.of( JSSourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") ); private List<JSSourceFile> externs; @Override public void setUp() throws Exception { super.setUp(); externs = DEFAULT_EXTERNS; lastCompiler = null; lastArg = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @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 testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {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 testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } 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 testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" + "}"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo() {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($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();", "throw (new function() {}).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();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testSourceSortingOn() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f() {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f() {}", "" }, RhinoErrorReporter.PARSE_ERROR); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.LEGACY, lastCompiler.getOptions().sourceMapFormat); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testVersionFlag2() { lastArg = "--version"; testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } public void testSyntheticExterns() { externs = ImmutableList.of( JSSourceFile.fromCode("externs", "myVar.property;")); test("var theirVar = {}; var myVar = {}; var yourVar = {};", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var yourVar = {};", "var theirVar={},myVar={},yourVar={};"); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var myVar = {};", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } /* 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) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { 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); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } 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); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? (":mod" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? ":mod0" : "")); } } if (lastArg != null) { args.add(lastArg); } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(runner.shouldRunCompiler()); Supplier<List<JSSourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<JSSourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(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 `testVersionFlag2` for the issue `Closure-319`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-319 // // ## Issue-Title: // Cannot see version with --version // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Download sources of latest (r698) command-line version of closure compiler. // 2. Build (with ant from command line). // 3. Run compiler (java -jar compiler.jar --version). // // What is the expected output? // Closure Compiler (http://code.google.com/closure/compiler) // Version: 698 // Built on: 2011/01/17 12:16 // // What do you see instead? // Опция "--version" требует операнд // (Option "--version" requires operand) // and full list of options with description. // // **What version of the product are you using? On what operating system?** // Latest source of command-line compiler from SVN (r698). OS Linux Mint 7, Sun Java 1.6.0\_22. // // **Please provide any additional information below.** // When running compiler with // java -jar compiler.jar --version ? // it shows error message, then version info, then full list of options. // // public void testVersionFlag2() {
607
83
599
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
test
```markdown ## Issue-ID: Closure-319 ## Issue-Title: Cannot see version with --version ## Issue-Description: **What steps will reproduce the problem?** 1. Download sources of latest (r698) command-line version of closure compiler. 2. Build (with ant from command line). 3. Run compiler (java -jar compiler.jar --version). What is the expected output? Closure Compiler (http://code.google.com/closure/compiler) Version: 698 Built on: 2011/01/17 12:16 What do you see instead? Опция "--version" требует операнд (Option "--version" requires operand) and full list of options with description. **What version of the product are you using? On what operating system?** Latest source of command-line compiler from SVN (r698). OS Linux Mint 7, Sun Java 1.6.0\_22. **Please provide any additional information below.** When running compiler with java -jar compiler.jar --version ? it shows error message, then version info, then full list of options. ``` You are a professional Java test case writer, please create a test case named `testVersionFlag2` for the issue `Closure-319`, utilizing the provided issue report information and the following function signature. ```java public void testVersionFlag2() { ```
599
[ "com.google.javascript.jscomp.CommandLineRunner" ]
d9dc4817aa484b906fb43c192eeb0df0ed7eae6a8eae1aa6dc12bca52fa5c635
public void testVersionFlag2()
// You are a professional Java test case writer, please create a test case named `testVersionFlag2` for the issue `Closure-319`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-319 // // ## Issue-Title: // Cannot see version with --version // // ## Issue-Description: // **What steps will reproduce the problem?** // 1. Download sources of latest (r698) command-line version of closure compiler. // 2. Build (with ant from command line). // 3. Run compiler (java -jar compiler.jar --version). // // What is the expected output? // Closure Compiler (http://code.google.com/closure/compiler) // Version: 698 // Built on: 2011/01/17 12:16 // // What do you see instead? // Опция "--version" требует операнд // (Option "--version" requires operand) // and full list of options with description. // // **What version of the product are you using? On what operating system?** // Latest source of command-line compiler from SVN (r698). OS Linux Mint 7, Sun Java 1.6.0\_22. // // **Please provide any additional information below.** // When running compiler with // java -jar compiler.jar --version ? // it shows error message, then version info, then full list of options. // //
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.Function; import com.google.common.base.Joiner; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; /** * Tests for {@link CommandLineRunner}. * * @author [email protected] (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; // If set, this will be appended to the end of the args list. // For testing args parsing. private String lastArg = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<JSSourceFile> DEFAULT_EXTERNS = ImmutableList.of( JSSourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @nosideeffects */ function noSideEffects() {}") ); private List<JSSourceFile> externs; @Override public void setUp() throws Exception { super.setUp(); externs = DEFAULT_EXTERNS; lastCompiler = null; lastArg = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @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 testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {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 testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } 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 testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);" + "}"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo() {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($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();", "throw (new function() {}).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();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, ProcessClosurePrimitives.LATE_PROVIDE_ERROR); } public void testSourceSortingOn() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f() {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f() {}", "" }, RhinoErrorReporter.PARSE_ERROR); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.LEGACY, lastCompiler.getOptions().sourceMapFormat); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestTo( lastCompiler.getModuleGraph(), builder); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testVersionFlag2() { lastArg = "--version"; testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } public void testSyntheticExterns() { externs = ImmutableList.of( JSSourceFile.fromCode("externs", "myVar.property;")); test("var theirVar = {}; var myVar = {}; var yourVar = {};", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var yourVar = {};", "var theirVar={},myVar={},yourVar={};"); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var myVar = {};", SyntacticScopeCreator.VAR_MULTIPLY_DECLARED_ERROR); } /* 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) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { 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); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } 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); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? (":mod" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("mod" + i + ":1" + (i > 0 ? ":mod0" : "")); } } if (lastArg != null) { args.add(lastArg); } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(runner.shouldRunCompiler()); Supplier<List<JSSourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(JSSourceFile.fromCode("input" + i, original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<JSSourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<JSSourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(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 createsFormData() { String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>" + "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' value='off'>" + "<input name='eight' type='checkbox' checked><input name='nine' type='checkbox' value='unset'>" + "<input name='ten' value='text' disabled>" + "</form>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(6, data.size()); assertEquals("one=two", data.get(0).toString()); assertEquals("three=four", data.get(1).toString()); assertEquals("three=five", data.get(2).toString()); assertEquals("six=seven", data.get(3).toString()); assertEquals("seven=on", data.get(4).toString()); // set assertEquals("eight=on", data.get(5).toString()); // default // nine should not appear, not checked checkbox // ten should not appear, disabled }
org.jsoup.nodes.FormElementTest::createsFormData
src/test/java/org/jsoup/nodes/FormElementTest.java
46
src/test/java/org/jsoup/nodes/FormElementTest.java
createsFormData
package org.jsoup.nodes; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** * Tests for FormElement * * @author Jonathan Hedley */ public class FormElementTest { @Test public void hasAssociatedControls() { //"button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" String html = "<form id=1><button id=1><fieldset id=2 /><input id=3><keygen id=4><object id=5><output id=6>" + "<select id=7><option></select><textarea id=8><p id=9>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); assertEquals(8, form.elements().size()); } @Test public void createsFormData() { String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>" + "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' value='off'>" + "<input name='eight' type='checkbox' checked><input name='nine' type='checkbox' value='unset'>" + "<input name='ten' value='text' disabled>" + "</form>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(6, data.size()); assertEquals("one=two", data.get(0).toString()); assertEquals("three=four", data.get(1).toString()); assertEquals("three=five", data.get(2).toString()); assertEquals("six=seven", data.get(3).toString()); assertEquals("seven=on", data.get(4).toString()); // set assertEquals("eight=on", data.get(5).toString()); // default // nine should not appear, not checked checkbox // ten should not appear, disabled } @Test public void createsSubmitableConnection() { String html = "<form action='/search'><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); doc.select("[name=q]").attr("value", "jsoup"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals(Connection.Method.GET, con.request().method()); assertEquals("http://example.com/search", con.request().url().toExternalForm()); List<Connection.KeyVal> dataList = (List<Connection.KeyVal>) con.request().data(); assertEquals("q=jsoup", dataList.get(0).toString()); doc.select("form").attr("method", "post"); Connection con2 = form.submit(); assertEquals(Connection.Method.POST, con2.request().method()); } @Test public void actionWithNoValue() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals("http://example.com/", con.request().url().toExternalForm()); } @Test public void actionWithNoBaseUri() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html); FormElement form = ((FormElement) doc.select("form").first()); boolean threw = false; try { Connection con = form.submit(); } catch (IllegalArgumentException e) { threw = true; assertEquals("Could not determine a form action URL for submit. Ensure you set a base URI when parsing.", e.getMessage()); } assertTrue(threw); } @Test public void formsAddedAfterParseAreFormElements() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form action='http://example.com/search'><input name='q' value='search'>"); Element formEl = doc.select("form").first(); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); } @Test public void controlsAddedAfterParseAreLinkedWithForms() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form />"); Element formEl = doc.select("form").first(); formEl.append("<input name=foo value=bar>"); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); List<Connection.KeyVal> data = form.formData(); assertEquals("foo=bar", data.get(0).toString()); } @Test public void usesOnForCheckboxValueIfNoValueSet() { Document doc = Jsoup.parse("<form><input type=checkbox checked name=foo></form>"); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals("on", data.get(0).value()); assertEquals("foo", data.get(0).key()); } }
// You are a professional Java test case writer, please create a test case named `createsFormData` for the issue `Jsoup-489`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-489 // // ## Issue-Title: // FormElement's formData ignores input checkbox checked without value. // // ## Issue-Description: // When there is input: // // // // ``` // <input type="checkbox" name="testCheckBox" checked="checked" /> // // ``` // // The "formData()" of FormElement's ignores that default value which should be "on" as submitted by browsers. // // // HTML fragment: // // // // ``` // <html> // <head> // <title>Test</title> // </head> // // <body> // // <form name="myForm" method="POST"> // <input type="checkbox" name="testCheckBox" checked="checked" /> Something<br/> // // <input type="submit" value="Submit" /> // </form> // // </body> // </html> // // ``` // // When submiting from Firefox it sends to sever: testCheckBox=on // // // Java code: // // // // ``` // public static void main(String[] args) // { // final String html = "<html>\n" // + " <head>\n" // + " <title>Test</title>\n" // + " </head>\n" // + " \n" // + " <body>\n" // + "\n" // + " <form name=\"myForm\" method=\"POST\">\n" // + " <input type=\"checkbox\" name=\"testCheckBox\" checked=\"checked\" /> Something<br/>\n" // + "\n" // + " <input type=\"submit\" value=\"Submit\" />\n" // + " </form>\n" // + "\n" // + " </body>\n" // + "</html>"; // // final Document document = Jsoup.parse(html); // // final FormElement formElement = (FormElement) document.select("form[name=myForm]").first(); // // for (Connection.KeyVal keyVal : formElement.formData()) // { // System.out.println(keyVal.key() + "=" + keyVal.value()); // } // // } // // ``` // // Output: testCheckBox= // // // Expected output: testCheckBox=on // // // @Test public void createsFormData() {
46
42
26
src/test/java/org/jsoup/nodes/FormElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-489 ## Issue-Title: FormElement's formData ignores input checkbox checked without value. ## Issue-Description: When there is input: ``` <input type="checkbox" name="testCheckBox" checked="checked" /> ``` The "formData()" of FormElement's ignores that default value which should be "on" as submitted by browsers. HTML fragment: ``` <html> <head> <title>Test</title> </head> <body> <form name="myForm" method="POST"> <input type="checkbox" name="testCheckBox" checked="checked" /> Something<br/> <input type="submit" value="Submit" /> </form> </body> </html> ``` When submiting from Firefox it sends to sever: testCheckBox=on Java code: ``` public static void main(String[] args) { final String html = "<html>\n" + " <head>\n" + " <title>Test</title>\n" + " </head>\n" + " \n" + " <body>\n" + "\n" + " <form name=\"myForm\" method=\"POST\">\n" + " <input type=\"checkbox\" name=\"testCheckBox\" checked=\"checked\" /> Something<br/>\n" + "\n" + " <input type=\"submit\" value=\"Submit\" />\n" + " </form>\n" + "\n" + " </body>\n" + "</html>"; final Document document = Jsoup.parse(html); final FormElement formElement = (FormElement) document.select("form[name=myForm]").first(); for (Connection.KeyVal keyVal : formElement.formData()) { System.out.println(keyVal.key() + "=" + keyVal.value()); } } ``` Output: testCheckBox= Expected output: testCheckBox=on ``` You are a professional Java test case writer, please create a test case named `createsFormData` for the issue `Jsoup-489`, utilizing the provided issue report information and the following function signature. ```java @Test public void createsFormData() { ```
26
[ "org.jsoup.nodes.FormElement" ]
daa8cded23e17c8ff9a208a7a9051d9d3ade9b66939ba7938438defa436689b4
@Test public void createsFormData()
// You are a professional Java test case writer, please create a test case named `createsFormData` for the issue `Jsoup-489`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-489 // // ## Issue-Title: // FormElement's formData ignores input checkbox checked without value. // // ## Issue-Description: // When there is input: // // // // ``` // <input type="checkbox" name="testCheckBox" checked="checked" /> // // ``` // // The "formData()" of FormElement's ignores that default value which should be "on" as submitted by browsers. // // // HTML fragment: // // // // ``` // <html> // <head> // <title>Test</title> // </head> // // <body> // // <form name="myForm" method="POST"> // <input type="checkbox" name="testCheckBox" checked="checked" /> Something<br/> // // <input type="submit" value="Submit" /> // </form> // // </body> // </html> // // ``` // // When submiting from Firefox it sends to sever: testCheckBox=on // // // Java code: // // // // ``` // public static void main(String[] args) // { // final String html = "<html>\n" // + " <head>\n" // + " <title>Test</title>\n" // + " </head>\n" // + " \n" // + " <body>\n" // + "\n" // + " <form name=\"myForm\" method=\"POST\">\n" // + " <input type=\"checkbox\" name=\"testCheckBox\" checked=\"checked\" /> Something<br/>\n" // + "\n" // + " <input type=\"submit\" value=\"Submit\" />\n" // + " </form>\n" // + "\n" // + " </body>\n" // + "</html>"; // // final Document document = Jsoup.parse(html); // // final FormElement formElement = (FormElement) document.select("form[name=myForm]").first(); // // for (Connection.KeyVal keyVal : formElement.formData()) // { // System.out.println(keyVal.key() + "=" + keyVal.value()); // } // // } // // ``` // // Output: testCheckBox= // // // Expected output: testCheckBox=on // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; /** * Tests for FormElement * * @author Jonathan Hedley */ public class FormElementTest { @Test public void hasAssociatedControls() { //"button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" String html = "<form id=1><button id=1><fieldset id=2 /><input id=3><keygen id=4><object id=5><output id=6>" + "<select id=7><option></select><textarea id=8><p id=9>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); assertEquals(8, form.elements().size()); } @Test public void createsFormData() { String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>" + "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' value='off'>" + "<input name='eight' type='checkbox' checked><input name='nine' type='checkbox' value='unset'>" + "<input name='ten' value='text' disabled>" + "</form>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals(6, data.size()); assertEquals("one=two", data.get(0).toString()); assertEquals("three=four", data.get(1).toString()); assertEquals("three=five", data.get(2).toString()); assertEquals("six=seven", data.get(3).toString()); assertEquals("seven=on", data.get(4).toString()); // set assertEquals("eight=on", data.get(5).toString()); // default // nine should not appear, not checked checkbox // ten should not appear, disabled } @Test public void createsSubmitableConnection() { String html = "<form action='/search'><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); doc.select("[name=q]").attr("value", "jsoup"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals(Connection.Method.GET, con.request().method()); assertEquals("http://example.com/search", con.request().url().toExternalForm()); List<Connection.KeyVal> dataList = (List<Connection.KeyVal>) con.request().data(); assertEquals("q=jsoup", dataList.get(0).toString()); doc.select("form").attr("method", "post"); Connection con2 = form.submit(); assertEquals(Connection.Method.POST, con2.request().method()); } @Test public void actionWithNoValue() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html, "http://example.com/"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals("http://example.com/", con.request().url().toExternalForm()); } @Test public void actionWithNoBaseUri() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html); FormElement form = ((FormElement) doc.select("form").first()); boolean threw = false; try { Connection con = form.submit(); } catch (IllegalArgumentException e) { threw = true; assertEquals("Could not determine a form action URL for submit. Ensure you set a base URI when parsing.", e.getMessage()); } assertTrue(threw); } @Test public void formsAddedAfterParseAreFormElements() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form action='http://example.com/search'><input name='q' value='search'>"); Element formEl = doc.select("form").first(); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); } @Test public void controlsAddedAfterParseAreLinkedWithForms() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form />"); Element formEl = doc.select("form").first(); formEl.append("<input name=foo value=bar>"); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); List<Connection.KeyVal> data = form.formData(); assertEquals("foo=bar", data.get(0).toString()); } @Test public void usesOnForCheckboxValueIfNoValueSet() { Document doc = Jsoup.parse("<form><input type=checkbox checked name=foo></form>"); FormElement form = (FormElement) doc.select("form").first(); List<Connection.KeyVal> data = form.formData(); assertEquals("on", data.get(0).value()); assertEquals("foo", data.get(0).key()); } }
public void testGetTypedPercent5() throws Exception { String js = "/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"; assertEquals(100.0, getTypedPercent(js), 0.1); }
com.google.javascript.jscomp.TypeCheckTest::testGetTypedPercent5
test/com/google/javascript/jscomp/TypeCheckTest.java
7,784
test/com/google/javascript/jscomp/TypeCheckTest.java
testGetTypedPercent5
/* * 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 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 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 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 `testGetTypedPercent5` for the issue `Closure-482`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-482 // // ## Issue-Title: // @enum does not type correctly // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. create an enum with any syntax // my example: // /\*\* // @type {Object} // \*/ // var NS = {}; // // /\*\* // @enum {number} // \*/ // NS.keys = { // a: 1, // b: 2, // c: 3 // }; // // /\*\* // @enum // \*/ // window['gKEYS'] = NS.keys; // // // 2. complie with --compilation\_level ADVANCED\_OPTIMIZATIONS --summary\_detail\_level 3 --warning\_level VERBOSE // // 3. look at the % typed // // **What is the expected output? What do you see instead?** // it shouldn't count the enum as un-typed; it does... // // **What version of the product are you using? On what operating system?** // Version: 1043 // Built on: 2011/05/02 19:47 // // **Please provide any additional information below.** // // i also tried to tersely coerce the type, eg: // /\*\* @type {number} \*/ a: (/\*\* @type {number} \*/(1)), // // which has no effect. // // public void testGetTypedPercent5() throws Exception {
7,784
66
7,781
test/com/google/javascript/jscomp/TypeCheckTest.java
test
```markdown ## Issue-ID: Closure-482 ## Issue-Title: @enum does not type correctly ## Issue-Description: **What steps will reproduce the problem?** 1. create an enum with any syntax my example: /\*\* @type {Object} \*/ var NS = {}; /\*\* @enum {number} \*/ NS.keys = { a: 1, b: 2, c: 3 }; /\*\* @enum \*/ window['gKEYS'] = NS.keys; 2. complie with --compilation\_level ADVANCED\_OPTIMIZATIONS --summary\_detail\_level 3 --warning\_level VERBOSE 3. look at the % typed **What is the expected output? What do you see instead?** it shouldn't count the enum as un-typed; it does... **What version of the product are you using? On what operating system?** Version: 1043 Built on: 2011/05/02 19:47 **Please provide any additional information below.** i also tried to tersely coerce the type, eg: /\*\* @type {number} \*/ a: (/\*\* @type {number} \*/(1)), which has no effect. ``` You are a professional Java test case writer, please create a test case named `testGetTypedPercent5` for the issue `Closure-482`, utilizing the provided issue report information and the following function signature. ```java public void testGetTypedPercent5() throws Exception { ```
7,781
[ "com.google.javascript.jscomp.TypeCheck" ]
dabd59958b99491a2252f2afb4acefc837902bf9e0c33d3c445d5a8242d0f47e
public void testGetTypedPercent5() throws Exception
// You are a professional Java test case writer, please create a test case named `testGetTypedPercent5` for the issue `Closure-482`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-482 // // ## Issue-Title: // @enum does not type correctly // // ## Issue-Description: // **What steps will reproduce the problem?** // // 1. create an enum with any syntax // my example: // /\*\* // @type {Object} // \*/ // var NS = {}; // // /\*\* // @enum {number} // \*/ // NS.keys = { // a: 1, // b: 2, // c: 3 // }; // // /\*\* // @enum // \*/ // window['gKEYS'] = NS.keys; // // // 2. complie with --compilation\_level ADVANCED\_OPTIMIZATIONS --summary\_detail\_level 3 --warning\_level VERBOSE // // 3. look at the % typed // // **What is the expected output? What do you see instead?** // it shouldn't count the enum as un-typed; it does... // // **What version of the product are you using? On what operating system?** // Version: 1043 // Built on: 2011/05/02 19:47 // // **Please provide any additional information below.** // // i also tried to tersely coerce the type, eg: // /\*\* @type {number} \*/ a: (/\*\* @type {number} \*/(1)), // // which has no effect. // //
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 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 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 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 constructorValidationOkWithBlankName() { DocumentType fail = new DocumentType("","", "", ""); }
org.jsoup.nodes.DocumentTypeTest::constructorValidationOkWithBlankName
src/test/java/org/jsoup/nodes/DocumentTypeTest.java
15
src/test/java/org/jsoup/nodes/DocumentTypeTest.java
constructorValidationOkWithBlankName
package org.jsoup.nodes; import org.junit.Test; import static org.junit.Assert.*; /** * Tests for the DocumentType node * * @author Jonathan Hedley, http://jonathanhedley.com/ */ public class DocumentTypeTest { @Test public void constructorValidationOkWithBlankName() { DocumentType fail = new DocumentType("","", "", ""); } @Test(expected = IllegalArgumentException.class) public void constructorValidationThrowsExceptionOnNulls() { DocumentType fail = new DocumentType("html", null, null, ""); } @Test public void constructorValidationOkWithBlankPublicAndSystemIds() { DocumentType fail = new DocumentType("html","", "",""); } @Test public void outerHtmlGeneration() { DocumentType html5 = new DocumentType("html", "", "", ""); assertEquals("<!DOCTYPE html>", html5.outerHtml()); DocumentType publicDocType = new DocumentType("html", "-//IETF//DTD HTML//", "", ""); assertEquals("<!DOCTYPE html PUBLIC \"-//IETF//DTD HTML//\">", publicDocType.outerHtml()); DocumentType systemDocType = new DocumentType("html", "", "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd", ""); assertEquals("<!DOCTYPE html \"http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd\">", systemDocType.outerHtml()); DocumentType combo = new DocumentType("notHtml", "--public", "--system", ""); assertEquals("<!DOCTYPE notHtml PUBLIC \"--public\" \"--system\">", combo.outerHtml()); } }
// You are a professional Java test case writer, please create a test case named `constructorValidationOkWithBlankName` for the issue `Jsoup-460`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-460 // // ## Issue-Title: // "<!DOCTYPE>" IllegalArgumentException: String must not be empty // // ## Issue-Description: // While this may be a contrived example, Jsoup.parse("<!DOCTYPE>") throws an exception, this was unexpected. Possibly related, a proper document with <!DOCTYPE> (no name) is generating corrupt html e.g. "<!DOCTYPE <html> ..." (missing right angle bracket on DOCTYPE.) // // // Spec says "When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), [...]" // // // // @Test public void constructorValidationOkWithBlankName() {
15
40
12
src/test/java/org/jsoup/nodes/DocumentTypeTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-460 ## Issue-Title: "<!DOCTYPE>" IllegalArgumentException: String must not be empty ## Issue-Description: While this may be a contrived example, Jsoup.parse("<!DOCTYPE>") throws an exception, this was unexpected. Possibly related, a proper document with <!DOCTYPE> (no name) is generating corrupt html e.g. "<!DOCTYPE <html> ..." (missing right angle bracket on DOCTYPE.) Spec says "When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), [...]" ``` You are a professional Java test case writer, please create a test case named `constructorValidationOkWithBlankName` for the issue `Jsoup-460`, utilizing the provided issue report information and the following function signature. ```java @Test public void constructorValidationOkWithBlankName() { ```
12
[ "org.jsoup.nodes.DocumentType" ]
db90c8fdc8d3e760b855b47a4354c6d040022d1518fea6907654cadd490331c2
@Test public void constructorValidationOkWithBlankName()
// You are a professional Java test case writer, please create a test case named `constructorValidationOkWithBlankName` for the issue `Jsoup-460`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-460 // // ## Issue-Title: // "<!DOCTYPE>" IllegalArgumentException: String must not be empty // // ## Issue-Description: // While this may be a contrived example, Jsoup.parse("<!DOCTYPE>") throws an exception, this was unexpected. Possibly related, a proper document with <!DOCTYPE> (no name) is generating corrupt html e.g. "<!DOCTYPE <html> ..." (missing right angle bracket on DOCTYPE.) // // // Spec says "When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), [...]" // // // //
Jsoup
package org.jsoup.nodes; import org.junit.Test; import static org.junit.Assert.*; /** * Tests for the DocumentType node * * @author Jonathan Hedley, http://jonathanhedley.com/ */ public class DocumentTypeTest { @Test public void constructorValidationOkWithBlankName() { DocumentType fail = new DocumentType("","", "", ""); } @Test(expected = IllegalArgumentException.class) public void constructorValidationThrowsExceptionOnNulls() { DocumentType fail = new DocumentType("html", null, null, ""); } @Test public void constructorValidationOkWithBlankPublicAndSystemIds() { DocumentType fail = new DocumentType("html","", "",""); } @Test public void outerHtmlGeneration() { DocumentType html5 = new DocumentType("html", "", "", ""); assertEquals("<!DOCTYPE html>", html5.outerHtml()); DocumentType publicDocType = new DocumentType("html", "-//IETF//DTD HTML//", "", ""); assertEquals("<!DOCTYPE html PUBLIC \"-//IETF//DTD HTML//\">", publicDocType.outerHtml()); DocumentType systemDocType = new DocumentType("html", "", "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd", ""); assertEquals("<!DOCTYPE html \"http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd\">", systemDocType.outerHtml()); DocumentType combo = new DocumentType("notHtml", "--public", "--system", ""); assertEquals("<!DOCTYPE notHtml PUBLIC \"--public\" \"--system\">", combo.outerHtml()); } }
public void testStopBursting() throws Exception { String[] args = new String[] { "-azc" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertFalse( "Confirm -c is not set", cl.hasOption("c") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue(cl.getArgList().contains("zc")); }
org.apache.commons.cli.PosixParserTest::testStopBursting
src/test/org/apache/commons/cli/PosixParserTest.java
142
src/test/org/apache/commons/cli/PosixParserTest.java
testStopBursting
/** * 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.util.Arrays; import java.util.List; import junit.framework.TestCase; /** * Test case for the PosixParser. * * @version $Revision$, $Date$ */ public class PosixParserTest extends TestCase { private Options options = null; private Parser parser = null; public void setUp() { options = new Options() .addOption("a", "enable-a", false, "turn [a] on or off") .addOption("b", "bfile", true, "set the value of [b]") .addOption("c", "copt", false, "turn [c] on or off"); parser = new PosixParser(); } public void testSimpleShort() throws Exception { String[] args = new String[] { "-a", "-b", "toast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testSimpleLong() throws Exception { String[] args = new String[] { "--enable-a", "--bfile", "toast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm arg of --bfile", cl.getOptionValue( "bfile" ).equals( "toast" ) ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testComplexShort() throws Exception { String[] args = new String[] { "-acbtoast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testUnrecognizedOption() throws Exception { String[] args = new String[] { "-adbtoast", "foo", "bar" }; try { parser.parse(options, args); fail("UnrecognizedOptionException wasn't thrown"); } catch (UnrecognizedOptionException e) { assertEquals("-adbtoast", e.getOption()); } } public void testMissingArg() throws Exception { String[] args = new String[] { "-acb" }; boolean caught = false; try { parser.parse(options, args); } catch (MissingArgumentException e) { caught = true; assertEquals("option missing an argument", "b", e.getOption().getOpt()); } assertTrue( "Confirm MissingArgumentException caught", caught ); } public void testStop() throws Exception { String[] args = new String[] { "-c", "foober", "-btoast" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); } public void testStopBursting() throws Exception { String[] args = new String[] { "-azc" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertFalse( "Confirm -c is not set", cl.hasOption("c") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue(cl.getArgList().contains("zc")); } public void testMultiple() throws Exception { String[] args = new String[] { "-c", "foobar", "-btoast" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); cl = parser.parse(options, cl.getArgs() ); assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); } public void testMultipleWithLong() throws Exception { String[] args = new String[] { "--copt", "foobar", "--bfile", "toast" }; CommandLine cl = parser.parse(options,args, true); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); cl = parser.parse(options, cl.getArgs() ); assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); } public void testDoubleDash() throws Exception { String[] args = new String[] { "--copt", "--", "-b", "toast" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm -b is not set", ! cl.hasOption("b") ); assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); } public void testSingleDash() throws Exception { String[] args = new String[] { "--copt", "-b", "-", "-a", "-" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("-") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-") ); } /** * Real world test with long and short options. */ public void testLongOptionWithShort() throws Exception { Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print version information"); Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items"); Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items"); Option timeLimit = OptionBuilder.withLongOpt("limit").hasArg() .withValueSeparator() .withDescription("Set time limit for execution, in mintues") .create("l"); Option age = OptionBuilder.withLongOpt("age").hasArg() .withValueSeparator() .withDescription("Age (in days) of cache item before being recomputed") .create("a"); Option server = OptionBuilder.withLongOpt("server").hasArg() .withValueSeparator() .withDescription("The NLT server address") .create("s"); Option numResults = OptionBuilder.withLongOpt("results").hasArg() .withValueSeparator() .withDescription("Number of results per item") .create("r"); Option configFile = OptionBuilder.withLongOpt("file").hasArg() .withValueSeparator() .withDescription("Use the specified configuration file") .create(); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(newRun); options.addOption(trackerRun); options.addOption(timeLimit); options.addOption(age); options.addOption(server); options.addOption(numResults); options.addOption(configFile); // create the command line parser CommandLineParser parser = new PosixParser(); String[] args = new String[] { "-v", "-l", "10", "-age", "5", "-file", "filename" }; CommandLine line = parser.parse(options, args); assertTrue(line.hasOption("v")); assertEquals(line.getOptionValue("l"), "10"); assertEquals(line.getOptionValue("limit"), "10"); assertEquals(line.getOptionValue("a"), "5"); assertEquals(line.getOptionValue("age"), "5"); assertEquals(line.getOptionValue("file"), "filename"); } public void testPropertiesOption() throws Exception { String[] args = new String[] { "-Jsource=1.5", "-J", "target", "1.5", "foo" }; Options options = new Options(); options.addOption(OptionBuilder.withValueSeparator().hasArgs(2).create('J')); Parser parser = new PosixParser(); CommandLine cl = parser.parse(options, args); List values = Arrays.asList(cl.getOptionValues("J")); assertNotNull("null values", values); assertEquals("number of values", 4, values.size()); assertEquals("value 1", "source", values.get(0)); assertEquals("value 2", "1.5", values.get(1)); assertEquals("value 3", "target", values.get(2)); assertEquals("value 4", "1.5", values.get(3)); List argsleft = cl.getArgList(); assertEquals("Should be 1 arg left",1,argsleft.size()); assertEquals("Expecting foo","foo",argsleft.get(0)); } }
// You are a professional Java test case writer, please create a test case named `testStopBursting` for the issue `Cli-CLI-163`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-163 // // ## Issue-Title: // PosixParser keeps bursting tokens even if a non option character is found // // ## Issue-Description: // // PosixParser doesn't stop the bursting process of a token if stopAtNonOption is enabled and a non option character is encountered. // // // For example if the options a and b are defined, with stopAtNonOption=true the following command line: // // // // // ``` // -azb // ``` // // // is turned into: // // // // // ``` // -a zb -b // ``` // // // the right output should be: // // // // // ``` // -a zb // ``` // // // // // public void testStopBursting() throws Exception {
142
17
132
src/test/org/apache/commons/cli/PosixParserTest.java
src/test
```markdown ## Issue-ID: Cli-CLI-163 ## Issue-Title: PosixParser keeps bursting tokens even if a non option character is found ## Issue-Description: PosixParser doesn't stop the bursting process of a token if stopAtNonOption is enabled and a non option character is encountered. For example if the options a and b are defined, with stopAtNonOption=true the following command line: ``` -azb ``` is turned into: ``` -a zb -b ``` the right output should be: ``` -a zb ``` ``` You are a professional Java test case writer, please create a test case named `testStopBursting` for the issue `Cli-CLI-163`, utilizing the provided issue report information and the following function signature. ```java public void testStopBursting() throws Exception { ```
132
[ "org.apache.commons.cli.PosixParser" ]
dbc9649d0fc7a2e46fd7f61d7ee7dc22f15a08e66d7682df6e836af9ee04ec9c
public void testStopBursting() throws Exception
// You are a professional Java test case writer, please create a test case named `testStopBursting` for the issue `Cli-CLI-163`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Cli-CLI-163 // // ## Issue-Title: // PosixParser keeps bursting tokens even if a non option character is found // // ## Issue-Description: // // PosixParser doesn't stop the bursting process of a token if stopAtNonOption is enabled and a non option character is encountered. // // // For example if the options a and b are defined, with stopAtNonOption=true the following command line: // // // // // ``` // -azb // ``` // // // is turned into: // // // // // ``` // -a zb -b // ``` // // // the right output should be: // // // // // ``` // -a zb // ``` // // // // //
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.util.Arrays; import java.util.List; import junit.framework.TestCase; /** * Test case for the PosixParser. * * @version $Revision$, $Date$ */ public class PosixParserTest extends TestCase { private Options options = null; private Parser parser = null; public void setUp() { options = new Options() .addOption("a", "enable-a", false, "turn [a] on or off") .addOption("b", "bfile", true, "set the value of [b]") .addOption("c", "copt", false, "turn [c] on or off"); parser = new PosixParser(); } public void testSimpleShort() throws Exception { String[] args = new String[] { "-a", "-b", "toast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testSimpleLong() throws Exception { String[] args = new String[] { "--enable-a", "--bfile", "toast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm arg of --bfile", cl.getOptionValue( "bfile" ).equals( "toast" ) ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testComplexShort() throws Exception { String[] args = new String[] { "-acbtoast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testUnrecognizedOption() throws Exception { String[] args = new String[] { "-adbtoast", "foo", "bar" }; try { parser.parse(options, args); fail("UnrecognizedOptionException wasn't thrown"); } catch (UnrecognizedOptionException e) { assertEquals("-adbtoast", e.getOption()); } } public void testMissingArg() throws Exception { String[] args = new String[] { "-acb" }; boolean caught = false; try { parser.parse(options, args); } catch (MissingArgumentException e) { caught = true; assertEquals("option missing an argument", "b", e.getOption().getOpt()); } assertTrue( "Confirm MissingArgumentException caught", caught ); } public void testStop() throws Exception { String[] args = new String[] { "-c", "foober", "-btoast" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); } public void testStopBursting() throws Exception { String[] args = new String[] { "-azc" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertFalse( "Confirm -c is not set", cl.hasOption("c") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue(cl.getArgList().contains("zc")); } public void testMultiple() throws Exception { String[] args = new String[] { "-c", "foobar", "-btoast" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); cl = parser.parse(options, cl.getArgs() ); assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); } public void testMultipleWithLong() throws Exception { String[] args = new String[] { "--copt", "foobar", "--bfile", "toast" }; CommandLine cl = parser.parse(options,args, true); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); cl = parser.parse(options, cl.getArgs() ); assertTrue( "Confirm -c is not set", ! cl.hasOption("c") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") ); } public void testDoubleDash() throws Exception { String[] args = new String[] { "--copt", "--", "-b", "toast" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm -b is not set", ! cl.hasOption("b") ); assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); } public void testSingleDash() throws Exception { String[] args = new String[] { "--copt", "-b", "-", "-a", "-" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("-") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-") ); } /** * Real world test with long and short options. */ public void testLongOptionWithShort() throws Exception { Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print version information"); Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items"); Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items"); Option timeLimit = OptionBuilder.withLongOpt("limit").hasArg() .withValueSeparator() .withDescription("Set time limit for execution, in mintues") .create("l"); Option age = OptionBuilder.withLongOpt("age").hasArg() .withValueSeparator() .withDescription("Age (in days) of cache item before being recomputed") .create("a"); Option server = OptionBuilder.withLongOpt("server").hasArg() .withValueSeparator() .withDescription("The NLT server address") .create("s"); Option numResults = OptionBuilder.withLongOpt("results").hasArg() .withValueSeparator() .withDescription("Number of results per item") .create("r"); Option configFile = OptionBuilder.withLongOpt("file").hasArg() .withValueSeparator() .withDescription("Use the specified configuration file") .create(); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(newRun); options.addOption(trackerRun); options.addOption(timeLimit); options.addOption(age); options.addOption(server); options.addOption(numResults); options.addOption(configFile); // create the command line parser CommandLineParser parser = new PosixParser(); String[] args = new String[] { "-v", "-l", "10", "-age", "5", "-file", "filename" }; CommandLine line = parser.parse(options, args); assertTrue(line.hasOption("v")); assertEquals(line.getOptionValue("l"), "10"); assertEquals(line.getOptionValue("limit"), "10"); assertEquals(line.getOptionValue("a"), "5"); assertEquals(line.getOptionValue("age"), "5"); assertEquals(line.getOptionValue("file"), "filename"); } public void testPropertiesOption() throws Exception { String[] args = new String[] { "-Jsource=1.5", "-J", "target", "1.5", "foo" }; Options options = new Options(); options.addOption(OptionBuilder.withValueSeparator().hasArgs(2).create('J')); Parser parser = new PosixParser(); CommandLine cl = parser.parse(options, args); List values = Arrays.asList(cl.getOptionValues("J")); assertNotNull("null values", values); assertEquals("number of values", 4, values.size()); assertEquals("value 1", "source", values.get(0)); assertEquals("value 2", "1.5", values.get(1)); assertEquals("value 3", "target", values.get(2)); assertEquals("value 4", "1.5", values.get(3)); List argsleft = cl.getArgList(); assertEquals("Should be 1 arg left",1,argsleft.size()); assertEquals("Expecting foo","foo",argsleft.get(0)); } }
public void testMath280() throws MathException { NormalDistribution normal = new NormalDistributionImpl(0,1); double result = normal.inverseCumulativeProbability(0.9772498680518209); assertEquals(2.0, result, 1.0e-12); }
org.apache.commons.math.distribution.NormalDistributionTest::testMath280
src/test/org/apache/commons/math/distribution/NormalDistributionTest.java
170
src/test/org/apache/commons/math/distribution/NormalDistributionTest.java
testMath280
/* * 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.distribution; import org.apache.commons.math.MathException; /** * Test cases for NormalDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. * * @version $Revision$ $Date$ */ public class NormalDistributionTest extends ContinuousDistributionAbstractTest { /** * Constructor for NormalDistributionTest. * @param arg0 */ public NormalDistributionTest(String arg0) { super(arg0); } //-------------- Implementations for abstract methods ----------------------- /** Creates the default continuous distribution instance to use in tests. */ @Override public ContinuousDistribution makeDistribution() { return new NormalDistributionImpl(2.1, 1.4); } /** Creates the default cumulative probability distribution test input values */ @Override public double[] makeCumulativeTestPoints() { // quantiles computed using R return new double[] {-2.226325d, -1.156887d, -0.6439496d, -0.2027951d, 0.3058278d, 6.426325d, 5.356887d, 4.84395d, 4.402795d, 3.894172d}; } /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d}; } // --------------------- Override tolerance -------------- @Override protected void setUp() throws Exception { super.setUp(); setTolerance(1E-6); } //---------------------------- Additional test cases ------------------------- private void verifyQuantiles() throws Exception { NormalDistribution distribution = (NormalDistribution) getDistribution(); double mu = distribution.getMean(); double sigma = distribution.getStandardDeviation(); setCumulativeTestPoints( new double[] {mu - 2 *sigma, mu - sigma, mu, mu + sigma, mu +2 * sigma, mu +3 * sigma, mu + 4 * sigma, mu + 5 * sigma}); // Quantiles computed using R (same as Mathematica) setCumulativeTestValues(new double[] {0.02275013, 0.1586553, 0.5, 0.8413447, 0.9772499, 0.9986501, 0.9999683, 0.9999997}); verifyCumulativeProbabilities(); } public void testQuantiles() throws Exception { verifyQuantiles(); setDistribution(new NormalDistributionImpl(0, 1)); verifyQuantiles(); setDistribution(new NormalDistributionImpl(0, 0.1)); verifyQuantiles(); } public void testInverseCumulativeProbabilityExtremes() throws Exception { setInverseCumulativeTestPoints(new double[] {0, 1}); setInverseCumulativeTestValues( new double[] {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY}); verifyInverseCumulativeProbabilities(); } public void testGetMean() { NormalDistribution distribution = (NormalDistribution) getDistribution(); assertEquals(2.1, distribution.getMean(), 0); } public void testSetMean() throws Exception { double mu = Math.random(); NormalDistribution distribution = (NormalDistribution) getDistribution(); distribution.setMean(mu); verifyQuantiles(); } public void testGetStandardDeviation() { NormalDistribution distribution = (NormalDistribution) getDistribution(); assertEquals(1.4, distribution.getStandardDeviation(), 0); } public void testSetStandardDeviation() throws Exception { double sigma = 0.1d + Math.random(); NormalDistribution distribution = (NormalDistribution) getDistribution(); distribution.setStandardDeviation(sigma); assertEquals(sigma, distribution.getStandardDeviation(), 0); verifyQuantiles(); try { distribution.setStandardDeviation(0); fail("Expecting IllegalArgumentException for sd = 0"); } catch (IllegalArgumentException ex) { // Expected } } public void testDensity() { double [] x = new double[]{-2, -1, 0, 1, 2}; // R 2.5: print(dnorm(c(-2,-1,0,1,2)), digits=10) checkDensity(0, 1, x, new double[]{0.05399096651, 0.24197072452, 0.39894228040, 0.24197072452, 0.05399096651}); // R 2.5: print(dnorm(c(-2,-1,0,1,2), mean=1.1), digits=10) checkDensity(1.1, 1, x, new double[]{0.003266819056,0.043983595980,0.217852177033,0.396952547477,0.266085249899}); } private void checkDensity(double mean, double sd, double[] x, double[] expected) { NormalDistribution d = new NormalDistributionImpl(mean, sd); for (int i = 0; i < x.length; i++) { assertEquals(expected[i], d.density(x[i]), 1e-9); } } /** * Check to make sure top-coding of extreme values works correctly. * Verifies fix for JIRA MATH-167 */ public void testExtremeValues() throws Exception { NormalDistribution distribution = (NormalDistribution) getDistribution(); distribution.setMean(0); distribution.setStandardDeviation(1); for (int i = 0; i < 100; i+=5) { // make sure no convergence exception double lowerTail = distribution.cumulativeProbability(-i); double upperTail = distribution.cumulativeProbability(i); if (i < 10) { // make sure not top-coded assertTrue(lowerTail > 0.0d); assertTrue(upperTail < 1.0d); } else { // make sure top coding not reversed assertTrue(lowerTail < 0.00001); assertTrue(upperTail > 0.99999); } } } public void testMath280() throws MathException { NormalDistribution normal = new NormalDistributionImpl(0,1); double result = normal.inverseCumulativeProbability(0.9772498680518209); assertEquals(2.0, result, 1.0e-12); } }
// You are a professional Java test case writer, please create a test case named `testMath280` for the issue `Math-MATH-280`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-280 // // ## Issue-Title: // bug in inverseCumulativeProbability() for Normal Distribution // // ## Issue-Description: // // * @version $Revision: 617953 $ $Date: 2008-02-02 22:54:00 -0700 (Sat, 02 Feb 2008) $ // // \*/ // // public class NormalDistributionImpl extends AbstractContinuousDistribution // // // * @version $Revision: 506600 $ $Date: 2007-02-12 12:35:59 -0700 (Mon, 12 Feb 2007) $ // // \*/ // // public abstract class AbstractContinuousDistribution // // // This code: // // // DistributionFactory factory = app.getDistributionFactory(); // // NormalDistribution normal = factory.createNormalDistribution(0,1); // // double result = normal.inverseCumulativeProbability(0.9772498680518209); // // // gives the exception below. It should return (approx) 2.0000... // // // normal.inverseCumulativeProbability(0.977249868051820); works fine // // // These also give errors: // // 0.9986501019683698 (should return 3.0000...) // // 0.9999683287581673 (should return 4.0000...) // // // org.apache.commons.math.MathException: Number of iterations=1, maximum iterations=2,147,483,647, initial=1, lower bound=0, upper bound=179,769,313,486,231,570,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000, final a value=0, final b value=2, f(a)=-0.477, f(b)=0 // // at org.apache.commons.math.distribution.AbstractContinuousDistribution.inverseCumulativeProbability(AbstractContinuousDistribution.java:103) // // at org.apache.commons.math.distribution.NormalDistributionImpl.inverseCumulativeProbability(NormalDistributionImpl.java:145) // // // // // public void testMath280() throws MathException {
170
85
166
src/test/org/apache/commons/math/distribution/NormalDistributionTest.java
src/test
```markdown ## Issue-ID: Math-MATH-280 ## Issue-Title: bug in inverseCumulativeProbability() for Normal Distribution ## Issue-Description: * @version $Revision: 617953 $ $Date: 2008-02-02 22:54:00 -0700 (Sat, 02 Feb 2008) $ \*/ public class NormalDistributionImpl extends AbstractContinuousDistribution * @version $Revision: 506600 $ $Date: 2007-02-12 12:35:59 -0700 (Mon, 12 Feb 2007) $ \*/ public abstract class AbstractContinuousDistribution This code: DistributionFactory factory = app.getDistributionFactory(); NormalDistribution normal = factory.createNormalDistribution(0,1); double result = normal.inverseCumulativeProbability(0.9772498680518209); gives the exception below. It should return (approx) 2.0000... normal.inverseCumulativeProbability(0.977249868051820); works fine These also give errors: 0.9986501019683698 (should return 3.0000...) 0.9999683287581673 (should return 4.0000...) org.apache.commons.math.MathException: Number of iterations=1, maximum iterations=2,147,483,647, initial=1, lower bound=0, upper bound=179,769,313,486,231,570,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000, final a value=0, final b value=2, f(a)=-0.477, f(b)=0 at org.apache.commons.math.distribution.AbstractContinuousDistribution.inverseCumulativeProbability(AbstractContinuousDistribution.java:103) at org.apache.commons.math.distribution.NormalDistributionImpl.inverseCumulativeProbability(NormalDistributionImpl.java:145) ``` You are a professional Java test case writer, please create a test case named `testMath280` for the issue `Math-MATH-280`, utilizing the provided issue report information and the following function signature. ```java public void testMath280() throws MathException { ```
166
[ "org.apache.commons.math.analysis.solvers.UnivariateRealSolverUtils" ]
dbd253a14e2a2c62d2577282600ea489e854fe74f4d9dc5d43427675dba8b612
public void testMath280() throws MathException
// You are a professional Java test case writer, please create a test case named `testMath280` for the issue `Math-MATH-280`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-280 // // ## Issue-Title: // bug in inverseCumulativeProbability() for Normal Distribution // // ## Issue-Description: // // * @version $Revision: 617953 $ $Date: 2008-02-02 22:54:00 -0700 (Sat, 02 Feb 2008) $ // // \*/ // // public class NormalDistributionImpl extends AbstractContinuousDistribution // // // * @version $Revision: 506600 $ $Date: 2007-02-12 12:35:59 -0700 (Mon, 12 Feb 2007) $ // // \*/ // // public abstract class AbstractContinuousDistribution // // // This code: // // // DistributionFactory factory = app.getDistributionFactory(); // // NormalDistribution normal = factory.createNormalDistribution(0,1); // // double result = normal.inverseCumulativeProbability(0.9772498680518209); // // // gives the exception below. It should return (approx) 2.0000... // // // normal.inverseCumulativeProbability(0.977249868051820); works fine // // // These also give errors: // // 0.9986501019683698 (should return 3.0000...) // // 0.9999683287581673 (should return 4.0000...) // // // org.apache.commons.math.MathException: Number of iterations=1, maximum iterations=2,147,483,647, initial=1, lower bound=0, upper bound=179,769,313,486,231,570,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000, final a value=0, final b value=2, f(a)=-0.477, f(b)=0 // // at org.apache.commons.math.distribution.AbstractContinuousDistribution.inverseCumulativeProbability(AbstractContinuousDistribution.java:103) // // at org.apache.commons.math.distribution.NormalDistributionImpl.inverseCumulativeProbability(NormalDistributionImpl.java:145) // // // // //
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.distribution; import org.apache.commons.math.MathException; /** * Test cases for NormalDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. * * @version $Revision$ $Date$ */ public class NormalDistributionTest extends ContinuousDistributionAbstractTest { /** * Constructor for NormalDistributionTest. * @param arg0 */ public NormalDistributionTest(String arg0) { super(arg0); } //-------------- Implementations for abstract methods ----------------------- /** Creates the default continuous distribution instance to use in tests. */ @Override public ContinuousDistribution makeDistribution() { return new NormalDistributionImpl(2.1, 1.4); } /** Creates the default cumulative probability distribution test input values */ @Override public double[] makeCumulativeTestPoints() { // quantiles computed using R return new double[] {-2.226325d, -1.156887d, -0.6439496d, -0.2027951d, 0.3058278d, 6.426325d, 5.356887d, 4.84395d, 4.402795d, 3.894172d}; } /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d}; } // --------------------- Override tolerance -------------- @Override protected void setUp() throws Exception { super.setUp(); setTolerance(1E-6); } //---------------------------- Additional test cases ------------------------- private void verifyQuantiles() throws Exception { NormalDistribution distribution = (NormalDistribution) getDistribution(); double mu = distribution.getMean(); double sigma = distribution.getStandardDeviation(); setCumulativeTestPoints( new double[] {mu - 2 *sigma, mu - sigma, mu, mu + sigma, mu +2 * sigma, mu +3 * sigma, mu + 4 * sigma, mu + 5 * sigma}); // Quantiles computed using R (same as Mathematica) setCumulativeTestValues(new double[] {0.02275013, 0.1586553, 0.5, 0.8413447, 0.9772499, 0.9986501, 0.9999683, 0.9999997}); verifyCumulativeProbabilities(); } public void testQuantiles() throws Exception { verifyQuantiles(); setDistribution(new NormalDistributionImpl(0, 1)); verifyQuantiles(); setDistribution(new NormalDistributionImpl(0, 0.1)); verifyQuantiles(); } public void testInverseCumulativeProbabilityExtremes() throws Exception { setInverseCumulativeTestPoints(new double[] {0, 1}); setInverseCumulativeTestValues( new double[] {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY}); verifyInverseCumulativeProbabilities(); } public void testGetMean() { NormalDistribution distribution = (NormalDistribution) getDistribution(); assertEquals(2.1, distribution.getMean(), 0); } public void testSetMean() throws Exception { double mu = Math.random(); NormalDistribution distribution = (NormalDistribution) getDistribution(); distribution.setMean(mu); verifyQuantiles(); } public void testGetStandardDeviation() { NormalDistribution distribution = (NormalDistribution) getDistribution(); assertEquals(1.4, distribution.getStandardDeviation(), 0); } public void testSetStandardDeviation() throws Exception { double sigma = 0.1d + Math.random(); NormalDistribution distribution = (NormalDistribution) getDistribution(); distribution.setStandardDeviation(sigma); assertEquals(sigma, distribution.getStandardDeviation(), 0); verifyQuantiles(); try { distribution.setStandardDeviation(0); fail("Expecting IllegalArgumentException for sd = 0"); } catch (IllegalArgumentException ex) { // Expected } } public void testDensity() { double [] x = new double[]{-2, -1, 0, 1, 2}; // R 2.5: print(dnorm(c(-2,-1,0,1,2)), digits=10) checkDensity(0, 1, x, new double[]{0.05399096651, 0.24197072452, 0.39894228040, 0.24197072452, 0.05399096651}); // R 2.5: print(dnorm(c(-2,-1,0,1,2), mean=1.1), digits=10) checkDensity(1.1, 1, x, new double[]{0.003266819056,0.043983595980,0.217852177033,0.396952547477,0.266085249899}); } private void checkDensity(double mean, double sd, double[] x, double[] expected) { NormalDistribution d = new NormalDistributionImpl(mean, sd); for (int i = 0; i < x.length; i++) { assertEquals(expected[i], d.density(x[i]), 1e-9); } } /** * Check to make sure top-coding of extreme values works correctly. * Verifies fix for JIRA MATH-167 */ public void testExtremeValues() throws Exception { NormalDistribution distribution = (NormalDistribution) getDistribution(); distribution.setMean(0); distribution.setStandardDeviation(1); for (int i = 0; i < 100; i+=5) { // make sure no convergence exception double lowerTail = distribution.cumulativeProbability(-i); double upperTail = distribution.cumulativeProbability(i); if (i < 10) { // make sure not top-coded assertTrue(lowerTail > 0.0d); assertTrue(upperTail < 1.0d); } else { // make sure top coding not reversed assertTrue(lowerTail < 0.00001); assertTrue(upperTail > 0.99999); } } } public void testMath280() throws MathException { NormalDistribution normal = new NormalDistributionImpl(0,1); double result = normal.inverseCumulativeProbability(0.9772498680518209); assertEquals(2.0, result, 1.0e-12); } }
public void testEscapedQuote_LANG_477() { String pattern = "it''s a {0,lower} 'test'!"; ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"})); }
org.apache.commons.lang.text.ExtendedMessageFormatTest::testEscapedQuote_LANG_477
src/test/org/apache/commons/lang/text/ExtendedMessageFormatTest.java
101
src/test/org/apache/commons/lang/text/ExtendedMessageFormatTest.java
testEscapedQuote_LANG_477
/* * 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.lang.text; import java.text.ChoiceFormat; import java.text.DateFormat; import java.text.FieldPosition; import java.text.Format; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.commons.lang.SystemUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case for {@link ExtendedMessageFormat}. * * @since 2.4 * @version $Id$ */ public class ExtendedMessageFormatTest extends TestCase { private Map registry = new HashMap(); /** * Return a new test suite containing this test case. * * @return a new test suite containing this test case */ public static Test suite() { TestSuite suite = new TestSuite(ExtendedMessageFormatTest.class); suite.setName("ExtendedMessageFormat Tests"); return suite; } /** * Create a new test case. * * @param name The name of the test */ public ExtendedMessageFormatTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); registry.put("lower", new LowerCaseFormatFactory()); registry.put("upper", new UpperCaseFormatFactory()); } protected void tearDown() throws Exception { super.tearDown(); } /** * Test extended formats. */ public void testExtendedFormats() { String pattern = "Lower: {0,lower} Upper: {1,upper}"; ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); assertPatternsEqual("TOPATTERN", pattern, emf.toPattern()); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"Foo", "Bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "BAR"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "BAR"})); } /** * Test Bug LANG-477 - out of memory error with escaped quote */ public void testEscapedQuote_LANG_477() { String pattern = "it''s a {0,lower} 'test'!"; ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"})); } /** * Test extended and built in formats. */ public void testExtendedAndBuiltInFormats() { Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); Object[] args = new Object[] {"John Doe", cal.getTime(), new Double("12345.67")}; String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}"; String extendedPattern = "Name: {0,upper} "; String pattern = extendedPattern + builtinsPattern; HashSet testLocales = new HashSet(); testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales())); testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales())); testLocales.add(null); for (Iterator l = testLocales.iterator(); l.hasNext();) { Locale locale = (Locale) l.next(); MessageFormat builtins = createMessageFormat(builtinsPattern, locale); String expectedPattern = extendedPattern + builtins.toPattern();; DateFormat df = null; NumberFormat nf = null; ExtendedMessageFormat emf = null; if (locale == null) { df = DateFormat.getDateInstance(DateFormat.SHORT); nf = NumberFormat.getCurrencyInstance(); emf = new ExtendedMessageFormat(pattern, registry); } else { df = DateFormat.getDateInstance(DateFormat.SHORT, locale); nf = NumberFormat.getCurrencyInstance(locale); emf = new ExtendedMessageFormat(pattern, locale, registry); } StringBuffer expected = new StringBuffer(); expected.append("Name: "); expected.append(args[0].toString().toUpperCase()); expected.append(" DOB: "); expected.append(df.format(args[1])); expected.append(" Salary: "); expected.append(nf.format(args[2])); assertPatternsEqual("pattern comparison for locale " + locale, expectedPattern, emf.toPattern()); assertEquals(String.valueOf(locale), expected.toString(), emf.format(args)); } } // /** // * Test extended formats with choice format. // * // * N.B. FAILING - currently sub-formats not supported // */ // public void testExtendedWithChoiceFormat() { // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // assertPatterns(null, pattern, emf.toPattern()); // try { // assertEquals("one", emf.format(new Object[] {new Integer(1), "ONE"})); // assertEquals("TWO", emf.format(new Object[] {new Integer(2), "two"})); // } catch (IllegalArgumentException e) { // // currently sub-formats not supported // } // } // /** // * Test mixed extended and built-in formats with choice format. // * // * N.B. FAILING - currently sub-formats not supported // */ // public void testExtendedAndBuiltInWithChoiceFormat() { // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // Object[] lowArgs = new Object[] {new Integer(1), "Low", new Double("1234.56")}; // Object[] highArgs = new Object[] {new Integer(2), "High", new Double("9876.54")}; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Locale[] testLocales = new Locale[availableLocales.length + 1]; // testLocales[0] = null; // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // for (int i = 0; i < testLocales.length; i++) { // NumberFormat nf = null; // NumberFormat cf = null; // ExtendedMessageFormat emf = null; // if (testLocales[i] == null) { // nf = NumberFormat.getNumberInstance(); // cf = NumberFormat.getCurrencyInstance(); // emf = new ExtendedMessageFormat(pattern, registry); // } else { // nf = NumberFormat.getNumberInstance(testLocales[i]); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // } // assertPatterns(null, pattern, emf.toPattern()); // try { // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // assertEquals(lowExpected, emf.format(lowArgs)); // assertEquals(highExpected, emf.format(highArgs)); // } catch (IllegalArgumentException e) { // // currently sub-formats not supported // } // } // } /** * Test the built in choice format. */ public void testBuiltInChoiceFormat() { Object[] values = new Number[] {new Integer(1), new Double("2.2"), new Double("1234.5")}; String choicePattern = null; Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}"; for (int i = 0; i < values.length; i++) { checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales); } choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}"; for (int i = 0; i < values.length; i++) { checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales); } } /** * Test the built in date/time formats */ public void testBuiltInDateTimeFormat() { Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); Object[] args = new Object[] {cal.getTime()}; Locale[] availableLocales = DateFormat.getAvailableLocales(); checkBuiltInFormat("1: {0,date,short}", args, availableLocales); checkBuiltInFormat("2: {0,date,medium}", args, availableLocales); checkBuiltInFormat("3: {0,date,long}", args, availableLocales); checkBuiltInFormat("4: {0,date,full}", args, availableLocales); checkBuiltInFormat("5: {0,date,d MMM yy}", args, availableLocales); checkBuiltInFormat("6: {0,time,short}", args, availableLocales); checkBuiltInFormat("7: {0,time,medium}", args, availableLocales); checkBuiltInFormat("8: {0,time,long}", args, availableLocales); checkBuiltInFormat("9: {0,time,full}", args, availableLocales); checkBuiltInFormat("10: {0,time,HH:mm}", args, availableLocales); checkBuiltInFormat("11: {0,date}", args, availableLocales); checkBuiltInFormat("12: {0,time}", args, availableLocales); } public void testOverriddenBuiltinFormat() { Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23); Object[] args = new Object[] {cal.getTime()}; Locale[] availableLocales = DateFormat.getAvailableLocales(); Map registry = Collections.singletonMap("date", new OverrideShortDateFormatFactory()); //check the non-overridden builtins: checkBuiltInFormat("1: {0,date}", registry, args, availableLocales); checkBuiltInFormat("2: {0,date,medium}", registry, args, availableLocales); checkBuiltInFormat("3: {0,date,long}", registry, args, availableLocales); checkBuiltInFormat("4: {0,date,full}", registry, args, availableLocales); checkBuiltInFormat("5: {0,date,d MMM yy}", registry, args, availableLocales); //check the overridden format: for (int i = -1; i < availableLocales.length; i++) { Locale locale = i < 0 ? null : availableLocales[i]; MessageFormat dateDefault = createMessageFormat("{0,date}", locale); String pattern = "{0,date,short}"; ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, registry); assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args)); assertEquals("overridden date,short pattern", pattern, dateShort.toPattern()); } } /** * Test the built in number formats. */ public void testBuiltInNumberFormat() { Object[] args = new Object[] {new Double("6543.21")}; Locale[] availableLocales = NumberFormat.getAvailableLocales(); checkBuiltInFormat("1: {0,number}", args, availableLocales); checkBuiltInFormat("2: {0,number,integer}", args, availableLocales); checkBuiltInFormat("3: {0,number,currency}", args, availableLocales); checkBuiltInFormat("4: {0,number,percent}", args, availableLocales); checkBuiltInFormat("5: {0,number,00000.000}", args, availableLocales); } /** * Test a built in format for the specified Locales, plus <code>null</code> Locale. * @param pattern MessageFormat pattern * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(String pattern, Object[] args, Locale[] locales) { checkBuiltInFormat(pattern, null, args, locales); } /** * Test a built in format for the specified Locales, plus <code>null</code> Locale. * @param pattern MessageFormat pattern * @param registry FormatFactory registry to use * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(String pattern, Map registry, Object[] args, Locale[] locales) { checkBuiltInFormat(pattern, registry, args, (Locale) null); for (int i = 0; i < locales.length; i++) { checkBuiltInFormat(pattern, registry, args, locales[i]); } } /** * Create an ExtendedMessageFormat for the specified pattern and locale and check the * formated output matches the expected result for the parameters. * @param pattern string * @param registry map * @param args Object[] * @param locale Locale */ private void checkBuiltInFormat(String pattern, Map registry, Object[] args, Locale locale) { StringBuffer buffer = new StringBuffer(); buffer.append("Pattern=["); buffer.append(pattern); buffer.append("], locale=["); buffer.append(locale); buffer.append("]"); MessageFormat mf = createMessageFormat(pattern, locale); // System.out.println(buffer + ", result=[" + mf.format(args) +"]"); ExtendedMessageFormat emf = null; if (locale == null) { emf = new ExtendedMessageFormat(pattern); } else { emf = new ExtendedMessageFormat(pattern, locale); } assertEquals("format " + buffer.toString(), mf.format(args), emf.format(args)); assertPatternsEqual("toPattern " + buffer.toString(), mf.toPattern(), emf.toPattern()); } //can't trust what MessageFormat does with toPattern() pre 1.4: private void assertPatternsEqual(String message, String expected, String actual) { if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertEquals(message, expected, actual); } } /** * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4). * @param pattern string * @param locale Locale * @return MessageFormat */ private MessageFormat createMessageFormat(String pattern, Locale locale) { MessageFormat result = new MessageFormat(pattern); if (locale != null) { result.setLocale(locale); result.applyPattern(pattern); } return result; } // ------------------------ Test Formats ------------------------ /** * {@link Format} implementation which converts to lower case. */ private static class LowerCaseFormat extends Format { public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(((String)obj).toLowerCase()); } public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();} } /** * {@link Format} implementation which converts to upper case. */ private static class UpperCaseFormat extends Format { public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(((String)obj).toUpperCase()); } public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();} } // ------------------------ Test Format Factories --------------- /** * {@link FormatFactory} implementation for lower case format. */ private static class LowerCaseFormatFactory implements FormatFactory { private static final Format LOWER_INSTANCE = new LowerCaseFormat(); public Format getFormat(String name, String arguments, Locale locale) { return LOWER_INSTANCE; } } /** * {@link FormatFactory} implementation for upper case format. */ private static class UpperCaseFormatFactory implements FormatFactory { private static final Format UPPER_INSTANCE = new UpperCaseFormat(); public Format getFormat(String name, String arguments, Locale locale) { return UPPER_INSTANCE; } } /** * {@link FormatFactory} implementation to override date format "short" to "default". */ private static class OverrideShortDateFormatFactory implements FormatFactory { public Format getFormat(String name, String arguments, Locale locale) { return !"short".equals(arguments) ? null : locale == null ? DateFormat .getDateInstance(DateFormat.DEFAULT) : DateFormat .getDateInstance(DateFormat.DEFAULT, locale); } } }
// You are a professional Java test case writer, please create a test case named `testEscapedQuote_LANG_477` for the issue `Lang-LANG-477`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-477 // // ## Issue-Title: // ExtendedMessageFormat: OutOfMemory with custom format registry and a pattern containing single quotes // // ## Issue-Description: // // When using ExtendedMessageFormat with a custom format registry and a pattern conatining single quotes, an OutOfMemoryError will occur. // // // Example that will cause error: // // // **ExtendedMessageFormatTest.java** // // ``` // // private static Map<String, Object> formatRegistry = new HashMap<String, Object>(); // static { // formatRegistry.put(DummyFormatFactory.DUMMY_FORMAT, new DummyFormatFactory()); // } // // public static void main(String[] args) { // ExtendedMessageFormat mf = new ExtendedMessageFormat("it''s a {dummy} 'test'!", formatRegistry); // String formattedPattern = mf.format(new String[] {"great"}); // System.out.println(formattedPattern); // } // } // // // ``` // // // The following change starting at line 421 on the 2.4 release seems to fix the problem: // // // **ExtendedMessageFormat.java** // // ``` // CURRENT (Broken): // if (escapingOn && c[start] == QUOTE) { // return appendTo == null ? null : appendTo.append(QUOTE); // } // // WORKING: // if (escapingOn && c[start] == QUOTE) { // next(pos); // return appendTo == null ? null : appendTo.append(QUOTE); // } // // ``` // // // // // public void testEscapedQuote_LANG_477() {
101
/** * Test Bug LANG-477 - out of memory error with escaped quote */
43
97
src/test/org/apache/commons/lang/text/ExtendedMessageFormatTest.java
src/test
```markdown ## Issue-ID: Lang-LANG-477 ## Issue-Title: ExtendedMessageFormat: OutOfMemory with custom format registry and a pattern containing single quotes ## Issue-Description: When using ExtendedMessageFormat with a custom format registry and a pattern conatining single quotes, an OutOfMemoryError will occur. Example that will cause error: **ExtendedMessageFormatTest.java** ``` private static Map<String, Object> formatRegistry = new HashMap<String, Object>(); static { formatRegistry.put(DummyFormatFactory.DUMMY_FORMAT, new DummyFormatFactory()); } public static void main(String[] args) { ExtendedMessageFormat mf = new ExtendedMessageFormat("it''s a {dummy} 'test'!", formatRegistry); String formattedPattern = mf.format(new String[] {"great"}); System.out.println(formattedPattern); } } ``` The following change starting at line 421 on the 2.4 release seems to fix the problem: **ExtendedMessageFormat.java** ``` CURRENT (Broken): if (escapingOn && c[start] == QUOTE) { return appendTo == null ? null : appendTo.append(QUOTE); } WORKING: if (escapingOn && c[start] == QUOTE) { next(pos); return appendTo == null ? null : appendTo.append(QUOTE); } ``` ``` You are a professional Java test case writer, please create a test case named `testEscapedQuote_LANG_477` for the issue `Lang-LANG-477`, utilizing the provided issue report information and the following function signature. ```java public void testEscapedQuote_LANG_477() { ```
97
[ "org.apache.commons.lang.text.ExtendedMessageFormat" ]
dd1d3a595e386dfececa305c3db068e5cb21d5851245c9453b97133a409192aa
public void testEscapedQuote_LANG_477()
// You are a professional Java test case writer, please create a test case named `testEscapedQuote_LANG_477` for the issue `Lang-LANG-477`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-477 // // ## Issue-Title: // ExtendedMessageFormat: OutOfMemory with custom format registry and a pattern containing single quotes // // ## Issue-Description: // // When using ExtendedMessageFormat with a custom format registry and a pattern conatining single quotes, an OutOfMemoryError will occur. // // // Example that will cause error: // // // **ExtendedMessageFormatTest.java** // // ``` // // private static Map<String, Object> formatRegistry = new HashMap<String, Object>(); // static { // formatRegistry.put(DummyFormatFactory.DUMMY_FORMAT, new DummyFormatFactory()); // } // // public static void main(String[] args) { // ExtendedMessageFormat mf = new ExtendedMessageFormat("it''s a {dummy} 'test'!", formatRegistry); // String formattedPattern = mf.format(new String[] {"great"}); // System.out.println(formattedPattern); // } // } // // // ``` // // // The following change starting at line 421 on the 2.4 release seems to fix the problem: // // // **ExtendedMessageFormat.java** // // ``` // CURRENT (Broken): // if (escapingOn && c[start] == QUOTE) { // return appendTo == null ? null : appendTo.append(QUOTE); // } // // WORKING: // if (escapingOn && c[start] == QUOTE) { // next(pos); // return appendTo == null ? null : appendTo.append(QUOTE); // } // // ``` // // // // //
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.lang.text; import java.text.ChoiceFormat; import java.text.DateFormat; import java.text.FieldPosition; import java.text.Format; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.commons.lang.SystemUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case for {@link ExtendedMessageFormat}. * * @since 2.4 * @version $Id$ */ public class ExtendedMessageFormatTest extends TestCase { private Map registry = new HashMap(); /** * Return a new test suite containing this test case. * * @return a new test suite containing this test case */ public static Test suite() { TestSuite suite = new TestSuite(ExtendedMessageFormatTest.class); suite.setName("ExtendedMessageFormat Tests"); return suite; } /** * Create a new test case. * * @param name The name of the test */ public ExtendedMessageFormatTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); registry.put("lower", new LowerCaseFormatFactory()); registry.put("upper", new UpperCaseFormatFactory()); } protected void tearDown() throws Exception { super.tearDown(); } /** * Test extended formats. */ public void testExtendedFormats() { String pattern = "Lower: {0,lower} Upper: {1,upper}"; ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); assertPatternsEqual("TOPATTERN", pattern, emf.toPattern()); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"Foo", "Bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "BAR"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "BAR"})); } /** * Test Bug LANG-477 - out of memory error with escaped quote */ public void testEscapedQuote_LANG_477() { String pattern = "it''s a {0,lower} 'test'!"; ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"})); } /** * Test extended and built in formats. */ public void testExtendedAndBuiltInFormats() { Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); Object[] args = new Object[] {"John Doe", cal.getTime(), new Double("12345.67")}; String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}"; String extendedPattern = "Name: {0,upper} "; String pattern = extendedPattern + builtinsPattern; HashSet testLocales = new HashSet(); testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales())); testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales())); testLocales.add(null); for (Iterator l = testLocales.iterator(); l.hasNext();) { Locale locale = (Locale) l.next(); MessageFormat builtins = createMessageFormat(builtinsPattern, locale); String expectedPattern = extendedPattern + builtins.toPattern();; DateFormat df = null; NumberFormat nf = null; ExtendedMessageFormat emf = null; if (locale == null) { df = DateFormat.getDateInstance(DateFormat.SHORT); nf = NumberFormat.getCurrencyInstance(); emf = new ExtendedMessageFormat(pattern, registry); } else { df = DateFormat.getDateInstance(DateFormat.SHORT, locale); nf = NumberFormat.getCurrencyInstance(locale); emf = new ExtendedMessageFormat(pattern, locale, registry); } StringBuffer expected = new StringBuffer(); expected.append("Name: "); expected.append(args[0].toString().toUpperCase()); expected.append(" DOB: "); expected.append(df.format(args[1])); expected.append(" Salary: "); expected.append(nf.format(args[2])); assertPatternsEqual("pattern comparison for locale " + locale, expectedPattern, emf.toPattern()); assertEquals(String.valueOf(locale), expected.toString(), emf.format(args)); } } // /** // * Test extended formats with choice format. // * // * N.B. FAILING - currently sub-formats not supported // */ // public void testExtendedWithChoiceFormat() { // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // assertPatterns(null, pattern, emf.toPattern()); // try { // assertEquals("one", emf.format(new Object[] {new Integer(1), "ONE"})); // assertEquals("TWO", emf.format(new Object[] {new Integer(2), "two"})); // } catch (IllegalArgumentException e) { // // currently sub-formats not supported // } // } // /** // * Test mixed extended and built-in formats with choice format. // * // * N.B. FAILING - currently sub-formats not supported // */ // public void testExtendedAndBuiltInWithChoiceFormat() { // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // Object[] lowArgs = new Object[] {new Integer(1), "Low", new Double("1234.56")}; // Object[] highArgs = new Object[] {new Integer(2), "High", new Double("9876.54")}; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Locale[] testLocales = new Locale[availableLocales.length + 1]; // testLocales[0] = null; // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // for (int i = 0; i < testLocales.length; i++) { // NumberFormat nf = null; // NumberFormat cf = null; // ExtendedMessageFormat emf = null; // if (testLocales[i] == null) { // nf = NumberFormat.getNumberInstance(); // cf = NumberFormat.getCurrencyInstance(); // emf = new ExtendedMessageFormat(pattern, registry); // } else { // nf = NumberFormat.getNumberInstance(testLocales[i]); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // } // assertPatterns(null, pattern, emf.toPattern()); // try { // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // assertEquals(lowExpected, emf.format(lowArgs)); // assertEquals(highExpected, emf.format(highArgs)); // } catch (IllegalArgumentException e) { // // currently sub-formats not supported // } // } // } /** * Test the built in choice format. */ public void testBuiltInChoiceFormat() { Object[] values = new Number[] {new Integer(1), new Double("2.2"), new Double("1234.5")}; String choicePattern = null; Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}"; for (int i = 0; i < values.length; i++) { checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales); } choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}"; for (int i = 0; i < values.length; i++) { checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales); } } /** * Test the built in date/time formats */ public void testBuiltInDateTimeFormat() { Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); Object[] args = new Object[] {cal.getTime()}; Locale[] availableLocales = DateFormat.getAvailableLocales(); checkBuiltInFormat("1: {0,date,short}", args, availableLocales); checkBuiltInFormat("2: {0,date,medium}", args, availableLocales); checkBuiltInFormat("3: {0,date,long}", args, availableLocales); checkBuiltInFormat("4: {0,date,full}", args, availableLocales); checkBuiltInFormat("5: {0,date,d MMM yy}", args, availableLocales); checkBuiltInFormat("6: {0,time,short}", args, availableLocales); checkBuiltInFormat("7: {0,time,medium}", args, availableLocales); checkBuiltInFormat("8: {0,time,long}", args, availableLocales); checkBuiltInFormat("9: {0,time,full}", args, availableLocales); checkBuiltInFormat("10: {0,time,HH:mm}", args, availableLocales); checkBuiltInFormat("11: {0,date}", args, availableLocales); checkBuiltInFormat("12: {0,time}", args, availableLocales); } public void testOverriddenBuiltinFormat() { Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23); Object[] args = new Object[] {cal.getTime()}; Locale[] availableLocales = DateFormat.getAvailableLocales(); Map registry = Collections.singletonMap("date", new OverrideShortDateFormatFactory()); //check the non-overridden builtins: checkBuiltInFormat("1: {0,date}", registry, args, availableLocales); checkBuiltInFormat("2: {0,date,medium}", registry, args, availableLocales); checkBuiltInFormat("3: {0,date,long}", registry, args, availableLocales); checkBuiltInFormat("4: {0,date,full}", registry, args, availableLocales); checkBuiltInFormat("5: {0,date,d MMM yy}", registry, args, availableLocales); //check the overridden format: for (int i = -1; i < availableLocales.length; i++) { Locale locale = i < 0 ? null : availableLocales[i]; MessageFormat dateDefault = createMessageFormat("{0,date}", locale); String pattern = "{0,date,short}"; ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, registry); assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args)); assertEquals("overridden date,short pattern", pattern, dateShort.toPattern()); } } /** * Test the built in number formats. */ public void testBuiltInNumberFormat() { Object[] args = new Object[] {new Double("6543.21")}; Locale[] availableLocales = NumberFormat.getAvailableLocales(); checkBuiltInFormat("1: {0,number}", args, availableLocales); checkBuiltInFormat("2: {0,number,integer}", args, availableLocales); checkBuiltInFormat("3: {0,number,currency}", args, availableLocales); checkBuiltInFormat("4: {0,number,percent}", args, availableLocales); checkBuiltInFormat("5: {0,number,00000.000}", args, availableLocales); } /** * Test a built in format for the specified Locales, plus <code>null</code> Locale. * @param pattern MessageFormat pattern * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(String pattern, Object[] args, Locale[] locales) { checkBuiltInFormat(pattern, null, args, locales); } /** * Test a built in format for the specified Locales, plus <code>null</code> Locale. * @param pattern MessageFormat pattern * @param registry FormatFactory registry to use * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(String pattern, Map registry, Object[] args, Locale[] locales) { checkBuiltInFormat(pattern, registry, args, (Locale) null); for (int i = 0; i < locales.length; i++) { checkBuiltInFormat(pattern, registry, args, locales[i]); } } /** * Create an ExtendedMessageFormat for the specified pattern and locale and check the * formated output matches the expected result for the parameters. * @param pattern string * @param registry map * @param args Object[] * @param locale Locale */ private void checkBuiltInFormat(String pattern, Map registry, Object[] args, Locale locale) { StringBuffer buffer = new StringBuffer(); buffer.append("Pattern=["); buffer.append(pattern); buffer.append("], locale=["); buffer.append(locale); buffer.append("]"); MessageFormat mf = createMessageFormat(pattern, locale); // System.out.println(buffer + ", result=[" + mf.format(args) +"]"); ExtendedMessageFormat emf = null; if (locale == null) { emf = new ExtendedMessageFormat(pattern); } else { emf = new ExtendedMessageFormat(pattern, locale); } assertEquals("format " + buffer.toString(), mf.format(args), emf.format(args)); assertPatternsEqual("toPattern " + buffer.toString(), mf.toPattern(), emf.toPattern()); } //can't trust what MessageFormat does with toPattern() pre 1.4: private void assertPatternsEqual(String message, String expected, String actual) { if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertEquals(message, expected, actual); } } /** * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4). * @param pattern string * @param locale Locale * @return MessageFormat */ private MessageFormat createMessageFormat(String pattern, Locale locale) { MessageFormat result = new MessageFormat(pattern); if (locale != null) { result.setLocale(locale); result.applyPattern(pattern); } return result; } // ------------------------ Test Formats ------------------------ /** * {@link Format} implementation which converts to lower case. */ private static class LowerCaseFormat extends Format { public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(((String)obj).toLowerCase()); } public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();} } /** * {@link Format} implementation which converts to upper case. */ private static class UpperCaseFormat extends Format { public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(((String)obj).toUpperCase()); } public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();} } // ------------------------ Test Format Factories --------------- /** * {@link FormatFactory} implementation for lower case format. */ private static class LowerCaseFormatFactory implements FormatFactory { private static final Format LOWER_INSTANCE = new LowerCaseFormat(); public Format getFormat(String name, String arguments, Locale locale) { return LOWER_INSTANCE; } } /** * {@link FormatFactory} implementation for upper case format. */ private static class UpperCaseFormatFactory implements FormatFactory { private static final Format UPPER_INSTANCE = new UpperCaseFormat(); public Format getFormat(String name, String arguments, Locale locale) { return UPPER_INSTANCE; } } /** * {@link FormatFactory} implementation to override date format "short" to "default". */ private static class OverrideShortDateFormatFactory implements FormatFactory { public Format getFormat(String name, String arguments, Locale locale) { return !"short".equals(arguments) ? null : locale == null ? DateFormat .getDateInstance(DateFormat.DEFAULT) : DateFormat .getDateInstance(DateFormat.DEFAULT, locale); } } }
public void testMissingOptionsException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); options.addOption(OptionBuilder.isRequired().create("x")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required options: fx", e.getMessage()); } }
org.apache.commons.cli.OptionsTest::testMissingOptionsException
src/test/org/apache/commons/cli/OptionsTest.java
117
src/test/org/apache/commons/cli/OptionsTest.java
testMissingOptionsException
/** * 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.util.ArrayList; import java.util.Collection; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * @author Rob Oxspring [email protected] * @version $Revision$ */ public class OptionsTest extends TestCase { public static Test suite() { return new TestSuite ( OptionsTest.class ); } public OptionsTest( String name ) { super( name ); } public void setUp() { } public void tearDown() { } public void testHelpOptions(){ Option longOnly1 = OptionBuilder .withLongOpt("long-only1") .create(); Option longOnly2 = OptionBuilder .withLongOpt("long-only2") .create(); Option shortOnly1 = OptionBuilder .create("1"); Option shortOnly2 = OptionBuilder .create("2"); Option bothA = OptionBuilder .withLongOpt("bothA") .create("a"); Option bothB = OptionBuilder .withLongOpt("bothB") .create("b"); Options options = new Options(); options.addOption(longOnly1); options.addOption(longOnly2); options.addOption(shortOnly1); options.addOption(shortOnly2); options.addOption(bothA); options.addOption(bothB); Collection allOptions = new ArrayList(); allOptions.add(longOnly1); allOptions.add(longOnly2); allOptions.add(shortOnly1); allOptions.add(shortOnly2); allOptions.add(bothA); allOptions.add(bothB); Collection helpOptions = options.helpOptions(); assertTrue("Everything in all should be in help",helpOptions.containsAll(allOptions)); assertTrue("Everything in help should be in all",allOptions.containsAll(helpOptions)); } public void testMissingOptionException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required option: f", e.getMessage()); } } public void testMissingOptionsException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); options.addOption(OptionBuilder.isRequired().create("x")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required options: fx", e.getMessage()); } } }
// You are a professional Java test case writer, please create a test case named `testMissingOptionsException` 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 testMissingOptionsException() throws ParseException {
117
4
107
src/test/org/apache/commons/cli/OptionsTest.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 `testMissingOptionsException` for the issue `Cli-cli-1`, utilizing the provided issue report information and the following function signature. ```java public void testMissingOptionsException() throws ParseException { ```
107
[ "org.apache.commons.cli.Parser" ]
de556e8eb2ddb50b6c559a52351868356be09603e9d53c7d0d0390e70184a58d
public void testMissingOptionsException() throws ParseException
// You are a professional Java test case writer, please create a test case named `testMissingOptionsException` 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.util.ArrayList; import java.util.Collection; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * @author Rob Oxspring [email protected] * @version $Revision$ */ public class OptionsTest extends TestCase { public static Test suite() { return new TestSuite ( OptionsTest.class ); } public OptionsTest( String name ) { super( name ); } public void setUp() { } public void tearDown() { } public void testHelpOptions(){ Option longOnly1 = OptionBuilder .withLongOpt("long-only1") .create(); Option longOnly2 = OptionBuilder .withLongOpt("long-only2") .create(); Option shortOnly1 = OptionBuilder .create("1"); Option shortOnly2 = OptionBuilder .create("2"); Option bothA = OptionBuilder .withLongOpt("bothA") .create("a"); Option bothB = OptionBuilder .withLongOpt("bothB") .create("b"); Options options = new Options(); options.addOption(longOnly1); options.addOption(longOnly2); options.addOption(shortOnly1); options.addOption(shortOnly2); options.addOption(bothA); options.addOption(bothB); Collection allOptions = new ArrayList(); allOptions.add(longOnly1); allOptions.add(longOnly2); allOptions.add(shortOnly1); allOptions.add(shortOnly2); allOptions.add(bothA); allOptions.add(bothB); Collection helpOptions = options.helpOptions(); assertTrue("Everything in all should be in help",helpOptions.containsAll(allOptions)); assertTrue("Everything in help should be in all",allOptions.containsAll(helpOptions)); } public void testMissingOptionException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required option: f", e.getMessage()); } } public void testMissingOptionsException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); options.addOption(OptionBuilder.isRequired().create("x")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required options: fx", e.getMessage()); } } }
public void testConstructor() { MultiplePiePlot plot = new MultiplePiePlot(); assertNull(plot.getDataset()); // the following checks that the plot registers itself as a listener // with the dataset passed to the constructor - see patch 1943021 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); plot = new MultiplePiePlot(dataset); assertTrue(dataset.hasListener(plot)); }
org.jfree.chart.plot.junit.MultiplePiePlotTests::testConstructor
tests/org/jfree/chart/plot/junit/MultiplePiePlotTests.java
112
tests/org/jfree/chart/plot/junit/MultiplePiePlotTests.java
testConstructor
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * MultiplePiePlotTests.java * ------------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Jun-2005 : Version 1 (DG); * 06-Apr-2006 : Added tests for new fields (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 18-Apr-2008 : Added testConstructor() (DG); * */ package org.jfree.chart.plot.junit; import java.awt.Color; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.PlotChangeListener; import org.jfree.chart.plot.MultiplePiePlot; import org.jfree.chart.util.TableOrder; import org.jfree.data.category.DefaultCategoryDataset; /** * Some tests for the {@link MultiplePiePlot} class. */ public class MultiplePiePlotTests extends TestCase implements PlotChangeListener { /** The last event received. */ PlotChangeEvent lastEvent; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(MultiplePiePlotTests.class); } /** * Receives a plot change event and records it. Some tests will use this * to check that events have been generated (or not) when required. */ public void plotChanged(PlotChangeEvent event) { this.lastEvent = event; } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public MultiplePiePlotTests(String name) { super(name); } /** * Some checks for the constructors. */ public void testConstructor() { MultiplePiePlot plot = new MultiplePiePlot(); assertNull(plot.getDataset()); // the following checks that the plot registers itself as a listener // with the dataset passed to the constructor - see patch 1943021 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); plot = new MultiplePiePlot(dataset); assertTrue(dataset.hasListener(plot)); } /** * Check that the equals() method distinguishes the required fields. */ public void testEquals() { MultiplePiePlot p1 = new MultiplePiePlot(); MultiplePiePlot p2 = new MultiplePiePlot(); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); p1.setDataExtractOrder(TableOrder.BY_ROW); assertFalse(p1.equals(p2)); p2.setDataExtractOrder(TableOrder.BY_ROW); assertTrue(p1.equals(p2)); p1.setLimit(1.23); assertFalse(p1.equals(p2)); p2.setLimit(1.23); assertTrue(p1.equals(p2)); p1.setAggregatedItemsKey("Aggregated Items"); assertFalse(p1.equals(p2)); p2.setAggregatedItemsKey("Aggregated Items"); assertTrue(p1.equals(p2)); p1.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertFalse(p1.equals(p2)); p2.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertTrue(p1.equals(p2)); p1.setPieChart(ChartFactory.createPieChart("Title", null, true, true, true)); assertFalse(p1.equals(p2)); p2.setPieChart(ChartFactory.createPieChart("Title", null, true, true, true)); assertTrue(p1.equals(p2)); } /** * Some basic checks for the clone() method. */ public void testCloning() { MultiplePiePlot p1 = new MultiplePiePlot(); MultiplePiePlot p2 = null; try { p2 = (MultiplePiePlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); System.err.println("Failed to clone."); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { MultiplePiePlot p1 = new MultiplePiePlot(null); p1.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.yellow, 3.0f, 4.0f, Color.red)); MultiplePiePlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); p2 = (MultiplePiePlot) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(p1, p2); } }
// You are a professional Java test case writer, please create a test case named `testConstructor` for the issue `Chart-213`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-213 // // ## Issue-Title: // #213 Fix for MultiplePiePlot // // // // // // ## Issue-Description: // When dataset is passed into constructor for MultiplePiePlot, the dataset is not wired to a listener, as it would be if setDataset is called. // // // // public void testConstructor() {
112
/** * Some checks for the constructors. */
12
103
tests/org/jfree/chart/plot/junit/MultiplePiePlotTests.java
tests
```markdown ## Issue-ID: Chart-213 ## Issue-Title: #213 Fix for MultiplePiePlot ## Issue-Description: When dataset is passed into constructor for MultiplePiePlot, the dataset is not wired to a listener, as it would be if setDataset is called. ``` You are a professional Java test case writer, please create a test case named `testConstructor` for the issue `Chart-213`, utilizing the provided issue report information and the following function signature. ```java public void testConstructor() { ```
103
[ "org.jfree.chart.plot.MultiplePiePlot" ]
e001e965aae2cbd3c27fc2201ea95faa49af642eee998c9dbd1c4ae39b6a84cf
public void testConstructor()
// You are a professional Java test case writer, please create a test case named `testConstructor` for the issue `Chart-213`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Chart-213 // // ## Issue-Title: // #213 Fix for MultiplePiePlot // // // // // // ## Issue-Description: // When dataset is passed into constructor for MultiplePiePlot, the dataset is not wired to a listener, as it would be if setDataset is called. // // // //
Chart
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * MultiplePiePlotTests.java * ------------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 16-Jun-2005 : Version 1 (DG); * 06-Apr-2006 : Added tests for new fields (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * 18-Apr-2008 : Added testConstructor() (DG); * */ package org.jfree.chart.plot.junit; import java.awt.Color; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.ChartFactory; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.PlotChangeListener; import org.jfree.chart.plot.MultiplePiePlot; import org.jfree.chart.util.TableOrder; import org.jfree.data.category.DefaultCategoryDataset; /** * Some tests for the {@link MultiplePiePlot} class. */ public class MultiplePiePlotTests extends TestCase implements PlotChangeListener { /** The last event received. */ PlotChangeEvent lastEvent; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(MultiplePiePlotTests.class); } /** * Receives a plot change event and records it. Some tests will use this * to check that events have been generated (or not) when required. */ public void plotChanged(PlotChangeEvent event) { this.lastEvent = event; } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public MultiplePiePlotTests(String name) { super(name); } /** * Some checks for the constructors. */ public void testConstructor() { MultiplePiePlot plot = new MultiplePiePlot(); assertNull(plot.getDataset()); // the following checks that the plot registers itself as a listener // with the dataset passed to the constructor - see patch 1943021 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); plot = new MultiplePiePlot(dataset); assertTrue(dataset.hasListener(plot)); } /** * Check that the equals() method distinguishes the required fields. */ public void testEquals() { MultiplePiePlot p1 = new MultiplePiePlot(); MultiplePiePlot p2 = new MultiplePiePlot(); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); p1.setDataExtractOrder(TableOrder.BY_ROW); assertFalse(p1.equals(p2)); p2.setDataExtractOrder(TableOrder.BY_ROW); assertTrue(p1.equals(p2)); p1.setLimit(1.23); assertFalse(p1.equals(p2)); p2.setLimit(1.23); assertTrue(p1.equals(p2)); p1.setAggregatedItemsKey("Aggregated Items"); assertFalse(p1.equals(p2)); p2.setAggregatedItemsKey("Aggregated Items"); assertTrue(p1.equals(p2)); p1.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertFalse(p1.equals(p2)); p2.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertTrue(p1.equals(p2)); p1.setPieChart(ChartFactory.createPieChart("Title", null, true, true, true)); assertFalse(p1.equals(p2)); p2.setPieChart(ChartFactory.createPieChart("Title", null, true, true, true)); assertTrue(p1.equals(p2)); } /** * Some basic checks for the clone() method. */ public void testCloning() { MultiplePiePlot p1 = new MultiplePiePlot(); MultiplePiePlot p2 = null; try { p2 = (MultiplePiePlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); System.err.println("Failed to clone."); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { MultiplePiePlot p1 = new MultiplePiePlot(null); p1.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.yellow, 3.0f, 4.0f, Color.red)); MultiplePiePlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); p2 = (MultiplePiePlot) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(p1, p2); } }
public void testSmallDegreesOfFreedom() throws Exception { org.apache.commons.math.distribution.FDistributionImpl fd = new org.apache.commons.math.distribution.FDistributionImpl( 1.0, 1.0); double p = fd.cumulativeProbability(0.975); double x = fd.inverseCumulativeProbability(p); assertEquals(0.975, x, 1.0e-5); fd.setDenominatorDegreesOfFreedom(2.0); p = fd.cumulativeProbability(0.975); x = fd.inverseCumulativeProbability(p); assertEquals(0.975, x, 1.0e-5); }
org.apache.commons.math.distribution.FDistributionTest::testSmallDegreesOfFreedom
src/test/org/apache/commons/math/distribution/FDistributionTest.java
120
src/test/org/apache/commons/math/distribution/FDistributionTest.java
testSmallDegreesOfFreedom
/* * 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.distribution; /** * Test cases for FDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. * * @version $Revision$ $Date$ */ public class FDistributionTest extends ContinuousDistributionAbstractTest { /** * Constructor for FDistributionTest. * @param name */ public FDistributionTest(String name) { super(name); } //-------------- Implementations for abstract methods ----------------------- /** Creates the default continuous distribution instance to use in tests. */ public ContinuousDistribution makeDistribution() { return new FDistributionImpl(5.0, 6.0); } /** Creates the default cumulative probability distribution test input values */ public double[] makeCumulativeTestPoints() { // quantiles computed using R version 1.8.1 (linux version) return new double[] {0.03468084d ,0.09370091d, 0.1433137d, 0.2020084d, 0.2937283d, 20.80266d, 8.745895d, 5.987565d, 4.387374d, 3.107512d}; } /** Creates the default cumulative probability density test expected values */ public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d}; } // --------------------- Override tolerance -------------- protected void setUp() throws Exception { super.setUp(); setTolerance(4e-6); } //---------------------------- Additional test cases ------------------------- public void testCumulativeProbabilityExtremes() throws Exception { setCumulativeTestPoints(new double[] {-2, 0}); setCumulativeTestValues(new double[] {0, 0}); verifyCumulativeProbabilities(); } public void testInverseCumulativeProbabilityExtremes() throws Exception { setInverseCumulativeTestPoints(new double[] {0, 1}); setInverseCumulativeTestValues(new double[] {0, Double.POSITIVE_INFINITY}); verifyInverseCumulativeProbabilities(); } public void testDfAccessors() { FDistribution distribution = (FDistribution) getDistribution(); assertEquals(5d, distribution.getNumeratorDegreesOfFreedom(), Double.MIN_VALUE); distribution.setNumeratorDegreesOfFreedom(4d); assertEquals(4d, distribution.getNumeratorDegreesOfFreedom(), Double.MIN_VALUE); assertEquals(6d, distribution.getDenominatorDegreesOfFreedom(), Double.MIN_VALUE); distribution.setDenominatorDegreesOfFreedom(4d); assertEquals(4d, distribution.getDenominatorDegreesOfFreedom(), Double.MIN_VALUE); try { distribution.setNumeratorDegreesOfFreedom(0d); fail("Expecting IllegalArgumentException for df = 0"); } catch (IllegalArgumentException ex) { // expected } try { distribution.setDenominatorDegreesOfFreedom(0d); fail("Expecting IllegalArgumentException for df = 0"); } catch (IllegalArgumentException ex) { // expected } } public void testLargeDegreesOfFreedom() throws Exception { org.apache.commons.math.distribution.FDistributionImpl fd = new org.apache.commons.math.distribution.FDistributionImpl( 100000., 100000.); double p = fd.cumulativeProbability(.999); double x = fd.inverseCumulativeProbability(p); assertEquals(.999, x, 1.0e-5); } public void testSmallDegreesOfFreedom() throws Exception { org.apache.commons.math.distribution.FDistributionImpl fd = new org.apache.commons.math.distribution.FDistributionImpl( 1.0, 1.0); double p = fd.cumulativeProbability(0.975); double x = fd.inverseCumulativeProbability(p); assertEquals(0.975, x, 1.0e-5); fd.setDenominatorDegreesOfFreedom(2.0); p = fd.cumulativeProbability(0.975); x = fd.inverseCumulativeProbability(p); assertEquals(0.975, x, 1.0e-5); } }
// You are a professional Java test case writer, please create a test case named `testSmallDegreesOfFreedom` for the issue `Math-MATH-227`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-227 // // ## Issue-Title: // denominatorDegreeOfFreedom in FDistribution leads to IllegalArgumentsException in UnivariateRealSolverUtils.bracket // // ## Issue-Description: // // We are using the FDistributionImpl from the commons.math project to do // // some statistical calculations, namely receiving the upper and lower // // boundaries of a confidence interval. Everything is working fine and the // // results are matching our reference calculations. // // // However, the FDistribution behaves strange if a // // denominatorDegreeOfFreedom of 2 is used, with an alpha-value of 0.95. // // This results in an IllegalArgumentsException, stating: // // // Invalid endpoint parameters: lowerBound=0.0 initial=Infinity // // upperBound=1.7976931348623157E308 // // // coming from // // org.apache.commons.math.analysis.UnivariateRealSolverUtils.bracket // // // The problem is the 'initial' parameter to that function, wich is // // POSITIVE\_INFINITY and therefore not within the boundaries. I already // // pinned down the problem to the FDistributions getInitialDomain()-method, // // wich goes like: // // // return getDenominatorDegreesOfFreedom() / // // (getDenominatorDegreesOfFreedom() - 2.0); // // // Obviously, in case of denominatorDegreesOfFreedom == 2, this must lead // // to a division-by-zero, resulting in POSTIVE\_INFINITY. The result of this // // operation is then directly passed into the // // UnivariateRealSolverUtils.bracket() - method as second argument. // // // // // public void testSmallDegreesOfFreedom() throws Exception {
120
95
108
src/test/org/apache/commons/math/distribution/FDistributionTest.java
src/test
```markdown ## Issue-ID: Math-MATH-227 ## Issue-Title: denominatorDegreeOfFreedom in FDistribution leads to IllegalArgumentsException in UnivariateRealSolverUtils.bracket ## Issue-Description: We are using the FDistributionImpl from the commons.math project to do some statistical calculations, namely receiving the upper and lower boundaries of a confidence interval. Everything is working fine and the results are matching our reference calculations. However, the FDistribution behaves strange if a denominatorDegreeOfFreedom of 2 is used, with an alpha-value of 0.95. This results in an IllegalArgumentsException, stating: Invalid endpoint parameters: lowerBound=0.0 initial=Infinity upperBound=1.7976931348623157E308 coming from org.apache.commons.math.analysis.UnivariateRealSolverUtils.bracket The problem is the 'initial' parameter to that function, wich is POSITIVE\_INFINITY and therefore not within the boundaries. I already pinned down the problem to the FDistributions getInitialDomain()-method, wich goes like: return getDenominatorDegreesOfFreedom() / (getDenominatorDegreesOfFreedom() - 2.0); Obviously, in case of denominatorDegreesOfFreedom == 2, this must lead to a division-by-zero, resulting in POSTIVE\_INFINITY. The result of this operation is then directly passed into the UnivariateRealSolverUtils.bracket() - method as second argument. ``` You are a professional Java test case writer, please create a test case named `testSmallDegreesOfFreedom` for the issue `Math-MATH-227`, utilizing the provided issue report information and the following function signature. ```java public void testSmallDegreesOfFreedom() throws Exception { ```
108
[ "org.apache.commons.math.distribution.FDistributionImpl" ]
e0e659301e73957c9123fed72809825eb3a61fed6251d886c124bcf6ea8f5813
public void testSmallDegreesOfFreedom() throws Exception
// You are a professional Java test case writer, please create a test case named `testSmallDegreesOfFreedom` for the issue `Math-MATH-227`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-227 // // ## Issue-Title: // denominatorDegreeOfFreedom in FDistribution leads to IllegalArgumentsException in UnivariateRealSolverUtils.bracket // // ## Issue-Description: // // We are using the FDistributionImpl from the commons.math project to do // // some statistical calculations, namely receiving the upper and lower // // boundaries of a confidence interval. Everything is working fine and the // // results are matching our reference calculations. // // // However, the FDistribution behaves strange if a // // denominatorDegreeOfFreedom of 2 is used, with an alpha-value of 0.95. // // This results in an IllegalArgumentsException, stating: // // // Invalid endpoint parameters: lowerBound=0.0 initial=Infinity // // upperBound=1.7976931348623157E308 // // // coming from // // org.apache.commons.math.analysis.UnivariateRealSolverUtils.bracket // // // The problem is the 'initial' parameter to that function, wich is // // POSITIVE\_INFINITY and therefore not within the boundaries. I already // // pinned down the problem to the FDistributions getInitialDomain()-method, // // wich goes like: // // // return getDenominatorDegreesOfFreedom() / // // (getDenominatorDegreesOfFreedom() - 2.0); // // // Obviously, in case of denominatorDegreesOfFreedom == 2, this must lead // // to a division-by-zero, resulting in POSTIVE\_INFINITY. The result of this // // operation is then directly passed into the // // UnivariateRealSolverUtils.bracket() - method as second argument. // // // // //
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.distribution; /** * Test cases for FDistribution. * Extends ContinuousDistributionAbstractTest. See class javadoc for * ContinuousDistributionAbstractTest for details. * * @version $Revision$ $Date$ */ public class FDistributionTest extends ContinuousDistributionAbstractTest { /** * Constructor for FDistributionTest. * @param name */ public FDistributionTest(String name) { super(name); } //-------------- Implementations for abstract methods ----------------------- /** Creates the default continuous distribution instance to use in tests. */ public ContinuousDistribution makeDistribution() { return new FDistributionImpl(5.0, 6.0); } /** Creates the default cumulative probability distribution test input values */ public double[] makeCumulativeTestPoints() { // quantiles computed using R version 1.8.1 (linux version) return new double[] {0.03468084d ,0.09370091d, 0.1433137d, 0.2020084d, 0.2937283d, 20.80266d, 8.745895d, 5.987565d, 4.387374d, 3.107512d}; } /** Creates the default cumulative probability density test expected values */ public double[] makeCumulativeTestValues() { return new double[] {0.001d, 0.01d, 0.025d, 0.05d, 0.1d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d}; } // --------------------- Override tolerance -------------- protected void setUp() throws Exception { super.setUp(); setTolerance(4e-6); } //---------------------------- Additional test cases ------------------------- public void testCumulativeProbabilityExtremes() throws Exception { setCumulativeTestPoints(new double[] {-2, 0}); setCumulativeTestValues(new double[] {0, 0}); verifyCumulativeProbabilities(); } public void testInverseCumulativeProbabilityExtremes() throws Exception { setInverseCumulativeTestPoints(new double[] {0, 1}); setInverseCumulativeTestValues(new double[] {0, Double.POSITIVE_INFINITY}); verifyInverseCumulativeProbabilities(); } public void testDfAccessors() { FDistribution distribution = (FDistribution) getDistribution(); assertEquals(5d, distribution.getNumeratorDegreesOfFreedom(), Double.MIN_VALUE); distribution.setNumeratorDegreesOfFreedom(4d); assertEquals(4d, distribution.getNumeratorDegreesOfFreedom(), Double.MIN_VALUE); assertEquals(6d, distribution.getDenominatorDegreesOfFreedom(), Double.MIN_VALUE); distribution.setDenominatorDegreesOfFreedom(4d); assertEquals(4d, distribution.getDenominatorDegreesOfFreedom(), Double.MIN_VALUE); try { distribution.setNumeratorDegreesOfFreedom(0d); fail("Expecting IllegalArgumentException for df = 0"); } catch (IllegalArgumentException ex) { // expected } try { distribution.setDenominatorDegreesOfFreedom(0d); fail("Expecting IllegalArgumentException for df = 0"); } catch (IllegalArgumentException ex) { // expected } } public void testLargeDegreesOfFreedom() throws Exception { org.apache.commons.math.distribution.FDistributionImpl fd = new org.apache.commons.math.distribution.FDistributionImpl( 100000., 100000.); double p = fd.cumulativeProbability(.999); double x = fd.inverseCumulativeProbability(p); assertEquals(.999, x, 1.0e-5); } public void testSmallDegreesOfFreedom() throws Exception { org.apache.commons.math.distribution.FDistributionImpl fd = new org.apache.commons.math.distribution.FDistributionImpl( 1.0, 1.0); double p = fd.cumulativeProbability(0.975); double x = fd.inverseCumulativeProbability(p); assertEquals(0.975, x, 1.0e-5); fd.setDenominatorDegreesOfFreedom(2.0); p = fd.cumulativeProbability(0.975); x = fd.inverseCumulativeProbability(p); assertEquals(0.975, x, 1.0e-5); } }
@Test public void testMath855() { final double minSin = 3 * Math.PI / 2; final double offset = 1e-8; final double delta = 1e-7; final UnivariateFunction f1 = new Sin(); final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 5 * offset }, new double[] { 0, -1, 0 }); final UnivariateFunction f = FunctionUtils.add(f1, f2); final UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-100); final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, minSin - 6.789 * delta, minSin + 9.876 * delta); final int numEval = optimizer.getEvaluations(); final double sol = result.getPoint(); final double expected = 4.712389027602411; // System.out.println("min=" + (minSin + offset) + " f=" + f.value(minSin + offset)); // System.out.println("sol=" + sol + " f=" + f.value(sol)); // System.out.println("exp=" + expected + " f=" + f.value(expected)); Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected)); }
org.apache.commons.math3.optimization.univariate.BrentOptimizerTest::testMath855
src/test/java/org/apache/commons/math3/optimization/univariate/BrentOptimizerTest.java
213
src/test/java/org/apache/commons/math3/optimization/univariate/BrentOptimizerTest.java
testMath855
/* * 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.univariate; import org.apache.commons.math3.analysis.QuinticFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.StepFunction; import org.apache.commons.math3.analysis.FunctionUtils; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * @version $Id$ */ public final class BrentOptimizerTest { @Test public void testSinMin() { UnivariateFunction f = new Sin(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5).getPoint(), 1e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); Assert.assertEquals(200, optimizer.getMaxEvaluations()); Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 1, 5).getPoint(), 1e-8); Assert.assertTrue(optimizer.getEvaluations() <= 100); Assert.assertTrue(optimizer.getEvaluations() >= 15); try { optimizer.optimize(10, f, GoalType.MINIMIZE, 4, 5); Assert.fail("an exception should have been thrown"); } catch (TooManyEvaluationsException fee) { // expected } } @Test public void testSinMinWithValueChecker() { final UnivariateFunction f = new Sin(); final ConvergenceChecker<UnivariatePointValuePair> checker = new SimpleUnivariateValueChecker(1e-5, 1e-14); // The default stopping criterion of Brent's algorithm should not // pass, but the search will stop at the given relative tolerance // for the function value. final UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14, checker); final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5); Assert.assertEquals(3 * Math.PI / 2, result.getPoint(), 1e-3); } @Test public void testBoundaries() { final double lower = -1.0; final double upper = +1.0; UnivariateFunction f = new UnivariateFunction() { public double value(double x) { if (x < lower) { throw new NumberIsTooSmallException(x, lower, true); } else if (x > upper) { throw new NumberIsTooLargeException(x, upper, true); } else { return x; } } }; UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(lower, optimizer.optimize(100, f, GoalType.MINIMIZE, lower, upper).getPoint(), 1.0e-8); Assert.assertEquals(upper, optimizer.optimize(100, f, GoalType.MAXIMIZE, lower, upper).getPoint(), 1.0e-8); } @Test public void testQuinticMin() { // The function has local minima at -0.27195613 and 0.82221643. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(-0.27195613, optimizer.optimize(200, f, GoalType.MINIMIZE, -0.3, -0.2).getPoint(), 1.0e-8); Assert.assertEquals( 0.82221643, optimizer.optimize(200, f, GoalType.MINIMIZE, 0.3, 0.9).getPoint(), 1.0e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); // search in a large interval Assert.assertEquals(-0.27195613, optimizer.optimize(200, f, GoalType.MINIMIZE, -1.0, 0.2).getPoint(), 1.0e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); } @Test public void testQuinticMinStatistics() { // The function has local minima at -0.27195613 and 0.82221643. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-11, 1e-14); final DescriptiveStatistics[] stat = new DescriptiveStatistics[2]; for (int i = 0; i < stat.length; i++) { stat[i] = new DescriptiveStatistics(); } final double min = -0.75; final double max = 0.25; final int nSamples = 200; final double delta = (max - min) / nSamples; for (int i = 0; i < nSamples; i++) { final double start = min + i * delta; stat[0].addValue(optimizer.optimize(40, f, GoalType.MINIMIZE, min, max, start).getPoint()); stat[1].addValue(optimizer.getEvaluations()); } final double meanOptValue = stat[0].getMean(); final double medianEval = stat[1].getPercentile(50); Assert.assertTrue(meanOptValue > -0.2719561281); Assert.assertTrue(meanOptValue < -0.2719561280); Assert.assertEquals(23, (int) medianEval); } @Test public void testQuinticMax() { // The quintic function has zeros at 0, +-0.5 and +-1. // The function has a local maximum at 0.27195613. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-12, 1e-14); Assert.assertEquals(0.27195613, optimizer.optimize(100, f, GoalType.MAXIMIZE, 0.2, 0.3).getPoint(), 1e-8); try { optimizer.optimize(5, f, GoalType.MAXIMIZE, 0.2, 0.3); Assert.fail("an exception should have been thrown"); } catch (TooManyEvaluationsException miee) { // expected } } @Test public void testMinEndpoints() { UnivariateFunction f = new Sin(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-14); // endpoint is minimum double result = optimizer.optimize(50, f, GoalType.MINIMIZE, 3 * Math.PI / 2, 5).getPoint(); Assert.assertEquals(3 * Math.PI / 2, result, 1e-6); result = optimizer.optimize(50, f, GoalType.MINIMIZE, 4, 3 * Math.PI / 2).getPoint(); Assert.assertEquals(3 * Math.PI / 2, result, 1e-6); } @Test public void testMath832() { final UnivariateFunction f = new UnivariateFunction() { public double value(double x) { final double sqrtX = FastMath.sqrt(x); final double a = 1e2 * sqrtX; final double b = 1e6 / x; final double c = 1e4 / sqrtX; return a + b + c; } }; UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-8); final double result = optimizer.optimize(1483, f, GoalType.MINIMIZE, Double.MIN_VALUE, Double.MAX_VALUE).getPoint(); Assert.assertEquals(804.9355825, result, 1e-6); } /** * Contrived example showing that prior to the resolution of MATH-855, * the algorithm, by always returning the last evaluated point, would * sometimes not report the best point it had found. */ @Test public void testMath855() { final double minSin = 3 * Math.PI / 2; final double offset = 1e-8; final double delta = 1e-7; final UnivariateFunction f1 = new Sin(); final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 5 * offset }, new double[] { 0, -1, 0 }); final UnivariateFunction f = FunctionUtils.add(f1, f2); final UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-100); final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, minSin - 6.789 * delta, minSin + 9.876 * delta); final int numEval = optimizer.getEvaluations(); final double sol = result.getPoint(); final double expected = 4.712389027602411; // System.out.println("min=" + (minSin + offset) + " f=" + f.value(minSin + offset)); // System.out.println("sol=" + sol + " f=" + f.value(sol)); // System.out.println("exp=" + expected + " f=" + f.value(expected)); Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected)); } }
// You are a professional Java test case writer, please create a test case named `testMath855` for the issue `Math-MATH-855`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-855 // // ## Issue-Title: // "BrentOptimizer" not always reporting the best point // // ## Issue-Description: // // BrentOptimizer (package "o.a.c.m.optimization.univariate") does not check that the point it is going to return is indeed the best one it has encountered. Indeed, the last evaluated point might be slightly worse than the one before last. // // // // // @Test public void testMath855() {
213
/** * Contrived example showing that prior to the resolution of MATH-855, * the algorithm, by always returning the last evaluated point, would * sometimes not report the best point it had found. */
24
191
src/test/java/org/apache/commons/math3/optimization/univariate/BrentOptimizerTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-855 ## Issue-Title: "BrentOptimizer" not always reporting the best point ## Issue-Description: BrentOptimizer (package "o.a.c.m.optimization.univariate") does not check that the point it is going to return is indeed the best one it has encountered. Indeed, the last evaluated point might be slightly worse than the one before last. ``` You are a professional Java test case writer, please create a test case named `testMath855` for the issue `Math-MATH-855`, utilizing the provided issue report information and the following function signature. ```java @Test public void testMath855() { ```
191
[ "org.apache.commons.math3.optimization.univariate.BrentOptimizer" ]
e1c8ec977ab88b6d844e01320396afc74064fffc0489ca1d2d6e0eebedcc9e15
@Test public void testMath855()
// You are a professional Java test case writer, please create a test case named `testMath855` for the issue `Math-MATH-855`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-855 // // ## Issue-Title: // "BrentOptimizer" not always reporting the best point // // ## Issue-Description: // // BrentOptimizer (package "o.a.c.m.optimization.univariate") does not check that the point it is going to return is indeed the best one it has encountered. Indeed, the last evaluated point might be slightly worse than the one before last. // // // // //
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.univariate; import org.apache.commons.math3.analysis.QuinticFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.StepFunction; import org.apache.commons.math3.analysis.FunctionUtils; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * @version $Id$ */ public final class BrentOptimizerTest { @Test public void testSinMin() { UnivariateFunction f = new Sin(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5).getPoint(), 1e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); Assert.assertEquals(200, optimizer.getMaxEvaluations()); Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 1, 5).getPoint(), 1e-8); Assert.assertTrue(optimizer.getEvaluations() <= 100); Assert.assertTrue(optimizer.getEvaluations() >= 15); try { optimizer.optimize(10, f, GoalType.MINIMIZE, 4, 5); Assert.fail("an exception should have been thrown"); } catch (TooManyEvaluationsException fee) { // expected } } @Test public void testSinMinWithValueChecker() { final UnivariateFunction f = new Sin(); final ConvergenceChecker<UnivariatePointValuePair> checker = new SimpleUnivariateValueChecker(1e-5, 1e-14); // The default stopping criterion of Brent's algorithm should not // pass, but the search will stop at the given relative tolerance // for the function value. final UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14, checker); final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5); Assert.assertEquals(3 * Math.PI / 2, result.getPoint(), 1e-3); } @Test public void testBoundaries() { final double lower = -1.0; final double upper = +1.0; UnivariateFunction f = new UnivariateFunction() { public double value(double x) { if (x < lower) { throw new NumberIsTooSmallException(x, lower, true); } else if (x > upper) { throw new NumberIsTooLargeException(x, upper, true); } else { return x; } } }; UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(lower, optimizer.optimize(100, f, GoalType.MINIMIZE, lower, upper).getPoint(), 1.0e-8); Assert.assertEquals(upper, optimizer.optimize(100, f, GoalType.MAXIMIZE, lower, upper).getPoint(), 1.0e-8); } @Test public void testQuinticMin() { // The function has local minima at -0.27195613 and 0.82221643. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(-0.27195613, optimizer.optimize(200, f, GoalType.MINIMIZE, -0.3, -0.2).getPoint(), 1.0e-8); Assert.assertEquals( 0.82221643, optimizer.optimize(200, f, GoalType.MINIMIZE, 0.3, 0.9).getPoint(), 1.0e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); // search in a large interval Assert.assertEquals(-0.27195613, optimizer.optimize(200, f, GoalType.MINIMIZE, -1.0, 0.2).getPoint(), 1.0e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); } @Test public void testQuinticMinStatistics() { // The function has local minima at -0.27195613 and 0.82221643. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-11, 1e-14); final DescriptiveStatistics[] stat = new DescriptiveStatistics[2]; for (int i = 0; i < stat.length; i++) { stat[i] = new DescriptiveStatistics(); } final double min = -0.75; final double max = 0.25; final int nSamples = 200; final double delta = (max - min) / nSamples; for (int i = 0; i < nSamples; i++) { final double start = min + i * delta; stat[0].addValue(optimizer.optimize(40, f, GoalType.MINIMIZE, min, max, start).getPoint()); stat[1].addValue(optimizer.getEvaluations()); } final double meanOptValue = stat[0].getMean(); final double medianEval = stat[1].getPercentile(50); Assert.assertTrue(meanOptValue > -0.2719561281); Assert.assertTrue(meanOptValue < -0.2719561280); Assert.assertEquals(23, (int) medianEval); } @Test public void testQuinticMax() { // The quintic function has zeros at 0, +-0.5 and +-1. // The function has a local maximum at 0.27195613. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-12, 1e-14); Assert.assertEquals(0.27195613, optimizer.optimize(100, f, GoalType.MAXIMIZE, 0.2, 0.3).getPoint(), 1e-8); try { optimizer.optimize(5, f, GoalType.MAXIMIZE, 0.2, 0.3); Assert.fail("an exception should have been thrown"); } catch (TooManyEvaluationsException miee) { // expected } } @Test public void testMinEndpoints() { UnivariateFunction f = new Sin(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-14); // endpoint is minimum double result = optimizer.optimize(50, f, GoalType.MINIMIZE, 3 * Math.PI / 2, 5).getPoint(); Assert.assertEquals(3 * Math.PI / 2, result, 1e-6); result = optimizer.optimize(50, f, GoalType.MINIMIZE, 4, 3 * Math.PI / 2).getPoint(); Assert.assertEquals(3 * Math.PI / 2, result, 1e-6); } @Test public void testMath832() { final UnivariateFunction f = new UnivariateFunction() { public double value(double x) { final double sqrtX = FastMath.sqrt(x); final double a = 1e2 * sqrtX; final double b = 1e6 / x; final double c = 1e4 / sqrtX; return a + b + c; } }; UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-8); final double result = optimizer.optimize(1483, f, GoalType.MINIMIZE, Double.MIN_VALUE, Double.MAX_VALUE).getPoint(); Assert.assertEquals(804.9355825, result, 1e-6); } /** * Contrived example showing that prior to the resolution of MATH-855, * the algorithm, by always returning the last evaluated point, would * sometimes not report the best point it had found. */ @Test public void testMath855() { final double minSin = 3 * Math.PI / 2; final double offset = 1e-8; final double delta = 1e-7; final UnivariateFunction f1 = new Sin(); final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 5 * offset }, new double[] { 0, -1, 0 }); final UnivariateFunction f = FunctionUtils.add(f1, f2); final UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-100); final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, minSin - 6.789 * delta, minSin + 9.876 * delta); final int numEval = optimizer.getEvaluations(); final double sol = result.getPoint(); final double expected = 4.712389027602411; // System.out.println("min=" + (minSin + offset) + " f=" + f.value(minSin + offset)); // System.out.println("sol=" + sol + " f=" + f.value(sol)); // System.out.println("exp=" + expected + " f=" + f.value(expected)); Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected)); } }
public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); // LANG-664 val = "1.1L"; assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val)); }
org.apache.commons.lang3.math.NumberUtilsTest::testIsNumber
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
1,145
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
testIsNumber
/* * 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.math; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import junit.framework.TestCase; import org.apache.commons.lang3.SystemUtils; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @author Apache Software Foundation * @author <a href="mailto:[email protected]">Rand McNeely</a> * @author <a href="mailto:[email protected]">Ringo De Smet</a> * @author Eric Pugh * @author Phil Steitz * @author Matthew Hawthorne * @author <a href="mailto:[email protected]">Gary Gregory</a> * @version $Id$ */ public class NumberUtilsTest extends TestCase { public NumberUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new NumberUtils()); Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(NumberUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {@link NumberUtils#toDouble(String)}. */ public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", new Integer("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 10 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertEquals("createNumber(String) 11 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); // jdk 1.2 doesn't support this. unsure about jdk 1.2.2 if (SystemUtils.isJavaVersionAtLeast(1.3f)) { assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); } assertEquals("createNumber(String) 16 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", new Float("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); } public void testCreateFloat() { assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(String str) { try { Float value = NumberUtils.createFloat(str); fail("createFloat(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateDouble() { assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(String str) { try { Double value = NumberUtils.createDouble(str); fail("createDouble(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateInteger() { assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(String str) { try { Integer value = NumberUtils.createInteger(str); fail("createInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateLong() { assertEquals("createLong(String) failed", new Long("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(String str) { try { Long value = NumberUtils.createLong(str); fail("createLong(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigIntegerFailure(String str) { try { BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigDecimalFailure(String str) { try { BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- public void testMinLong() { final long[] l = null; try { NumberUtils.min(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } public void testMinInt() { final int[] i = null; try { NumberUtils.min(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } public void testMinShort() { final short[] s = null; try { NumberUtils.min(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } public void testMinByte() { final byte[] b = null; try { NumberUtils.min(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } public void testMinDouble() { final double[] d = null; try { NumberUtils.min(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } public void testMinFloat() { final float[] f = null; try { NumberUtils.min(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } public void testMaxLong() { final long[] l = null; try { NumberUtils.max(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } public void testMaxInt() { final int[] i = null; try { NumberUtils.max(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } public void testMaxShort() { final short[] s = null; try { NumberUtils.max(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } public void testMaxByte() { final byte[] b = null; try { NumberUtils.max(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } public void testMaxFloat() { final float[] f = null; try { NumberUtils.max(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } public void testMinimumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } public void testMinimumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } public void testMaximumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } public void testMaximumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } public void testIsDigits() { assertEquals("isDigits(null) failed", false, NumberUtils.isDigits(null)); assertEquals("isDigits('') failed", false, NumberUtils.isDigits("")); assertEquals("isDigits(String) failed", true, NumberUtils.isDigits("12345")); assertEquals("isDigits(String) neg 1 failed", false, NumberUtils.isDigits("1234.5")); assertEquals("isDigits(String) neg 3 failed", false, NumberUtils.isDigits("1ab")); assertEquals("isDigits(String) neg 4 failed", false, NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); // LANG-664 val = "1.1L"; assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(String val) { try { Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
// You are a professional Java test case writer, please create a test case named `testIsNumber` for the issue `Lang-LANG-664`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-664 // // ## Issue-Title: // NumberUtils.isNumber(String) is not right when the String is "1.1L" // // ## Issue-Description: // // "1.1L" is not a Java Number . but NumberUtils.isNumber(String) return true. // // // perhaps change: // // // // // ``` // if (chars[i] == 'l' // || chars[i] == 'L') { // // not allowing L with an exponent // return foundDigit && !hasExp; // } // // ``` // // // to: // // // // // ``` // if (chars[i] == 'l' // || chars[i] == 'L') { // // not allowing L with an exponent // return foundDigit && !hasExp && !hasDecPoint; // } // // ``` // // // // // public void testIsNumber() {
1,145
/** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */
24
1,004
src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java
src/test/java
```markdown ## Issue-ID: Lang-LANG-664 ## Issue-Title: NumberUtils.isNumber(String) is not right when the String is "1.1L" ## Issue-Description: "1.1L" is not a Java Number . but NumberUtils.isNumber(String) return true. perhaps change: ``` if (chars[i] == 'l' || chars[i] == 'L') { // not allowing L with an exponent return foundDigit && !hasExp; } ``` to: ``` if (chars[i] == 'l' || chars[i] == 'L') { // not allowing L with an exponent return foundDigit && !hasExp && !hasDecPoint; } ``` ``` You are a professional Java test case writer, please create a test case named `testIsNumber` for the issue `Lang-LANG-664`, utilizing the provided issue report information and the following function signature. ```java public void testIsNumber() { ```
1,004
[ "org.apache.commons.lang3.math.NumberUtils" ]
e288b6477f0427ea56e26de05b3df30a5cea05706fd275540fb22fc66f9152a8
public void testIsNumber()
// You are a professional Java test case writer, please create a test case named `testIsNumber` for the issue `Lang-LANG-664`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-664 // // ## Issue-Title: // NumberUtils.isNumber(String) is not right when the String is "1.1L" // // ## Issue-Description: // // "1.1L" is not a Java Number . but NumberUtils.isNumber(String) return true. // // // perhaps change: // // // // // ``` // if (chars[i] == 'l' // || chars[i] == 'L') { // // not allowing L with an exponent // return foundDigit && !hasExp; // } // // ``` // // // to: // // // // // ``` // if (chars[i] == 'l' // || chars[i] == 'L') { // // not allowing L with an exponent // return foundDigit && !hasExp && !hasDecPoint; // } // // ``` // // // // //
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.math; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import junit.framework.TestCase; import org.apache.commons.lang3.SystemUtils; /** * Unit tests {@link org.apache.commons.lang3.math.NumberUtils}. * * @author Apache Software Foundation * @author <a href="mailto:[email protected]">Rand McNeely</a> * @author <a href="mailto:[email protected]">Ringo De Smet</a> * @author Eric Pugh * @author Phil Steitz * @author Matthew Hawthorne * @author <a href="mailto:[email protected]">Gary Gregory</a> * @version $Id$ */ public class NumberUtilsTest extends TestCase { public NumberUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new NumberUtils()); Constructor<?>[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(NumberUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#toInt(String)}. */ public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {@link NumberUtils#toDouble(String)}. */ public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", new Integer("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 10 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertEquals("createNumber(String) 11 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); // jdk 1.2 doesn't support this. unsure about jdk 1.2.2 if (SystemUtils.isJavaVersionAtLeast(1.3f)) { assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); } assertEquals("createNumber(String) 16 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", new Float("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); } public void testCreateFloat() { assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(String str) { try { Float value = NumberUtils.createFloat(str); fail("createFloat(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateDouble() { assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(String str) { try { Double value = NumberUtils.createDouble(str); fail("createDouble(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateInteger() { assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(String str) { try { Integer value = NumberUtils.createInteger(str); fail("createInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateLong() { assertEquals("createLong(String) failed", new Long("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(String str) { try { Long value = NumberUtils.createLong(str); fail("createLong(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigIntegerFailure(String str) { try { BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigDecimalFailure(String str) { try { BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- public void testMinLong() { final long[] l = null; try { NumberUtils.min(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } public void testMinInt() { final int[] i = null; try { NumberUtils.min(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } public void testMinShort() { final short[] s = null; try { NumberUtils.min(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } public void testMinByte() { final byte[] b = null; try { NumberUtils.min(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } public void testMinDouble() { final double[] d = null; try { NumberUtils.min(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } public void testMinFloat() { final float[] f = null; try { NumberUtils.min(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } public void testMaxLong() { final long[] l = null; try { NumberUtils.max(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } public void testMaxInt() { final int[] i = null; try { NumberUtils.max(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } public void testMaxShort() { final short[] s = null; try { NumberUtils.max(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } public void testMaxByte() { final byte[] b = null; try { NumberUtils.max(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } public void testMaxFloat() { final float[] f = null; try { NumberUtils.max(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } public void testMinimumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } public void testMinimumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } public void testMaximumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } public void testMaximumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } // Testing JDK against old Lang functionality public void testCompareDouble() { assertTrue(Double.compare(Double.NaN, Double.NaN) == 0); assertTrue(Double.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, 1.2d) == +1); assertTrue(Double.compare(Double.NaN, 0.0d) == +1); assertTrue(Double.compare(Double.NaN, -0.0d) == +1); assertTrue(Double.compare(Double.NaN, -1.2d) == +1); assertTrue(Double.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(Double.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(1.2d, Double.NaN) == -1); assertTrue(Double.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(1.2d, 1.2d) == 0); assertTrue(Double.compare(1.2d, 0.0d) == +1); assertTrue(Double.compare(1.2d, -0.0d) == +1); assertTrue(Double.compare(1.2d, -1.2d) == +1); assertTrue(Double.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(0.0d, Double.NaN) == -1); assertTrue(Double.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(0.0d, 1.2d) == -1); assertTrue(Double.compare(0.0d, 0.0d) == 0); assertTrue(Double.compare(0.0d, -0.0d) == +1); assertTrue(Double.compare(0.0d, -1.2d) == +1); assertTrue(Double.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-0.0d, Double.NaN) == -1); assertTrue(Double.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-0.0d, 1.2d) == -1); assertTrue(Double.compare(-0.0d, 0.0d) == -1); assertTrue(Double.compare(-0.0d, -0.0d) == 0); assertTrue(Double.compare(-0.0d, -1.2d) == +1); assertTrue(Double.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-1.2d, Double.NaN) == -1); assertTrue(Double.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-1.2d, 1.2d) == -1); assertTrue(Double.compare(-1.2d, 0.0d) == -1); assertTrue(Double.compare(-1.2d, -0.0d) == -1); assertTrue(Double.compare(-1.2d, -1.2d) == 0); assertTrue(Double.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(Double.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } public void testCompareFloat() { assertTrue(Float.compare(Float.NaN, Float.NaN) == 0); assertTrue(Float.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, 1.2f) == +1); assertTrue(Float.compare(Float.NaN, 0.0f) == +1); assertTrue(Float.compare(Float.NaN, -0.0f) == +1); assertTrue(Float.compare(Float.NaN, -1.2f) == +1); assertTrue(Float.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(Float.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(1.2f, Float.NaN) == -1); assertTrue(Float.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(1.2f, 1.2f) == 0); assertTrue(Float.compare(1.2f, 0.0f) == +1); assertTrue(Float.compare(1.2f, -0.0f) == +1); assertTrue(Float.compare(1.2f, -1.2f) == +1); assertTrue(Float.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(0.0f, Float.NaN) == -1); assertTrue(Float.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(0.0f, 1.2f) == -1); assertTrue(Float.compare(0.0f, 0.0f) == 0); assertTrue(Float.compare(0.0f, -0.0f) == +1); assertTrue(Float.compare(0.0f, -1.2f) == +1); assertTrue(Float.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-0.0f, Float.NaN) == -1); assertTrue(Float.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-0.0f, 1.2f) == -1); assertTrue(Float.compare(-0.0f, 0.0f) == -1); assertTrue(Float.compare(-0.0f, -0.0f) == 0); assertTrue(Float.compare(-0.0f, -1.2f) == +1); assertTrue(Float.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-1.2f, Float.NaN) == -1); assertTrue(Float.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-1.2f, 1.2f) == -1); assertTrue(Float.compare(-1.2f, 0.0f) == -1); assertTrue(Float.compare(-1.2f, -0.0f) == -1); assertTrue(Float.compare(-1.2f, -1.2f) == 0); assertTrue(Float.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(Float.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } public void testIsDigits() { assertEquals("isDigits(null) failed", false, NumberUtils.isDigits(null)); assertEquals("isDigits('') failed", false, NumberUtils.isDigits("")); assertEquals("isDigits(String) failed", true, NumberUtils.isDigits("12345")); assertEquals("isDigits(String) neg 1 failed", false, NumberUtils.isDigits("1234.5")); assertEquals("isDigits(String) neg 3 failed", false, NumberUtils.isDigits("1ab")); assertEquals("isDigits(String) neg 4 failed", false, NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); // LANG-664 val = "1.1L"; assertFalse("isNumber(String) LANG-664 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(String val) { try { Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (NumberFormatException e) { return false; } } @SuppressWarnings("cast") // suppress instanceof warning check public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } }
public void testProvideInIndependentModules4() { // Regression test for bug 261: // http://code.google.com/p/closure-compiler/issues/detail?id=261 test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.bar.B');", "goog.provide('apps.foo.bar.C');"), new String[] { "var apps = {};apps.foo = {};apps.foo.bar = {}", "apps.foo.bar.B = {};", "apps.foo.bar.C = {};", }); }
com.google.javascript.jscomp.ProcessClosurePrimitivesTest::testProvideInIndependentModules4
test/com/google/javascript/jscomp/ProcessClosurePrimitivesTest.java
786
test/com/google/javascript/jscomp/ProcessClosurePrimitivesTest.java
testProvideInIndependentModules4
/* * 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.javascript.rhino.Node; import com.google.javascript.jscomp.CheckLevel; import static com.google.javascript.jscomp.ProcessClosurePrimitives.BASE_CLASS_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.DUPLICATE_NAMESPACE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.FUNCTION_NAMESPACE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.INVALID_ARGUMENT_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.INVALID_PROVIDE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.LATE_PROVIDE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.MISSING_PROVIDE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.NULL_ARGUMENT_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.TOO_MANY_ARGUMENTS_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.XMODULE_REQUIRE_ERROR; /** * Tests for {@link ProcessClosurePrimitives}. * */ public class ProcessClosurePrimitivesTest extends CompilerTestCase { private String additionalCode; private String additionalEndCode; private boolean addAdditionalNamespace; public ProcessClosurePrimitivesTest() { enableLineNumberCheck(true); } @Override protected void setUp() { additionalCode = null; additionalEndCode = null; addAdditionalNamespace = false; } @Override public CompilerPass getProcessor(final Compiler compiler) { if ((additionalCode == null) && (additionalEndCode == null)) { return new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true); } else { return new CompilerPass() { public void process(Node externs, Node root) { // Process the original code. new ProcessClosurePrimitives(compiler, CheckLevel.OFF, true) .process(externs, root); // Inject additional code at the beginning. if (additionalCode != null) { JSSourceFile file = JSSourceFile.fromCode("additionalcode", additionalCode); Node scriptNode = root.getFirstChild(); Node newScriptNode = new CompilerInput(file).getAstRoot(compiler); if (addAdditionalNamespace) { newScriptNode.getFirstChild() .putBooleanProp(Node.IS_NAMESPACE, true); } while (newScriptNode.getLastChild() != null) { Node lastChild = newScriptNode.getLastChild(); newScriptNode.removeChild(lastChild); scriptNode.addChildBefore(lastChild, scriptNode.getFirstChild()); } } // Inject additional code at the end. if (additionalEndCode != null) { JSSourceFile file = JSSourceFile.fromCode("additionalendcode", additionalEndCode); Node scriptNode = root.getFirstChild(); Node newScriptNode = new CompilerInput(file).getAstRoot(compiler); if (addAdditionalNamespace) { newScriptNode.getFirstChild() .putBooleanProp(Node.IS_NAMESPACE, true); } while (newScriptNode.getFirstChild() != null) { Node firstChild = newScriptNode.getFirstChild(); newScriptNode.removeChild(firstChild); scriptNode.addChildToBack(firstChild); } } // Process the tree a second time. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(externs, root); } }; } } @Override public int getNumRepetitions() { return 1; } public void testSimpleProvides() { test("goog.provide('foo');", "var foo={};"); test("goog.provide('foo.bar');", "var foo={}; foo.bar={};"); test("goog.provide('foo.bar.baz');", "var foo={}; foo.bar={}; foo.bar.baz={};"); test("goog.provide('foo.bar.baz.boo');", "var foo={}; foo.bar={}; foo.bar.baz={}; foo.bar.baz.boo={};"); test("goog.provide('goog.bar');", "goog.bar={};"); // goog is special-cased } public void testMultipleProvides() { test("goog.provide('foo.bar'); goog.provide('foo.baz');", "var foo={}; foo.bar={}; foo.baz={};"); test("goog.provide('foo.bar.baz'); goog.provide('foo.boo.foo');", "var foo={}; foo.bar={}; foo.bar.baz={}; foo.boo={}; foo.boo.foo={};"); test("goog.provide('foo.bar.baz'); goog.provide('foo.bar.boo');", "var foo={}; foo.bar={}; foo.bar.baz={}; foo.bar.boo={};"); test("goog.provide('foo.bar.baz'); goog.provide('goog.bar.boo');", "var foo={}; foo.bar={}; foo.bar.baz={}; goog.bar={}; " + "goog.bar.boo={};"); } public void testRemovalOfProvidedObjLit() { test("goog.provide('foo'); foo = 0;", "var foo = 0;"); test("goog.provide('foo'); foo = {a: 0};", "var foo = {a: 0};"); test("goog.provide('foo'); foo = function(){};", "var foo = function(){};"); test("goog.provide('foo'); var foo = 0;", "var foo = 0;"); test("goog.provide('foo'); var foo = {a: 0};", "var foo = {a: 0};"); test("goog.provide('foo'); var foo = function(){};", "var foo = function(){};"); test("goog.provide('foo.bar.Baz'); foo.bar.Baz=function(){};", "var foo={}; foo.bar={}; foo.bar.Baz=function(){};"); test("goog.provide('foo.bar.moo'); foo.bar.moo={E:1,S:2};", "var foo={}; foo.bar={}; foo.bar.moo={E:1,S:2};"); test("goog.provide('foo.bar.moo'); foo.bar.moo={E:1}; foo.bar.moo={E:2};", "var foo={}; foo.bar={}; foo.bar.moo={E:1}; foo.bar.moo={E:2};"); } public void testProvidedDeclaredFunctionError() { test("goog.provide('foo'); function foo(){}", null, FUNCTION_NAMESPACE_ERROR); } public void testRemovalMultipleAssignment1() { test("goog.provide('foo'); foo = 0; foo = 1", "var foo = 0; foo = 1;"); } public void testRemovalMultipleAssignment2() { test("goog.provide('foo'); var foo = 0; foo = 1", "var foo = 0; foo = 1;"); } public void testRemovalMultipleAssignment3() { test("goog.provide('foo'); foo = 0; var foo = 1", "foo = 0; var foo = 1;"); } public void testRemovalMultipleAssignment4() { test("goog.provide('foo.bar'); foo.bar = 0; foo.bar = 1", "var foo = {}; foo.bar = 0; foo.bar = 1"); } public void testNoRemovalFunction1() { test("goog.provide('foo'); function f(){foo = 0}", "var foo = {}; function f(){foo = 0}"); } public void testNoRemovalFunction2() { test("goog.provide('foo'); function f(){var foo = 0}", "var foo = {}; function f(){var foo = 0}"); } public void testRemovalMultipleAssignmentInIf1() { test("goog.provide('foo'); if (true) { var foo = 0 } else { foo = 1 }", "if (true) { var foo = 0 } else { foo = 1 }"); } public void testRemovalMultipleAssignmentInIf2() { test("goog.provide('foo'); if (true) { foo = 0 } else { var foo = 1 }", "if (true) { foo = 0 } else { var foo = 1 }"); } public void testRemovalMultipleAssignmentInIf3() { test("goog.provide('foo'); if (true) { foo = 0 } else { foo = 1 }", "if (true) { var foo = 0 } else { foo = 1 }"); } public void testRemovalMultipleAssignmentInIf4() { test("goog.provide('foo.bar');" + "if (true) { foo.bar = 0 } else { foo.bar = 1 }", "var foo = {}; if (true) { foo.bar = 0 } else { foo.bar = 1 }"); } public void testMultipleDeclarationError1() { String rest = "if (true) { foo.bar = 0 } else { foo.bar = 1 }"; test("goog.provide('foo.bar');" + "var foo = {};" + rest, "var foo = {};" + "var foo = {};" + rest); } public void testMultipleDeclarationError2() { test("goog.provide('foo.bar');" + "if (true) { var foo = {}; foo.bar = 0 } else { foo.bar = 1 }", "var foo = {};" + "if (true) {" + " var foo = {}; foo.bar = 0" + "} else {" + " foo.bar = 1" + "}"); } public void testMultipleDeclarationError3() { test("goog.provide('foo.bar');" + "if (true) { foo.bar = 0 } else { var foo = {}; foo.bar = 1 }", "var foo = {};" + "if (true) {" + " foo.bar = 0" + "} else {" + " var foo = {}; foo.bar = 1" + "}"); } public void testProvideAfterDeclarationError() { test("var x = 42; goog.provide('x');", "var x = 42; var x = {}"); } public void testProvideErrorCases() { test("goog.provide();", "", NULL_ARGUMENT_ERROR); test("goog.provide(5);", "", INVALID_ARGUMENT_ERROR); test("goog.provide([]);", "", INVALID_ARGUMENT_ERROR); test("goog.provide({});", "", INVALID_ARGUMENT_ERROR); test("goog.provide('foo', 'bar');", "", TOO_MANY_ARGUMENTS_ERROR); test("goog.provide('foo'); goog.provide('foo');", "", DUPLICATE_NAMESPACE_ERROR); test("goog.provide('foo.bar'); goog.provide('foo'); goog.provide('foo');", "", DUPLICATE_NAMESPACE_ERROR); } public void testRemovalOfRequires() { test("goog.provide('foo'); goog.require('foo');", "var foo={};"); test("goog.provide('foo.bar'); goog.require('foo.bar');", "var foo={}; foo.bar={};"); test("goog.provide('foo.bar.baz'); goog.require('foo.bar.baz');", "var foo={}; foo.bar={}; foo.bar.baz={};"); test("goog.provide('foo'); var x = 3; goog.require('foo'); something();", "var foo={}; var x = 3; something();"); testSame("foo.require('foo.bar');"); } public void testRequireErrorCases() { test("goog.require();", "", NULL_ARGUMENT_ERROR); test("goog.require(5);", "", INVALID_ARGUMENT_ERROR); test("goog.require([]);", "", INVALID_ARGUMENT_ERROR); test("goog.require({});", "", INVALID_ARGUMENT_ERROR); } public void testLateProvides() { test("goog.require('foo'); goog.provide('foo');", "var foo={};", LATE_PROVIDE_ERROR); test("goog.require('foo.bar'); goog.provide('foo.bar');", "var foo={}; foo.bar={};", LATE_PROVIDE_ERROR); test("goog.provide('foo.bar'); goog.require('foo'); goog.provide('foo');", "var foo={}; foo.bar={};", LATE_PROVIDE_ERROR); } public void testMissingProvides() { test("goog.require('foo');", "", MISSING_PROVIDE_ERROR); test("goog.provide('foo'); goog.require('Foo');", "var foo={};", MISSING_PROVIDE_ERROR); test("goog.provide('foo'); goog.require('foo.bar');", "var foo={};", MISSING_PROVIDE_ERROR); test("goog.provide('foo'); var EXPERIMENT_FOO = true; " + "if (EXPERIMENT_FOO) {goog.require('foo.bar');}", "var foo={}; var EXPERIMENT_FOO = true; if (EXPERIMENT_FOO) {}", MISSING_PROVIDE_ERROR); } public void testNewDateGoogNowSimplification() { test("var x = new Date(goog.now());", "var x = new Date();"); testSame("var x = new Date(goog.now() + 1);"); testSame("var x = new Date(goog.now(1));"); testSame("var x = new Date(1, goog.now());"); testSame("var x = new Date(1);"); testSame("var x = new Date();"); } public void testAddDependency() { test("goog.addDependency('x.js', ['A', 'B'], []);", "0"); Compiler compiler = getLastCompiler(); assertTrue(compiler.getTypeRegistry().isForwardDeclaredType("A")); assertTrue(compiler.getTypeRegistry().isForwardDeclaredType("B")); assertFalse(compiler.getTypeRegistry().isForwardDeclaredType("C")); } public void testValidSetCssNameMapping() { test("goog.setCssNameMapping({foo:'bar',\"biz\":'baz'});", ""); CssRenamingMap map = getLastCompiler().getCssRenamingMap(); assertNotNull(map); assertEquals("bar", map.get("foo")); assertEquals("baz", map.get("biz")); } public void testSetCssNameMappingNonStringValueReturnsError() { // Make sure the argument is an object literal. test("var BAR = {foo:'bar'}; goog.setCssNameMapping(BAR);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping([]);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping(false);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping(null);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping(undefined);", "", INVALID_ARGUMENT_ERROR); // Make sure all values of the object literal are string literals. test("var BAR = 'bar'; goog.setCssNameMapping({foo:BAR});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:6});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:false});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:null});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:undefined});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); } public void testBadCrossModuleRequire() { test( createModuleStar( "", "goog.provide('goog.ui');", "goog.require('goog.ui');"), new String[] { "", "goog.ui = {};", "" }, null, XMODULE_REQUIRE_ERROR); } public void testGoodCrossModuleRequire1() { test( createModuleStar( "goog.provide('goog.ui');", "", "goog.require('goog.ui');"), new String[] { "goog.ui = {};", "", "", }); } public void testGoodCrossModuleRequire2() { test( createModuleStar( "", "", "goog.provide('goog.ui'); goog.require('goog.ui');"), new String[] { "", "", "goog.ui = {};", }); } // Tests providing additional code with non-overlapping var namespace. public void testSimpleAdditionalProvide() { additionalCode = "goog.provide('b.B'); b.B = {};"; test("goog.provide('a.A'); a.A = {};", "var b={};b.B={};var a={};a.A={};"); } // Same as above, but with the additional code added after the original. public void testSimpleAdditionalProvideAtEnd() { additionalEndCode = "goog.provide('b.B'); b.B = {};"; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};var b={};b.B={};"); } // Tests providing additional code with non-overlapping dotted namespace. public void testSimpleDottedAdditionalProvide() { additionalCode = "goog.provide('a.b.B'); a.b.B = {};"; test("goog.provide('c.d.D'); c.d.D = {};", "var a={};a.b={};a.b.B={};var c={};c.d={};c.d.D={};"); } // Tests providing additional code with overlapping var namespace. public void testOverlappingAdditionalProvide() { additionalCode = "goog.provide('a.B'); a.B = {};"; test("goog.provide('a.A'); a.A = {};", "var a={};a.B={};a.A={};"); } // Tests providing additional code with overlapping var namespace. public void testOverlappingAdditionalProvideAtEnd() { additionalEndCode = "goog.provide('a.B'); a.B = {};"; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};a.B={};"); } // Tests providing additional code with overlapping dotted namespace. public void testOverlappingDottedAdditionalProvide() { additionalCode = "goog.provide('a.b.B'); a.b.B = {};"; test("goog.provide('a.b.C'); a.b.C = {};", "var a={};a.b={};a.b.B={};a.b.C={};"); } // Tests that a require of additional code generates no error. public void testRequireOfAdditionalProvide() { additionalCode = "goog.provide('b.B'); b.B = {};"; test("goog.require('b.B'); goog.provide('a.A'); a.A = {};", "var b={};b.B={};var a={};a.A={};"); } // Tests that a require not in additional code generates (only) one error. public void testMissingRequireWithAdditionalProvide() { additionalCode = "goog.provide('b.B'); b.B = {};"; test("goog.require('b.C'); goog.provide('a.A'); a.A = {};", "var b={};b.B={};var a={};a.A={};", MISSING_PROVIDE_ERROR); } // Tests that a require in additional code generates no error. public void testLateRequire() { additionalEndCode = "goog.require('a.A');"; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};"); } // Tests a case where code is reordered after processing provides and then // provides are processed again. public void testReorderedProvides() { additionalCode = "a.B = {};"; // as if a.B was after a.A originally addAdditionalNamespace = true; test("goog.provide('a.A'); a.A = {};", "var a={};a.B={};a.A={};"); } // Another version of above. public void testReorderedProvides2() { additionalEndCode = "a.B = {};"; addAdditionalNamespace = true; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};a.B={};"); } // Provide a name before the definition of the class providing the // parent namespace. public void testProvideOrder1() { additionalEndCode = ""; addAdditionalNamespace = false; // TODO(johnlenz): This test confirms that the constructor (a.b) isn't // improperly removed, but this result isn't really what we want as the // reassign of a.b removes the definition of "a.b.c". test("goog.provide('a.b');" + "goog.provide('a.b.c');" + "a.b.c;" + "a.b = function(x,y) {};", "var a = {};" + "a.b = {};" + "a.b.c = {};" + "a.b.c;" + "a.b = function(x,y) {};"); } // Provide a name after the definition of the class providing the // parent namespace. public void testProvideOrder2() { additionalEndCode = ""; addAdditionalNamespace = false; // TODO(johnlenz): This test confirms that the constructor (a.b) isn't // improperly removed, but this result isn't really what we want as // namespace placeholders for a.b and a.b.c remain. test("goog.provide('a.b');" + "goog.provide('a.b.c');" + "a.b = function(x,y) {};" + "a.b.c;", "var a = {};" + "a.b = {};" + "a.b.c = {};" + "a.b = function(x,y) {};" + "a.b.c;"); } // Provide a name after the definition of the class providing the // parent namespace. public void testProvideOrder3a() { test("goog.provide('a.b');" + "a.b = function(x,y) {};" + "goog.provide('a.b.c');" + "a.b.c;", "var a = {};" + "a.b = function(x,y) {};" + "a.b.c = {};" + "a.b.c;"); } public void testProvideOrder3b() { additionalEndCode = ""; addAdditionalNamespace = false; // This tests a cleanly provided name, below a function namespace. test("goog.provide('a.b');" + "a.b = function(x,y) {};" + "goog.provide('a.b.c');" + "a.b.c;", "var a = {};" + "a.b = function(x,y) {};" + "a.b.c = {};" + "a.b.c;"); } public void testProvideOrder4a() { test("goog.provide('goog.a');" + "goog.provide('goog.a.b');" + "if (x) {" + " goog.a.b = 1;" + "} else {" + " goog.a.b = 2;" + "}", "goog.a={};" + "if(x)" + " goog.a.b=1;" + "else" + " goog.a.b=2;"); } public void testProvideOrder4b() { additionalEndCode = ""; addAdditionalNamespace = false; // This tests a cleanly provided name, below a namespace. test("goog.provide('goog.a');" + "goog.provide('goog.a.b');" + "if (x) {" + " goog.a.b = 1;" + "} else {" + " goog.a.b = 2;" + "}", "goog.a={};" + "if(x)" + " goog.a.b=1;" + "else" + " goog.a.b=2;"); } public void testInvalidProvide() { test("goog.provide('a.class');", null, INVALID_PROVIDE_ERROR); } private static final String METHOD_FORMAT = "function Foo() {} Foo.prototype.method = function() { %s };"; private static final String FOO_INHERITS = "goog.inherits(Foo, BaseFoo);"; public void testInvalidBase1() { test("goog.base(this, 'method');", null, BASE_CLASS_ERROR); } public void testInvalidBase2() { test("function Foo() {}" + "Foo.method = function() {" + " goog.base(this, 'method');" + "};", null, BASE_CLASS_ERROR); } public void testInvalidBase3() { test(String.format(METHOD_FORMAT, "goog.base();"), null, BASE_CLASS_ERROR); } public void testInvalidBase4() { test(String.format(METHOD_FORMAT, "goog.base(this, 'bar');"), null, BASE_CLASS_ERROR); } public void testInvalidBase5() { test(String.format(METHOD_FORMAT, "goog.base('foo', 'method');"), null, BASE_CLASS_ERROR); } public void testInvalidBase6() { test(String.format(METHOD_FORMAT, "goog.base.call(null, this, 'method');"), null, BASE_CLASS_ERROR); } public void testInvalidBase7() { test("function Foo() { goog.base(this); }", null, BASE_CLASS_ERROR); } public void testInvalidBase8() { test("var Foo = function() { goog.base(this); }", null, BASE_CLASS_ERROR); } public void testInvalidBase9() { test("var goog = {}; goog.Foo = function() { goog.base(this); }", null, BASE_CLASS_ERROR); } public void testValidBase1() { test(String.format(METHOD_FORMAT, "goog.base(this, 'method');"), String.format(METHOD_FORMAT, "Foo.superClass_.method.call(this)")); } public void testValidBase2() { test(String.format(METHOD_FORMAT, "goog.base(this, 'method', 1, 2);"), String.format(METHOD_FORMAT, "Foo.superClass_.method.call(this, 1, 2)")); } public void testValidBase3() { test(String.format(METHOD_FORMAT, "return goog.base(this, 'method');"), String.format(METHOD_FORMAT, "return Foo.superClass_.method.call(this)")); } public void testValidBase4() { test("function Foo() { goog.base(this, 1, 2); }" + FOO_INHERITS, "function Foo() { BaseFoo.call(this, 1, 2); } " + FOO_INHERITS); } public void testValidBase5() { test("var Foo = function() { goog.base(this, 1); };" + FOO_INHERITS, "var Foo = function() { BaseFoo.call(this, 1); }; " + FOO_INHERITS); } public void testValidBase6() { test("var goog = {}; goog.Foo = function() { goog.base(this); }; " + "goog.inherits(goog.Foo, goog.BaseFoo);", "var goog = {}; goog.Foo = function() { goog.BaseFoo.call(this); }; " + "goog.inherits(goog.Foo, goog.BaseFoo);"); } public void testImplicitAndExplicitProvide() { test("var goog = {}; " + "goog.provide('goog.foo.bar'); goog.provide('goog.foo');", "var goog = {}; goog.foo = {}; goog.foo.bar = {};"); } public void testImplicitProvideInIndependentModules() { test( createModuleStar( "", "goog.provide('apps.A');", "goog.provide('apps.B');"), new String[] { "var apps = {};", "apps.A = {};", "apps.B = {};", }); } public void testImplicitProvideInIndependentModules2() { test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.A');", "goog.provide('apps.foo.B');"), new String[] { "var apps = {}; apps.foo = {};", "apps.foo.A = {};", "apps.foo.B = {};", }); } public void testImplicitProvideInIndependentModules3() { test( createModuleStar( "var goog = {};", "goog.provide('goog.foo.A');", "goog.provide('goog.foo.B');"), new String[] { "var goog = {}; goog.foo = {};", "goog.foo.A = {};", "goog.foo.B = {};", }); } public void testProvideInIndependentModules1() { test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo');", "goog.provide('apps.foo.B');"), new String[] { "var apps = {}; apps.foo = {};", "", "apps.foo.B = {};", }); } public void testProvideInIndependentModules2() { // TODO(nicksantos): Make this an error. test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo'); apps.foo = {};", "goog.provide('apps.foo.B');"), new String[] { "var apps = {};", "apps.foo = {};", "apps.foo.B = {};", }); } public void testProvideInIndependentModules2b() { // TODO(nicksantos): Make this an error. test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo'); apps.foo = function() {};", "goog.provide('apps.foo.B');"), new String[] { "var apps = {};", "apps.foo = function() {};", "apps.foo.B = {};", }); } public void testProvideInIndependentModules3() { test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.B');", "goog.provide('apps.foo'); goog.require('apps.foo');"), new String[] { "var apps = {}; apps.foo = {};", "apps.foo.B = {};", "", }); } public void testProvideInIndependentModules3b() { // TODO(nicksantos): Make this an error. test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.B');", "goog.provide('apps.foo'); apps.foo = function() {}; " + "goog.require('apps.foo');"), new String[] { "var apps = {};", "apps.foo.B = {};", "apps.foo = function() {};", }); } public void testProvideInIndependentModules4() { // Regression test for bug 261: // http://code.google.com/p/closure-compiler/issues/detail?id=261 test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.bar.B');", "goog.provide('apps.foo.bar.C');"), new String[] { "var apps = {};apps.foo = {};apps.foo.bar = {}", "apps.foo.bar.B = {};", "apps.foo.bar.C = {};", }); } public void testRequireOfBaseGoog() { test("goog.require('goog');", "", MISSING_PROVIDE_ERROR); } }
// You are a professional Java test case writer, please create a test case named `testProvideInIndependentModules4` for the issue `Closure-261`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-261 // // ## Issue-Title: // bug with implicit namespaces across modules // // ## Issue-Description: // If there are three modules, the latter two of which depend on the root module: // // // Module A // goog.provide('apps'); // // // Module B // goog.provide('apps.foo.bar.B'); // // // Module C // goog.provide('apps.foo.bar.C'); // // and this is compiled in SIMPLE\_OPTIMIZATIONS mode, the following code will be produced: // // // Module A // var apps={};apps.foo.bar={};apps.foo={}; // // // Module B // apps.foo.bar.B={}; // // // Module C // apps.foo.bar.C={}; // // This will result in a runtime error in Module A because apps.foo.bar is assigned before apps.foo. // // The patch for the fix (with regression test) is available at: // http://codereview.appspot.com/2416041 // // public void testProvideInIndependentModules4() {
786
92
773
test/com/google/javascript/jscomp/ProcessClosurePrimitivesTest.java
test
```markdown ## Issue-ID: Closure-261 ## Issue-Title: bug with implicit namespaces across modules ## Issue-Description: If there are three modules, the latter two of which depend on the root module: // Module A goog.provide('apps'); // Module B goog.provide('apps.foo.bar.B'); // Module C goog.provide('apps.foo.bar.C'); and this is compiled in SIMPLE\_OPTIMIZATIONS mode, the following code will be produced: // Module A var apps={};apps.foo.bar={};apps.foo={}; // Module B apps.foo.bar.B={}; // Module C apps.foo.bar.C={}; This will result in a runtime error in Module A because apps.foo.bar is assigned before apps.foo. The patch for the fix (with regression test) is available at: http://codereview.appspot.com/2416041 ``` You are a professional Java test case writer, please create a test case named `testProvideInIndependentModules4` for the issue `Closure-261`, utilizing the provided issue report information and the following function signature. ```java public void testProvideInIndependentModules4() { ```
773
[ "com.google.javascript.jscomp.ProcessClosurePrimitives" ]
e50181bf61b8c59da27927c1c6faed443e60239b2b7c87ff55e9333ed8556421
public void testProvideInIndependentModules4()
// You are a professional Java test case writer, please create a test case named `testProvideInIndependentModules4` for the issue `Closure-261`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-261 // // ## Issue-Title: // bug with implicit namespaces across modules // // ## Issue-Description: // If there are three modules, the latter two of which depend on the root module: // // // Module A // goog.provide('apps'); // // // Module B // goog.provide('apps.foo.bar.B'); // // // Module C // goog.provide('apps.foo.bar.C'); // // and this is compiled in SIMPLE\_OPTIMIZATIONS mode, the following code will be produced: // // // Module A // var apps={};apps.foo.bar={};apps.foo={}; // // // Module B // apps.foo.bar.B={}; // // // Module C // apps.foo.bar.C={}; // // This will result in a runtime error in Module A because apps.foo.bar is assigned before apps.foo. // // The patch for the fix (with regression test) is available at: // http://codereview.appspot.com/2416041 // //
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.javascript.rhino.Node; import com.google.javascript.jscomp.CheckLevel; import static com.google.javascript.jscomp.ProcessClosurePrimitives.BASE_CLASS_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.DUPLICATE_NAMESPACE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.FUNCTION_NAMESPACE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.INVALID_ARGUMENT_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.INVALID_PROVIDE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.LATE_PROVIDE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.MISSING_PROVIDE_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.NULL_ARGUMENT_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.TOO_MANY_ARGUMENTS_ERROR; import static com.google.javascript.jscomp.ProcessClosurePrimitives.XMODULE_REQUIRE_ERROR; /** * Tests for {@link ProcessClosurePrimitives}. * */ public class ProcessClosurePrimitivesTest extends CompilerTestCase { private String additionalCode; private String additionalEndCode; private boolean addAdditionalNamespace; public ProcessClosurePrimitivesTest() { enableLineNumberCheck(true); } @Override protected void setUp() { additionalCode = null; additionalEndCode = null; addAdditionalNamespace = false; } @Override public CompilerPass getProcessor(final Compiler compiler) { if ((additionalCode == null) && (additionalEndCode == null)) { return new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true); } else { return new CompilerPass() { public void process(Node externs, Node root) { // Process the original code. new ProcessClosurePrimitives(compiler, CheckLevel.OFF, true) .process(externs, root); // Inject additional code at the beginning. if (additionalCode != null) { JSSourceFile file = JSSourceFile.fromCode("additionalcode", additionalCode); Node scriptNode = root.getFirstChild(); Node newScriptNode = new CompilerInput(file).getAstRoot(compiler); if (addAdditionalNamespace) { newScriptNode.getFirstChild() .putBooleanProp(Node.IS_NAMESPACE, true); } while (newScriptNode.getLastChild() != null) { Node lastChild = newScriptNode.getLastChild(); newScriptNode.removeChild(lastChild); scriptNode.addChildBefore(lastChild, scriptNode.getFirstChild()); } } // Inject additional code at the end. if (additionalEndCode != null) { JSSourceFile file = JSSourceFile.fromCode("additionalendcode", additionalEndCode); Node scriptNode = root.getFirstChild(); Node newScriptNode = new CompilerInput(file).getAstRoot(compiler); if (addAdditionalNamespace) { newScriptNode.getFirstChild() .putBooleanProp(Node.IS_NAMESPACE, true); } while (newScriptNode.getFirstChild() != null) { Node firstChild = newScriptNode.getFirstChild(); newScriptNode.removeChild(firstChild); scriptNode.addChildToBack(firstChild); } } // Process the tree a second time. new ProcessClosurePrimitives(compiler, CheckLevel.ERROR, true) .process(externs, root); } }; } } @Override public int getNumRepetitions() { return 1; } public void testSimpleProvides() { test("goog.provide('foo');", "var foo={};"); test("goog.provide('foo.bar');", "var foo={}; foo.bar={};"); test("goog.provide('foo.bar.baz');", "var foo={}; foo.bar={}; foo.bar.baz={};"); test("goog.provide('foo.bar.baz.boo');", "var foo={}; foo.bar={}; foo.bar.baz={}; foo.bar.baz.boo={};"); test("goog.provide('goog.bar');", "goog.bar={};"); // goog is special-cased } public void testMultipleProvides() { test("goog.provide('foo.bar'); goog.provide('foo.baz');", "var foo={}; foo.bar={}; foo.baz={};"); test("goog.provide('foo.bar.baz'); goog.provide('foo.boo.foo');", "var foo={}; foo.bar={}; foo.bar.baz={}; foo.boo={}; foo.boo.foo={};"); test("goog.provide('foo.bar.baz'); goog.provide('foo.bar.boo');", "var foo={}; foo.bar={}; foo.bar.baz={}; foo.bar.boo={};"); test("goog.provide('foo.bar.baz'); goog.provide('goog.bar.boo');", "var foo={}; foo.bar={}; foo.bar.baz={}; goog.bar={}; " + "goog.bar.boo={};"); } public void testRemovalOfProvidedObjLit() { test("goog.provide('foo'); foo = 0;", "var foo = 0;"); test("goog.provide('foo'); foo = {a: 0};", "var foo = {a: 0};"); test("goog.provide('foo'); foo = function(){};", "var foo = function(){};"); test("goog.provide('foo'); var foo = 0;", "var foo = 0;"); test("goog.provide('foo'); var foo = {a: 0};", "var foo = {a: 0};"); test("goog.provide('foo'); var foo = function(){};", "var foo = function(){};"); test("goog.provide('foo.bar.Baz'); foo.bar.Baz=function(){};", "var foo={}; foo.bar={}; foo.bar.Baz=function(){};"); test("goog.provide('foo.bar.moo'); foo.bar.moo={E:1,S:2};", "var foo={}; foo.bar={}; foo.bar.moo={E:1,S:2};"); test("goog.provide('foo.bar.moo'); foo.bar.moo={E:1}; foo.bar.moo={E:2};", "var foo={}; foo.bar={}; foo.bar.moo={E:1}; foo.bar.moo={E:2};"); } public void testProvidedDeclaredFunctionError() { test("goog.provide('foo'); function foo(){}", null, FUNCTION_NAMESPACE_ERROR); } public void testRemovalMultipleAssignment1() { test("goog.provide('foo'); foo = 0; foo = 1", "var foo = 0; foo = 1;"); } public void testRemovalMultipleAssignment2() { test("goog.provide('foo'); var foo = 0; foo = 1", "var foo = 0; foo = 1;"); } public void testRemovalMultipleAssignment3() { test("goog.provide('foo'); foo = 0; var foo = 1", "foo = 0; var foo = 1;"); } public void testRemovalMultipleAssignment4() { test("goog.provide('foo.bar'); foo.bar = 0; foo.bar = 1", "var foo = {}; foo.bar = 0; foo.bar = 1"); } public void testNoRemovalFunction1() { test("goog.provide('foo'); function f(){foo = 0}", "var foo = {}; function f(){foo = 0}"); } public void testNoRemovalFunction2() { test("goog.provide('foo'); function f(){var foo = 0}", "var foo = {}; function f(){var foo = 0}"); } public void testRemovalMultipleAssignmentInIf1() { test("goog.provide('foo'); if (true) { var foo = 0 } else { foo = 1 }", "if (true) { var foo = 0 } else { foo = 1 }"); } public void testRemovalMultipleAssignmentInIf2() { test("goog.provide('foo'); if (true) { foo = 0 } else { var foo = 1 }", "if (true) { foo = 0 } else { var foo = 1 }"); } public void testRemovalMultipleAssignmentInIf3() { test("goog.provide('foo'); if (true) { foo = 0 } else { foo = 1 }", "if (true) { var foo = 0 } else { foo = 1 }"); } public void testRemovalMultipleAssignmentInIf4() { test("goog.provide('foo.bar');" + "if (true) { foo.bar = 0 } else { foo.bar = 1 }", "var foo = {}; if (true) { foo.bar = 0 } else { foo.bar = 1 }"); } public void testMultipleDeclarationError1() { String rest = "if (true) { foo.bar = 0 } else { foo.bar = 1 }"; test("goog.provide('foo.bar');" + "var foo = {};" + rest, "var foo = {};" + "var foo = {};" + rest); } public void testMultipleDeclarationError2() { test("goog.provide('foo.bar');" + "if (true) { var foo = {}; foo.bar = 0 } else { foo.bar = 1 }", "var foo = {};" + "if (true) {" + " var foo = {}; foo.bar = 0" + "} else {" + " foo.bar = 1" + "}"); } public void testMultipleDeclarationError3() { test("goog.provide('foo.bar');" + "if (true) { foo.bar = 0 } else { var foo = {}; foo.bar = 1 }", "var foo = {};" + "if (true) {" + " foo.bar = 0" + "} else {" + " var foo = {}; foo.bar = 1" + "}"); } public void testProvideAfterDeclarationError() { test("var x = 42; goog.provide('x');", "var x = 42; var x = {}"); } public void testProvideErrorCases() { test("goog.provide();", "", NULL_ARGUMENT_ERROR); test("goog.provide(5);", "", INVALID_ARGUMENT_ERROR); test("goog.provide([]);", "", INVALID_ARGUMENT_ERROR); test("goog.provide({});", "", INVALID_ARGUMENT_ERROR); test("goog.provide('foo', 'bar');", "", TOO_MANY_ARGUMENTS_ERROR); test("goog.provide('foo'); goog.provide('foo');", "", DUPLICATE_NAMESPACE_ERROR); test("goog.provide('foo.bar'); goog.provide('foo'); goog.provide('foo');", "", DUPLICATE_NAMESPACE_ERROR); } public void testRemovalOfRequires() { test("goog.provide('foo'); goog.require('foo');", "var foo={};"); test("goog.provide('foo.bar'); goog.require('foo.bar');", "var foo={}; foo.bar={};"); test("goog.provide('foo.bar.baz'); goog.require('foo.bar.baz');", "var foo={}; foo.bar={}; foo.bar.baz={};"); test("goog.provide('foo'); var x = 3; goog.require('foo'); something();", "var foo={}; var x = 3; something();"); testSame("foo.require('foo.bar');"); } public void testRequireErrorCases() { test("goog.require();", "", NULL_ARGUMENT_ERROR); test("goog.require(5);", "", INVALID_ARGUMENT_ERROR); test("goog.require([]);", "", INVALID_ARGUMENT_ERROR); test("goog.require({});", "", INVALID_ARGUMENT_ERROR); } public void testLateProvides() { test("goog.require('foo'); goog.provide('foo');", "var foo={};", LATE_PROVIDE_ERROR); test("goog.require('foo.bar'); goog.provide('foo.bar');", "var foo={}; foo.bar={};", LATE_PROVIDE_ERROR); test("goog.provide('foo.bar'); goog.require('foo'); goog.provide('foo');", "var foo={}; foo.bar={};", LATE_PROVIDE_ERROR); } public void testMissingProvides() { test("goog.require('foo');", "", MISSING_PROVIDE_ERROR); test("goog.provide('foo'); goog.require('Foo');", "var foo={};", MISSING_PROVIDE_ERROR); test("goog.provide('foo'); goog.require('foo.bar');", "var foo={};", MISSING_PROVIDE_ERROR); test("goog.provide('foo'); var EXPERIMENT_FOO = true; " + "if (EXPERIMENT_FOO) {goog.require('foo.bar');}", "var foo={}; var EXPERIMENT_FOO = true; if (EXPERIMENT_FOO) {}", MISSING_PROVIDE_ERROR); } public void testNewDateGoogNowSimplification() { test("var x = new Date(goog.now());", "var x = new Date();"); testSame("var x = new Date(goog.now() + 1);"); testSame("var x = new Date(goog.now(1));"); testSame("var x = new Date(1, goog.now());"); testSame("var x = new Date(1);"); testSame("var x = new Date();"); } public void testAddDependency() { test("goog.addDependency('x.js', ['A', 'B'], []);", "0"); Compiler compiler = getLastCompiler(); assertTrue(compiler.getTypeRegistry().isForwardDeclaredType("A")); assertTrue(compiler.getTypeRegistry().isForwardDeclaredType("B")); assertFalse(compiler.getTypeRegistry().isForwardDeclaredType("C")); } public void testValidSetCssNameMapping() { test("goog.setCssNameMapping({foo:'bar',\"biz\":'baz'});", ""); CssRenamingMap map = getLastCompiler().getCssRenamingMap(); assertNotNull(map); assertEquals("bar", map.get("foo")); assertEquals("baz", map.get("biz")); } public void testSetCssNameMappingNonStringValueReturnsError() { // Make sure the argument is an object literal. test("var BAR = {foo:'bar'}; goog.setCssNameMapping(BAR);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping([]);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping(false);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping(null);", "", INVALID_ARGUMENT_ERROR); test("goog.setCssNameMapping(undefined);", "", INVALID_ARGUMENT_ERROR); // Make sure all values of the object literal are string literals. test("var BAR = 'bar'; goog.setCssNameMapping({foo:BAR});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:6});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:false});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:null});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); test("goog.setCssNameMapping({foo:undefined});", "", NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR); } public void testBadCrossModuleRequire() { test( createModuleStar( "", "goog.provide('goog.ui');", "goog.require('goog.ui');"), new String[] { "", "goog.ui = {};", "" }, null, XMODULE_REQUIRE_ERROR); } public void testGoodCrossModuleRequire1() { test( createModuleStar( "goog.provide('goog.ui');", "", "goog.require('goog.ui');"), new String[] { "goog.ui = {};", "", "", }); } public void testGoodCrossModuleRequire2() { test( createModuleStar( "", "", "goog.provide('goog.ui'); goog.require('goog.ui');"), new String[] { "", "", "goog.ui = {};", }); } // Tests providing additional code with non-overlapping var namespace. public void testSimpleAdditionalProvide() { additionalCode = "goog.provide('b.B'); b.B = {};"; test("goog.provide('a.A'); a.A = {};", "var b={};b.B={};var a={};a.A={};"); } // Same as above, but with the additional code added after the original. public void testSimpleAdditionalProvideAtEnd() { additionalEndCode = "goog.provide('b.B'); b.B = {};"; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};var b={};b.B={};"); } // Tests providing additional code with non-overlapping dotted namespace. public void testSimpleDottedAdditionalProvide() { additionalCode = "goog.provide('a.b.B'); a.b.B = {};"; test("goog.provide('c.d.D'); c.d.D = {};", "var a={};a.b={};a.b.B={};var c={};c.d={};c.d.D={};"); } // Tests providing additional code with overlapping var namespace. public void testOverlappingAdditionalProvide() { additionalCode = "goog.provide('a.B'); a.B = {};"; test("goog.provide('a.A'); a.A = {};", "var a={};a.B={};a.A={};"); } // Tests providing additional code with overlapping var namespace. public void testOverlappingAdditionalProvideAtEnd() { additionalEndCode = "goog.provide('a.B'); a.B = {};"; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};a.B={};"); } // Tests providing additional code with overlapping dotted namespace. public void testOverlappingDottedAdditionalProvide() { additionalCode = "goog.provide('a.b.B'); a.b.B = {};"; test("goog.provide('a.b.C'); a.b.C = {};", "var a={};a.b={};a.b.B={};a.b.C={};"); } // Tests that a require of additional code generates no error. public void testRequireOfAdditionalProvide() { additionalCode = "goog.provide('b.B'); b.B = {};"; test("goog.require('b.B'); goog.provide('a.A'); a.A = {};", "var b={};b.B={};var a={};a.A={};"); } // Tests that a require not in additional code generates (only) one error. public void testMissingRequireWithAdditionalProvide() { additionalCode = "goog.provide('b.B'); b.B = {};"; test("goog.require('b.C'); goog.provide('a.A'); a.A = {};", "var b={};b.B={};var a={};a.A={};", MISSING_PROVIDE_ERROR); } // Tests that a require in additional code generates no error. public void testLateRequire() { additionalEndCode = "goog.require('a.A');"; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};"); } // Tests a case where code is reordered after processing provides and then // provides are processed again. public void testReorderedProvides() { additionalCode = "a.B = {};"; // as if a.B was after a.A originally addAdditionalNamespace = true; test("goog.provide('a.A'); a.A = {};", "var a={};a.B={};a.A={};"); } // Another version of above. public void testReorderedProvides2() { additionalEndCode = "a.B = {};"; addAdditionalNamespace = true; test("goog.provide('a.A'); a.A = {};", "var a={};a.A={};a.B={};"); } // Provide a name before the definition of the class providing the // parent namespace. public void testProvideOrder1() { additionalEndCode = ""; addAdditionalNamespace = false; // TODO(johnlenz): This test confirms that the constructor (a.b) isn't // improperly removed, but this result isn't really what we want as the // reassign of a.b removes the definition of "a.b.c". test("goog.provide('a.b');" + "goog.provide('a.b.c');" + "a.b.c;" + "a.b = function(x,y) {};", "var a = {};" + "a.b = {};" + "a.b.c = {};" + "a.b.c;" + "a.b = function(x,y) {};"); } // Provide a name after the definition of the class providing the // parent namespace. public void testProvideOrder2() { additionalEndCode = ""; addAdditionalNamespace = false; // TODO(johnlenz): This test confirms that the constructor (a.b) isn't // improperly removed, but this result isn't really what we want as // namespace placeholders for a.b and a.b.c remain. test("goog.provide('a.b');" + "goog.provide('a.b.c');" + "a.b = function(x,y) {};" + "a.b.c;", "var a = {};" + "a.b = {};" + "a.b.c = {};" + "a.b = function(x,y) {};" + "a.b.c;"); } // Provide a name after the definition of the class providing the // parent namespace. public void testProvideOrder3a() { test("goog.provide('a.b');" + "a.b = function(x,y) {};" + "goog.provide('a.b.c');" + "a.b.c;", "var a = {};" + "a.b = function(x,y) {};" + "a.b.c = {};" + "a.b.c;"); } public void testProvideOrder3b() { additionalEndCode = ""; addAdditionalNamespace = false; // This tests a cleanly provided name, below a function namespace. test("goog.provide('a.b');" + "a.b = function(x,y) {};" + "goog.provide('a.b.c');" + "a.b.c;", "var a = {};" + "a.b = function(x,y) {};" + "a.b.c = {};" + "a.b.c;"); } public void testProvideOrder4a() { test("goog.provide('goog.a');" + "goog.provide('goog.a.b');" + "if (x) {" + " goog.a.b = 1;" + "} else {" + " goog.a.b = 2;" + "}", "goog.a={};" + "if(x)" + " goog.a.b=1;" + "else" + " goog.a.b=2;"); } public void testProvideOrder4b() { additionalEndCode = ""; addAdditionalNamespace = false; // This tests a cleanly provided name, below a namespace. test("goog.provide('goog.a');" + "goog.provide('goog.a.b');" + "if (x) {" + " goog.a.b = 1;" + "} else {" + " goog.a.b = 2;" + "}", "goog.a={};" + "if(x)" + " goog.a.b=1;" + "else" + " goog.a.b=2;"); } public void testInvalidProvide() { test("goog.provide('a.class');", null, INVALID_PROVIDE_ERROR); } private static final String METHOD_FORMAT = "function Foo() {} Foo.prototype.method = function() { %s };"; private static final String FOO_INHERITS = "goog.inherits(Foo, BaseFoo);"; public void testInvalidBase1() { test("goog.base(this, 'method');", null, BASE_CLASS_ERROR); } public void testInvalidBase2() { test("function Foo() {}" + "Foo.method = function() {" + " goog.base(this, 'method');" + "};", null, BASE_CLASS_ERROR); } public void testInvalidBase3() { test(String.format(METHOD_FORMAT, "goog.base();"), null, BASE_CLASS_ERROR); } public void testInvalidBase4() { test(String.format(METHOD_FORMAT, "goog.base(this, 'bar');"), null, BASE_CLASS_ERROR); } public void testInvalidBase5() { test(String.format(METHOD_FORMAT, "goog.base('foo', 'method');"), null, BASE_CLASS_ERROR); } public void testInvalidBase6() { test(String.format(METHOD_FORMAT, "goog.base.call(null, this, 'method');"), null, BASE_CLASS_ERROR); } public void testInvalidBase7() { test("function Foo() { goog.base(this); }", null, BASE_CLASS_ERROR); } public void testInvalidBase8() { test("var Foo = function() { goog.base(this); }", null, BASE_CLASS_ERROR); } public void testInvalidBase9() { test("var goog = {}; goog.Foo = function() { goog.base(this); }", null, BASE_CLASS_ERROR); } public void testValidBase1() { test(String.format(METHOD_FORMAT, "goog.base(this, 'method');"), String.format(METHOD_FORMAT, "Foo.superClass_.method.call(this)")); } public void testValidBase2() { test(String.format(METHOD_FORMAT, "goog.base(this, 'method', 1, 2);"), String.format(METHOD_FORMAT, "Foo.superClass_.method.call(this, 1, 2)")); } public void testValidBase3() { test(String.format(METHOD_FORMAT, "return goog.base(this, 'method');"), String.format(METHOD_FORMAT, "return Foo.superClass_.method.call(this)")); } public void testValidBase4() { test("function Foo() { goog.base(this, 1, 2); }" + FOO_INHERITS, "function Foo() { BaseFoo.call(this, 1, 2); } " + FOO_INHERITS); } public void testValidBase5() { test("var Foo = function() { goog.base(this, 1); };" + FOO_INHERITS, "var Foo = function() { BaseFoo.call(this, 1); }; " + FOO_INHERITS); } public void testValidBase6() { test("var goog = {}; goog.Foo = function() { goog.base(this); }; " + "goog.inherits(goog.Foo, goog.BaseFoo);", "var goog = {}; goog.Foo = function() { goog.BaseFoo.call(this); }; " + "goog.inherits(goog.Foo, goog.BaseFoo);"); } public void testImplicitAndExplicitProvide() { test("var goog = {}; " + "goog.provide('goog.foo.bar'); goog.provide('goog.foo');", "var goog = {}; goog.foo = {}; goog.foo.bar = {};"); } public void testImplicitProvideInIndependentModules() { test( createModuleStar( "", "goog.provide('apps.A');", "goog.provide('apps.B');"), new String[] { "var apps = {};", "apps.A = {};", "apps.B = {};", }); } public void testImplicitProvideInIndependentModules2() { test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.A');", "goog.provide('apps.foo.B');"), new String[] { "var apps = {}; apps.foo = {};", "apps.foo.A = {};", "apps.foo.B = {};", }); } public void testImplicitProvideInIndependentModules3() { test( createModuleStar( "var goog = {};", "goog.provide('goog.foo.A');", "goog.provide('goog.foo.B');"), new String[] { "var goog = {}; goog.foo = {};", "goog.foo.A = {};", "goog.foo.B = {};", }); } public void testProvideInIndependentModules1() { test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo');", "goog.provide('apps.foo.B');"), new String[] { "var apps = {}; apps.foo = {};", "", "apps.foo.B = {};", }); } public void testProvideInIndependentModules2() { // TODO(nicksantos): Make this an error. test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo'); apps.foo = {};", "goog.provide('apps.foo.B');"), new String[] { "var apps = {};", "apps.foo = {};", "apps.foo.B = {};", }); } public void testProvideInIndependentModules2b() { // TODO(nicksantos): Make this an error. test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo'); apps.foo = function() {};", "goog.provide('apps.foo.B');"), new String[] { "var apps = {};", "apps.foo = function() {};", "apps.foo.B = {};", }); } public void testProvideInIndependentModules3() { test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.B');", "goog.provide('apps.foo'); goog.require('apps.foo');"), new String[] { "var apps = {}; apps.foo = {};", "apps.foo.B = {};", "", }); } public void testProvideInIndependentModules3b() { // TODO(nicksantos): Make this an error. test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.B');", "goog.provide('apps.foo'); apps.foo = function() {}; " + "goog.require('apps.foo');"), new String[] { "var apps = {};", "apps.foo.B = {};", "apps.foo = function() {};", }); } public void testProvideInIndependentModules4() { // Regression test for bug 261: // http://code.google.com/p/closure-compiler/issues/detail?id=261 test( createModuleStar( "goog.provide('apps');", "goog.provide('apps.foo.bar.B');", "goog.provide('apps.foo.bar.C');"), new String[] { "var apps = {};apps.foo = {};apps.foo.bar = {}", "apps.foo.bar.B = {};", "apps.foo.bar.C = {};", }); } public void testRequireOfBaseGoog() { test("goog.require('goog');", "", MISSING_PROVIDE_ERROR); } }
public void testSkipValue_filledJsonObject() throws IOException { JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonArray.add('c'); jsonArray.add("text"); jsonObject.add("a", jsonArray); jsonObject.addProperty("b", true); jsonObject.addProperty("i", 1); jsonObject.add("n", JsonNull.INSTANCE); JsonObject jsonObject2 = new JsonObject(); jsonObject2.addProperty("n", 2L); jsonObject.add("o", jsonObject2); jsonObject.addProperty("s", "text"); JsonTreeReader in = new JsonTreeReader(jsonObject); in.skipValue(); assertEquals(JsonToken.END_DOCUMENT, in.peek()); }
com.google.gson.internal.bind.JsonTreeReaderTest::testSkipValue_filledJsonObject
gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java
48
gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java
testSkipValue_filledJsonObject
/* * Copyright (C) 2017 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.internal.bind; import com.google.gson.JsonArray; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.stream.JsonToken; import java.io.IOException; import junit.framework.TestCase; @SuppressWarnings("resource") public class JsonTreeReaderTest extends TestCase { public void testSkipValue_emptyJsonObject() throws IOException { JsonTreeReader in = new JsonTreeReader(new JsonObject()); in.skipValue(); assertEquals(JsonToken.END_DOCUMENT, in.peek()); } public void testSkipValue_filledJsonObject() throws IOException { JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonArray.add('c'); jsonArray.add("text"); jsonObject.add("a", jsonArray); jsonObject.addProperty("b", true); jsonObject.addProperty("i", 1); jsonObject.add("n", JsonNull.INSTANCE); JsonObject jsonObject2 = new JsonObject(); jsonObject2.addProperty("n", 2L); jsonObject.add("o", jsonObject2); jsonObject.addProperty("s", "text"); JsonTreeReader in = new JsonTreeReader(jsonObject); in.skipValue(); assertEquals(JsonToken.END_DOCUMENT, in.peek()); } }
// You are a professional Java test case writer, please create a test case named `testSkipValue_filledJsonObject` for the issue `Gson-1013`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-1013 // // ## Issue-Title: // Bug when skipping a value while using the JsonTreeReader // // ## Issue-Description: // When using a `JsonReader` to read a JSON object, `skipValue()` skips the structure successfully. // // // // ``` // @Test // public void testSkipValue\_JsonReader() throws IOException { // try (JsonReader in = new JsonReader(new StringReader("{}"))) { // in.skipValue(); // } // } // ``` // // But when using a `JsonTreeReader` to read a JSON object, `skipValue()` throws a `ArrayIndexOutOfBoundsException`. // // // // ``` // @Test // public void testSkipValue\_JsonTreeReader() throws IOException { // try (JsonTreeReader in = new JsonTreeReader(new JsonObject())) { // in.skipValue(); // } // } // ``` // // Stacktrace // // // // ``` // java.lang.ArrayIndexOutOfBoundsException: -1 // at com.google.gson.internal.bind.JsonTreeReader.skipValue(JsonTreeReader.java:262) // // ``` // // The method `popStack()` is being called on line 261 with a `stackSize` of `1` and afterwards the `stackSize` is `0` and the call on line 262 must result in an `ArrayIndexOutOfBoundsException`. // // // // public void testSkipValue_filledJsonObject() throws IOException {
48
12
32
gson/src/test/java/com/google/gson/internal/bind/JsonTreeReaderTest.java
gson/src/test/java
```markdown ## Issue-ID: Gson-1013 ## Issue-Title: Bug when skipping a value while using the JsonTreeReader ## Issue-Description: When using a `JsonReader` to read a JSON object, `skipValue()` skips the structure successfully. ``` @Test public void testSkipValue\_JsonReader() throws IOException { try (JsonReader in = new JsonReader(new StringReader("{}"))) { in.skipValue(); } } ``` But when using a `JsonTreeReader` to read a JSON object, `skipValue()` throws a `ArrayIndexOutOfBoundsException`. ``` @Test public void testSkipValue\_JsonTreeReader() throws IOException { try (JsonTreeReader in = new JsonTreeReader(new JsonObject())) { in.skipValue(); } } ``` Stacktrace ``` java.lang.ArrayIndexOutOfBoundsException: -1 at com.google.gson.internal.bind.JsonTreeReader.skipValue(JsonTreeReader.java:262) ``` The method `popStack()` is being called on line 261 with a `stackSize` of `1` and afterwards the `stackSize` is `0` and the call on line 262 must result in an `ArrayIndexOutOfBoundsException`. ``` You are a professional Java test case writer, please create a test case named `testSkipValue_filledJsonObject` for the issue `Gson-1013`, utilizing the provided issue report information and the following function signature. ```java public void testSkipValue_filledJsonObject() throws IOException { ```
32
[ "com.google.gson.internal.bind.JsonTreeReader" ]
e54a927b796bc95f7b02513e3771b7a1b3d536268635571acffe0c8542bf8032
public void testSkipValue_filledJsonObject() throws IOException
// You are a professional Java test case writer, please create a test case named `testSkipValue_filledJsonObject` for the issue `Gson-1013`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Gson-1013 // // ## Issue-Title: // Bug when skipping a value while using the JsonTreeReader // // ## Issue-Description: // When using a `JsonReader` to read a JSON object, `skipValue()` skips the structure successfully. // // // // ``` // @Test // public void testSkipValue\_JsonReader() throws IOException { // try (JsonReader in = new JsonReader(new StringReader("{}"))) { // in.skipValue(); // } // } // ``` // // But when using a `JsonTreeReader` to read a JSON object, `skipValue()` throws a `ArrayIndexOutOfBoundsException`. // // // // ``` // @Test // public void testSkipValue\_JsonTreeReader() throws IOException { // try (JsonTreeReader in = new JsonTreeReader(new JsonObject())) { // in.skipValue(); // } // } // ``` // // Stacktrace // // // // ``` // java.lang.ArrayIndexOutOfBoundsException: -1 // at com.google.gson.internal.bind.JsonTreeReader.skipValue(JsonTreeReader.java:262) // // ``` // // The method `popStack()` is being called on line 261 with a `stackSize` of `1` and afterwards the `stackSize` is `0` and the call on line 262 must result in an `ArrayIndexOutOfBoundsException`. // // // //
Gson
/* * Copyright (C) 2017 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.internal.bind; import com.google.gson.JsonArray; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.stream.JsonToken; import java.io.IOException; import junit.framework.TestCase; @SuppressWarnings("resource") public class JsonTreeReaderTest extends TestCase { public void testSkipValue_emptyJsonObject() throws IOException { JsonTreeReader in = new JsonTreeReader(new JsonObject()); in.skipValue(); assertEquals(JsonToken.END_DOCUMENT, in.peek()); } public void testSkipValue_filledJsonObject() throws IOException { JsonObject jsonObject = new JsonObject(); JsonArray jsonArray = new JsonArray(); jsonArray.add('c'); jsonArray.add("text"); jsonObject.add("a", jsonArray); jsonObject.addProperty("b", true); jsonObject.addProperty("i", 1); jsonObject.add("n", JsonNull.INSTANCE); JsonObject jsonObject2 = new JsonObject(); jsonObject2.addProperty("n", 2L); jsonObject.add("o", jsonObject2); jsonObject.addProperty("s", "text"); JsonTreeReader in = new JsonTreeReader(jsonObject); in.skipValue(); assertEquals(JsonToken.END_DOCUMENT, in.peek()); } }
public void testTruncateLang59() throws Exception { // Set TimeZone to Mountain Time TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT"); TimeZone.setDefault(MST_MDT); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); format.setTimeZone(MST_MDT); Date oct31_01MDT = new Date(1099206000000L); Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT)); assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT)); assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT)); assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT)); assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT)); // ------- Demonstrate Problem ------- Calendar gval = Calendar.getInstance(); gval.setTime(new Date(oct31_01MDT.getTime())); gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L); // ---------- Test Truncate ---------- assertEquals("Truncate Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Truncate Calendar.SECOND", oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Truncate Calendar.MINUTE", oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Truncate Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Truncate Calendar.HOUR", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Truncate Calendar.DATE", oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE)); // ---------- Test Round (down) ---------- assertEquals("Round Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Round Calendar.SECOND", oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Round Calendar.MINUTE", oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Round Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Round Calendar.HOUR", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Round Calendar.DATE", oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE)); // restore default time zone TimeZone.setDefault(defaultZone); }
org.apache.commons.lang.time.DateUtilsTest::testTruncateLang59
src/test/org/apache/commons/lang/time/DateUtilsTest.java
963
src/test/org/apache/commons/lang/time/DateUtilsTest.java
testTruncateLang59
/* * Copyright 2002-2005 The Apache Software Foundation. * * 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 org.apache.commons.lang.time; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.lang.SystemUtils; /** * Unit tests {@link org.apache.commons.lang.time.DateUtils}. * * @author <a href="mailto:[email protected]">Serge Knystautas</a> * @author <a href="mailto:[email protected]">Steven Caswell</a> */ public class DateUtilsTest extends TestCase { private static final long MILLIS_TEST; static { GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2); cal.set(Calendar.MILLISECOND, 1); MILLIS_TEST = cal.getTime().getTime(); } DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; public DateUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(DateUtilsTest.class); suite.setName("DateUtils Tests"); return suite; } protected void setUp() throws Exception { super.setUp(); dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH); dateAmPm1 = dateTimeParser.parse("February 3, 2002 01:10:00.000"); dateAmPm2 = dateTimeParser.parse("February 3, 2002 11:10:00.000"); dateAmPm3 = dateTimeParser.parse("February 3, 2002 13:10:00.000"); dateAmPm4 = dateTimeParser.parse("February 3, 2002 19:10:00.000"); date0 = dateTimeParser.parse("February 3, 2002 12:34:56.789"); date1 = dateTimeParser.parse("February 12, 2002 12:34:56.789"); date2 = dateTimeParser.parse("November 18, 2001 1:23:11.321"); defaultZone = TimeZone.getDefault(); zone = TimeZone.getTimeZone("MET"); TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); date3 = dateTimeParser.parse("March 30, 2003 05:30:45.000"); date4 = dateTimeParser.parse("March 30, 2003 01:10:00.000"); date5 = dateTimeParser.parse("March 30, 2003 01:40:00.000"); date6 = dateTimeParser.parse("March 30, 2003 02:10:00.000"); date7 = dateTimeParser.parse("March 30, 2003 02:40:00.000"); date8 = dateTimeParser.parse("October 26, 2003 05:30:45.000"); dateTimeParser.setTimeZone(defaultZone); TimeZone.setDefault(defaultZone); calAmPm1 = Calendar.getInstance(); calAmPm1.setTime(dateAmPm1); calAmPm2 = Calendar.getInstance(); calAmPm2.setTime(dateAmPm2); calAmPm3 = Calendar.getInstance(); calAmPm3.setTime(dateAmPm3); calAmPm4 = Calendar.getInstance(); calAmPm4.setTime(dateAmPm4); cal1 = Calendar.getInstance(); cal1.setTime(date1); cal2 = Calendar.getInstance(); cal2.setTime(date2); TimeZone.setDefault(zone); cal3 = Calendar.getInstance(); cal3.setTime(date3); cal4 = Calendar.getInstance(); cal4.setTime(date4); cal5 = Calendar.getInstance(); cal5.setTime(date5); cal6 = Calendar.getInstance(); cal6.setTime(date6); cal7 = Calendar.getInstance(); cal7.setTime(date7); cal8 = Calendar.getInstance(); cal8.setTime(date8); TimeZone.setDefault(defaultZone); } protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new DateUtils()); Constructor[] cons = DateUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(DateUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIsSameDay_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); try { DateUtils.isSameDay((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameDay_Cal() { GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45); GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.DAY_OF_YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); cal1.add(Calendar.DAY_OF_YEAR, 1); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); try { DateUtils.isSameDay((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); try { DateUtils.isSameInstant((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(false, DateUtils.isSameInstant(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(true, DateUtils.isSameInstant(cal1, cal2)); try { DateUtils.isSameInstant((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameLocalTime_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(true, DateUtils.isSameLocalTime(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(false, DateUtils.isSameLocalTime(cal1, cal2)); try { DateUtils.isSameLocalTime((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseDate() throws Exception { GregorianCalendar cal = new GregorianCalendar(1972, 11, 3); String dateStr = "1972-12-03"; String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "1972-338"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "19721203"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { DateUtils.parseDate("PURPLE", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate("197212AB", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate(null, parsers); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testAddYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addYears(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2001, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 1999, 6, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMonths() {} // Defects4J: flaky method // public void testAddMonths() throws Exception { // Date base = new Date(MILLIS_TEST); // Date result = DateUtils.addMonths(base, 0); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 1); // // result = DateUtils.addMonths(base, 1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 7, 5, 4, 3, 2, 1); // // result = DateUtils.addMonths(base, -1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 5, 5, 4, 3, 2, 1); // } //----------------------------------------------------------------------- public void testAddWeeks() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addWeeks(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addWeeks(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 12, 4, 3, 2, 1); result = DateUtils.addWeeks(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // july assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june } //----------------------------------------------------------------------- public void testAddDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addDays(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 6, 4, 3, 2, 1); result = DateUtils.addDays(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 4, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addHours(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 5, 3, 2, 1); result = DateUtils.addHours(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 3, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMinutes(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 4, 2, 1); result = DateUtils.addMinutes(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 2, 2, 1); } //----------------------------------------------------------------------- public void testAddSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addSeconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 3, 1); result = DateUtils.addSeconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 1, 1); } //----------------------------------------------------------------------- public void testAddMilliseconds() {} // Defects4J: flaky method // public void testAddMilliseconds() throws Exception { // Date base = new Date(MILLIS_TEST); // Date result = DateUtils.addMilliseconds(base, 0); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 1); // // result = DateUtils.addMilliseconds(base, 1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 2); // // result = DateUtils.addMilliseconds(base, -1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 0); // } //----------------------------------------------------------------------- public void testAddByField() {} // Defects4J: flaky method // public void testAddByField() throws Exception { // Date base = new Date(MILLIS_TEST); // Date result = DateUtils.add(base, Calendar.YEAR, 0); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 1); // // result = DateUtils.add(base, Calendar.YEAR, 1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2001, 6, 5, 4, 3, 2, 1); // // result = DateUtils.add(base, Calendar.YEAR, -1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 1999, 6, 5, 4, 3, 2, 1); // } //----------------------------------------------------------------------- private void assertDate(Date date, int year, int month, int day, int hour, int min, int sec, int mil) throws Exception { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); assertEquals(year, cal.get(Calendar.YEAR)); assertEquals(month, cal.get(Calendar.MONTH)); assertEquals(day, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(min, cal.get(Calendar.MINUTE)); assertEquals(sec, cal.get(Calendar.SECOND)); assertEquals(mil, cal.get(Calendar.MILLISECOND)); } //----------------------------------------------------------------------- /** * Tests various values with the round method */ public void testRound() throws Exception { // tests for public static Date round(Date date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round(date2, Calendar.MONTH)); assertEquals("round semimonth-0 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date0, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round(date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round(date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round(date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round(date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round(date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round(date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round(date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round(date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round(date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 4, 2002 12:00:00.000"), DateUtils.round(dateAmPm4, Calendar.AM_PM)); // tests for public static Date round(Object date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round((Object) date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round((Object) date2, Calendar.MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round((Object) date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round((Object) date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round((Object) date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round((Object) date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round((Object) date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round((Object) date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) date2, Calendar.SECOND)); assertEquals("round calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) cal1, Calendar.SECOND)); assertEquals("round calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 4, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm4, Calendar.AM_PM)); try { DateUtils.round((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.round(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 4, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm4, Calendar.AM_PM)); // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test rounding across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round(date4, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round(date7, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("Some date rounding tests not run since the current version is " + SystemUtils.JAVA_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); } /** * Tests various values with the trunc method */ public void testTruncate() throws Exception { // tests public static Date truncate(Date date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate(date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate(date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate(date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate(date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate(date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate(date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate(date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate(date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate(date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate(date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate(date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm4, Calendar.AM_PM)); // tests public static Date truncate(Object date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate((Object) date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate((Object) date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate((Object) date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate((Object) date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate((Object) date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate((Object) date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate((Object) date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate((Object) date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate((Object) date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("truncate calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) cal1, Calendar.SECOND)); assertEquals("truncate calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.truncate((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test truncate across beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate(date3, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate((Object) cal3, Calendar.DATE)); // Test truncate across end of daylight saving time assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate(date8, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate((Object) cal8, Calendar.DATE)); TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.truncate(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests for LANG-59 * * see http://issues.apache.org/jira/browse/LANG-59 */ public void testTruncateLang59() throws Exception { // Set TimeZone to Mountain Time TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT"); TimeZone.setDefault(MST_MDT); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); format.setTimeZone(MST_MDT); Date oct31_01MDT = new Date(1099206000000L); Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT)); assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT)); assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT)); assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT)); assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT)); // ------- Demonstrate Problem ------- Calendar gval = Calendar.getInstance(); gval.setTime(new Date(oct31_01MDT.getTime())); gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L); // ---------- Test Truncate ---------- assertEquals("Truncate Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Truncate Calendar.SECOND", oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Truncate Calendar.MINUTE", oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Truncate Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Truncate Calendar.HOUR", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Truncate Calendar.DATE", oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE)); // ---------- Test Round (down) ---------- assertEquals("Round Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Round Calendar.SECOND", oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Round Calendar.MINUTE", oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Round Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Round Calendar.HOUR", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Round Calendar.DATE", oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE)); // restore default time zone TimeZone.setDefault(defaultZone); } /** * Tests the iterator exceptions */ public void testIteratorEx() throws Exception { try { DateUtils.iterator(Calendar.getInstance(), -9999); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER); fail(); } catch (ClassCastException ex) {} } /** * Tests the calendar iterator for week ranges */ public void testWeekIterator() throws Exception { Calendar now = Calendar.getInstance(); for (int i = 0; i< 7; i++) { Calendar today = DateUtils.truncate(now, Calendar.DATE); Calendar sunday = DateUtils.truncate(now, Calendar.DATE); sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK)); Calendar monday = DateUtils.truncate(now, Calendar.DATE); if (monday.get(Calendar.DAY_OF_WEEK) == 1) { //This is sunday... roll back 6 days monday.add(Calendar.DATE, -6); } else { monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK)); } Calendar centered = DateUtils.truncate(now, Calendar.DATE); centered.add(Calendar.DATE, -3); Iterator it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_SUNDAY); assertWeekIterator(it, sunday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_MONDAY); assertWeekIterator(it, monday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_RELATIVE); assertWeekIterator(it, today); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); try { it.next(); fail(); } catch (NoSuchElementException ex) {} it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); it.next(); try { it.remove(); } catch( UnsupportedOperationException ex) {} now.add(Calendar.DATE,1); } } /** * Tests the calendar iterator for month-based ranges */ public void testMonthIterator() throws Exception { Iterator it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("January 27, 2002"), dateParser.parse("March 2, 2002")); it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("January 28, 2002"), dateParser.parse("March 3, 2002")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("October 28, 2001"), dateParser.parse("December 1, 2001")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("October 29, 2001"), dateParser.parse("December 2, 2001")); } /** * This checks that this is a 7 element iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other. */ private static void assertWeekIterator(Iterator it, Calendar start) { Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, 6); assertWeekIterator(it, start, end); } /** * Convenience method for when working with Date objects */ private static void assertWeekIterator(Iterator it, Date start, Date end) { Calendar calStart = Calendar.getInstance(); calStart.setTime(start); Calendar calEnd = Calendar.getInstance(); calEnd.setTime(end); assertWeekIterator(it, calStart, calEnd); } /** * This checks that this is a 7 divisble iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other * (in addition to the proper start and stop dates) */ private static void assertWeekIterator(Iterator it, Calendar start, Calendar end) { Calendar cal = (Calendar) it.next(); assertEquals("", start, cal, 0); Calendar last = null; int count = 1; while (it.hasNext()) { //Check this is just a date (no time component) assertEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0); last = cal; cal = (Calendar) it.next(); count++; //Check that this is one day more than the last date last.add(Calendar.DATE, 1); assertEquals("", last, cal, 0); } if (count % 7 != 0) { throw new AssertionFailedError("There were " + count + " days in this iterator"); } assertEquals("", end, cal, 0); } /** * Used to check that Calendar objects are close enough * delta is in milliseconds */ private static void assertEquals(String message, Calendar cal1, Calendar cal2, long delta) { if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) { throw new AssertionFailedError( message + " expected " + cal1.getTime() + " but got " + cal2.getTime()); } } void warn(String msg) { System.err.println(msg); } }
// You are a professional Java test case writer, please create a test case named `testTruncateLang59` for the issue `Lang-LANG-59`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-59 // // ## Issue-Title: // [lang] DateUtils.truncate method is buggy when dealing with DST switching hours // // ## Issue-Description: // // Try to truncate 2004-10-31 01:00:00 MDT by hour and you'll actually get 2004-10- // // 31 01:00:00 MST, which is one hour after the input hour. // // // // truncate 2004-10-31 01:00:00 MDT // // Date oct31\_01MDT = new Date(1099206000000L); // // Date result = DateUtils.truncate(oct31\_01MDT, Calendar.HOUR\_OF\_DAY); // // assertEquals(oct31\_01MDT, result); // // // // // public void testTruncateLang59() throws Exception {
963
/** * Tests for LANG-59 * * see http://issues.apache.org/jira/browse/LANG-59 */
65
895
src/test/org/apache/commons/lang/time/DateUtilsTest.java
src/test
```markdown ## Issue-ID: Lang-LANG-59 ## Issue-Title: [lang] DateUtils.truncate method is buggy when dealing with DST switching hours ## Issue-Description: Try to truncate 2004-10-31 01:00:00 MDT by hour and you'll actually get 2004-10- 31 01:00:00 MST, which is one hour after the input hour. // truncate 2004-10-31 01:00:00 MDT Date oct31\_01MDT = new Date(1099206000000L); Date result = DateUtils.truncate(oct31\_01MDT, Calendar.HOUR\_OF\_DAY); assertEquals(oct31\_01MDT, result); ``` You are a professional Java test case writer, please create a test case named `testTruncateLang59` for the issue `Lang-LANG-59`, utilizing the provided issue report information and the following function signature. ```java public void testTruncateLang59() throws Exception { ```
895
[ "org.apache.commons.lang.time.DateUtils" ]
e5a9ab2e170424f60b29f61e7d3f24a3301cd3bd8b01d4e6f7755dedebd60ef6
public void testTruncateLang59() throws Exception
// You are a professional Java test case writer, please create a test case named `testTruncateLang59` for the issue `Lang-LANG-59`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Lang-LANG-59 // // ## Issue-Title: // [lang] DateUtils.truncate method is buggy when dealing with DST switching hours // // ## Issue-Description: // // Try to truncate 2004-10-31 01:00:00 MDT by hour and you'll actually get 2004-10- // // 31 01:00:00 MST, which is one hour after the input hour. // // // // truncate 2004-10-31 01:00:00 MDT // // Date oct31\_01MDT = new Date(1099206000000L); // // Date result = DateUtils.truncate(oct31\_01MDT, Calendar.HOUR\_OF\_DAY); // // assertEquals(oct31\_01MDT, result); // // // // //
Lang
/* * Copyright 2002-2005 The Apache Software Foundation. * * 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 org.apache.commons.lang.time; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.lang.SystemUtils; /** * Unit tests {@link org.apache.commons.lang.time.DateUtils}. * * @author <a href="mailto:[email protected]">Serge Knystautas</a> * @author <a href="mailto:[email protected]">Steven Caswell</a> */ public class DateUtilsTest extends TestCase { private static final long MILLIS_TEST; static { GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2); cal.set(Calendar.MILLISECOND, 1); MILLIS_TEST = cal.getTime().getTime(); } DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; public DateUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(DateUtilsTest.class); suite.setName("DateUtils Tests"); return suite; } protected void setUp() throws Exception { super.setUp(); dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH); dateAmPm1 = dateTimeParser.parse("February 3, 2002 01:10:00.000"); dateAmPm2 = dateTimeParser.parse("February 3, 2002 11:10:00.000"); dateAmPm3 = dateTimeParser.parse("February 3, 2002 13:10:00.000"); dateAmPm4 = dateTimeParser.parse("February 3, 2002 19:10:00.000"); date0 = dateTimeParser.parse("February 3, 2002 12:34:56.789"); date1 = dateTimeParser.parse("February 12, 2002 12:34:56.789"); date2 = dateTimeParser.parse("November 18, 2001 1:23:11.321"); defaultZone = TimeZone.getDefault(); zone = TimeZone.getTimeZone("MET"); TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); date3 = dateTimeParser.parse("March 30, 2003 05:30:45.000"); date4 = dateTimeParser.parse("March 30, 2003 01:10:00.000"); date5 = dateTimeParser.parse("March 30, 2003 01:40:00.000"); date6 = dateTimeParser.parse("March 30, 2003 02:10:00.000"); date7 = dateTimeParser.parse("March 30, 2003 02:40:00.000"); date8 = dateTimeParser.parse("October 26, 2003 05:30:45.000"); dateTimeParser.setTimeZone(defaultZone); TimeZone.setDefault(defaultZone); calAmPm1 = Calendar.getInstance(); calAmPm1.setTime(dateAmPm1); calAmPm2 = Calendar.getInstance(); calAmPm2.setTime(dateAmPm2); calAmPm3 = Calendar.getInstance(); calAmPm3.setTime(dateAmPm3); calAmPm4 = Calendar.getInstance(); calAmPm4.setTime(dateAmPm4); cal1 = Calendar.getInstance(); cal1.setTime(date1); cal2 = Calendar.getInstance(); cal2.setTime(date2); TimeZone.setDefault(zone); cal3 = Calendar.getInstance(); cal3.setTime(date3); cal4 = Calendar.getInstance(); cal4.setTime(date4); cal5 = Calendar.getInstance(); cal5.setTime(date5); cal6 = Calendar.getInstance(); cal6.setTime(date6); cal7 = Calendar.getInstance(); cal7.setTime(date7); cal8 = Calendar.getInstance(); cal8.setTime(date8); TimeZone.setDefault(defaultZone); } protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new DateUtils()); Constructor[] cons = DateUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(DateUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIsSameDay_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); try { DateUtils.isSameDay((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameDay_Cal() { GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45); GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.DAY_OF_YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); cal1.add(Calendar.DAY_OF_YEAR, 1); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); try { DateUtils.isSameDay((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); try { DateUtils.isSameInstant((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(false, DateUtils.isSameInstant(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(true, DateUtils.isSameInstant(cal1, cal2)); try { DateUtils.isSameInstant((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameLocalTime_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(true, DateUtils.isSameLocalTime(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(false, DateUtils.isSameLocalTime(cal1, cal2)); try { DateUtils.isSameLocalTime((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseDate() throws Exception { GregorianCalendar cal = new GregorianCalendar(1972, 11, 3); String dateStr = "1972-12-03"; String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "1972-338"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "19721203"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { DateUtils.parseDate("PURPLE", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate("197212AB", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate(null, parsers); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testAddYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addYears(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2001, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 1999, 6, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMonths() {} // Defects4J: flaky method // public void testAddMonths() throws Exception { // Date base = new Date(MILLIS_TEST); // Date result = DateUtils.addMonths(base, 0); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 1); // // result = DateUtils.addMonths(base, 1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 7, 5, 4, 3, 2, 1); // // result = DateUtils.addMonths(base, -1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 5, 5, 4, 3, 2, 1); // } //----------------------------------------------------------------------- public void testAddWeeks() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addWeeks(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addWeeks(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 12, 4, 3, 2, 1); result = DateUtils.addWeeks(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // july assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june } //----------------------------------------------------------------------- public void testAddDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addDays(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 6, 4, 3, 2, 1); result = DateUtils.addDays(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 4, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addHours(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 5, 3, 2, 1); result = DateUtils.addHours(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 3, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMinutes(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 4, 2, 1); result = DateUtils.addMinutes(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 2, 2, 1); } //----------------------------------------------------------------------- public void testAddSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addSeconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 3, 1); result = DateUtils.addSeconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 1, 1); } //----------------------------------------------------------------------- public void testAddMilliseconds() {} // Defects4J: flaky method // public void testAddMilliseconds() throws Exception { // Date base = new Date(MILLIS_TEST); // Date result = DateUtils.addMilliseconds(base, 0); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 1); // // result = DateUtils.addMilliseconds(base, 1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 2); // // result = DateUtils.addMilliseconds(base, -1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 0); // } //----------------------------------------------------------------------- public void testAddByField() {} // Defects4J: flaky method // public void testAddByField() throws Exception { // Date base = new Date(MILLIS_TEST); // Date result = DateUtils.add(base, Calendar.YEAR, 0); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2000, 6, 5, 4, 3, 2, 1); // // result = DateUtils.add(base, Calendar.YEAR, 1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 2001, 6, 5, 4, 3, 2, 1); // // result = DateUtils.add(base, Calendar.YEAR, -1); // assertNotSame(base, result); // assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // assertDate(result, 1999, 6, 5, 4, 3, 2, 1); // } //----------------------------------------------------------------------- private void assertDate(Date date, int year, int month, int day, int hour, int min, int sec, int mil) throws Exception { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); assertEquals(year, cal.get(Calendar.YEAR)); assertEquals(month, cal.get(Calendar.MONTH)); assertEquals(day, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(min, cal.get(Calendar.MINUTE)); assertEquals(sec, cal.get(Calendar.SECOND)); assertEquals(mil, cal.get(Calendar.MILLISECOND)); } //----------------------------------------------------------------------- /** * Tests various values with the round method */ public void testRound() throws Exception { // tests for public static Date round(Date date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round(date2, Calendar.MONTH)); assertEquals("round semimonth-0 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date0, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round(date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round(date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round(date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round(date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round(date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round(date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round(date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round(date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round(date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 4, 2002 12:00:00.000"), DateUtils.round(dateAmPm4, Calendar.AM_PM)); // tests for public static Date round(Object date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round((Object) date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round((Object) date2, Calendar.MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round((Object) date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round((Object) date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round((Object) date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round((Object) date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round((Object) date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round((Object) date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) date2, Calendar.SECOND)); assertEquals("round calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) cal1, Calendar.SECOND)); assertEquals("round calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 4, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm4, Calendar.AM_PM)); try { DateUtils.round((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.round(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 4, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm4, Calendar.AM_PM)); // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test rounding across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round(date4, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round(date7, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("Some date rounding tests not run since the current version is " + SystemUtils.JAVA_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); } /** * Tests various values with the trunc method */ public void testTruncate() throws Exception { // tests public static Date truncate(Date date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate(date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate(date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate(date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate(date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate(date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate(date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate(date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate(date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate(date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate(date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate(date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm4, Calendar.AM_PM)); // tests public static Date truncate(Object date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate((Object) date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate((Object) date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate((Object) date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate((Object) date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate((Object) date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate((Object) date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate((Object) date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate((Object) date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate((Object) date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("truncate calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) cal1, Calendar.SECOND)); assertEquals("truncate calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.truncate((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test truncate across beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate(date3, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate((Object) cal3, Calendar.DATE)); // Test truncate across end of daylight saving time assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate(date8, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate((Object) cal8, Calendar.DATE)); TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.truncate(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests for LANG-59 * * see http://issues.apache.org/jira/browse/LANG-59 */ public void testTruncateLang59() throws Exception { // Set TimeZone to Mountain Time TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT"); TimeZone.setDefault(MST_MDT); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); format.setTimeZone(MST_MDT); Date oct31_01MDT = new Date(1099206000000L); Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT)); assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT)); assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT)); assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT)); assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT)); // ------- Demonstrate Problem ------- Calendar gval = Calendar.getInstance(); gval.setTime(new Date(oct31_01MDT.getTime())); gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L); // ---------- Test Truncate ---------- assertEquals("Truncate Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Truncate Calendar.SECOND", oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Truncate Calendar.MINUTE", oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Truncate Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Truncate Calendar.HOUR", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Truncate Calendar.DATE", oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE)); // ---------- Test Round (down) ---------- assertEquals("Round Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Round Calendar.SECOND", oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Round Calendar.MINUTE", oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Round Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Round Calendar.HOUR", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Round Calendar.DATE", oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE)); // restore default time zone TimeZone.setDefault(defaultZone); } /** * Tests the iterator exceptions */ public void testIteratorEx() throws Exception { try { DateUtils.iterator(Calendar.getInstance(), -9999); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER); fail(); } catch (ClassCastException ex) {} } /** * Tests the calendar iterator for week ranges */ public void testWeekIterator() throws Exception { Calendar now = Calendar.getInstance(); for (int i = 0; i< 7; i++) { Calendar today = DateUtils.truncate(now, Calendar.DATE); Calendar sunday = DateUtils.truncate(now, Calendar.DATE); sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK)); Calendar monday = DateUtils.truncate(now, Calendar.DATE); if (monday.get(Calendar.DAY_OF_WEEK) == 1) { //This is sunday... roll back 6 days monday.add(Calendar.DATE, -6); } else { monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK)); } Calendar centered = DateUtils.truncate(now, Calendar.DATE); centered.add(Calendar.DATE, -3); Iterator it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_SUNDAY); assertWeekIterator(it, sunday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_MONDAY); assertWeekIterator(it, monday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_RELATIVE); assertWeekIterator(it, today); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); try { it.next(); fail(); } catch (NoSuchElementException ex) {} it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); it.next(); try { it.remove(); } catch( UnsupportedOperationException ex) {} now.add(Calendar.DATE,1); } } /** * Tests the calendar iterator for month-based ranges */ public void testMonthIterator() throws Exception { Iterator it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("January 27, 2002"), dateParser.parse("March 2, 2002")); it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("January 28, 2002"), dateParser.parse("March 3, 2002")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("October 28, 2001"), dateParser.parse("December 1, 2001")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("October 29, 2001"), dateParser.parse("December 2, 2001")); } /** * This checks that this is a 7 element iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other. */ private static void assertWeekIterator(Iterator it, Calendar start) { Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, 6); assertWeekIterator(it, start, end); } /** * Convenience method for when working with Date objects */ private static void assertWeekIterator(Iterator it, Date start, Date end) { Calendar calStart = Calendar.getInstance(); calStart.setTime(start); Calendar calEnd = Calendar.getInstance(); calEnd.setTime(end); assertWeekIterator(it, calStart, calEnd); } /** * This checks that this is a 7 divisble iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other * (in addition to the proper start and stop dates) */ private static void assertWeekIterator(Iterator it, Calendar start, Calendar end) { Calendar cal = (Calendar) it.next(); assertEquals("", start, cal, 0); Calendar last = null; int count = 1; while (it.hasNext()) { //Check this is just a date (no time component) assertEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0); last = cal; cal = (Calendar) it.next(); count++; //Check that this is one day more than the last date last.add(Calendar.DATE, 1); assertEquals("", last, cal, 0); } if (count % 7 != 0) { throw new AssertionFailedError("There were " + count + " days in this iterator"); } assertEquals("", end, cal, 0); } /** * Used to check that Calendar objects are close enough * delta is in milliseconds */ private static void assertEquals(String message, Calendar cal1, Calendar cal2, long delta) { if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) { throw new AssertionFailedError( message + " expected " + cal1.getTime() + " but got " + cal2.getTime()); } } void warn(String msg) { System.err.println(msg); } }
@Test public void testBigDataSet() throws Exception { double[] d1 = new double[1500]; double[] d2 = new double[1500]; for (int i = 0; i < 1500; i++) { d1[i] = 2 * i; d2[i] = 2 * i + 1; } double result = testStatistic.mannWhitneyUTest(d1, d2); Assert.assertTrue(result > 0.1); }
org.apache.commons.math3.stat.inference.MannWhitneyUTestTest::testBigDataSet
src/test/java/org/apache/commons/math3/stat/inference/MannWhitneyUTestTest.java
113
src/test/java/org/apache/commons/math3/stat/inference/MannWhitneyUTestTest.java
testBigDataSet
/* * 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.stat.inference; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.junit.Assert; import org.junit.Test; /** * Test cases for the MannWhitneyUTestImpl class. * * @version $Id$ */ public class MannWhitneyUTestTest { protected MannWhitneyUTest testStatistic = new MannWhitneyUTest(); @Test public void testMannWhitneyUSimple() throws Exception { /* Target values computed using R version 2.11.1 * x <- c(19, 22, 16, 29, 24) * y <- c(20, 11, 17, 12) * wilcox.test(x, y, alternative = "two.sided", mu = 0, paired = FALSE, exact = FALSE, correct = FALSE) * W = 17, p-value = 0.08641 */ final double x[] = {19, 22, 16, 29, 24}; final double y[] = {20, 11, 17, 12}; Assert.assertEquals(17, testStatistic.mannWhitneyU(x, y), 1e-10); Assert.assertEquals(0.08641, testStatistic.mannWhitneyUTest(x, y), 1e-5); } @Test public void testMannWhitneyUInputValidation() throws Exception { /* Samples must be present, i.e. length > 0 */ try { testStatistic.mannWhitneyUTest(new double[] { }, new double[] { 1.0 }); Assert.fail("x does not contain samples (exact), NoDataException expected"); } catch (NoDataException ex) { // expected } try { testStatistic.mannWhitneyUTest(new double[] { 1.0 }, new double[] { }); Assert.fail("y does not contain samples (exact), NoDataException expected"); } catch (NoDataException ex) { // expected } /* * x and y is null */ try { testStatistic.mannWhitneyUTest(null, null); Assert.fail("x and y is null (exact), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } try { testStatistic.mannWhitneyUTest(null, null); Assert.fail("x and y is null (asymptotic), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } /* * x or y is null */ try { testStatistic.mannWhitneyUTest(null, new double[] { 1.0 }); Assert.fail("x is null (exact), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } try { testStatistic.mannWhitneyUTest(new double[] { 1.0 }, null); Assert.fail("y is null (exact), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } } @Test public void testBigDataSet() throws Exception { double[] d1 = new double[1500]; double[] d2 = new double[1500]; for (int i = 0; i < 1500; i++) { d1[i] = 2 * i; d2[i] = 2 * i + 1; } double result = testStatistic.mannWhitneyUTest(d1, d2); Assert.assertTrue(result > 0.1); } }
// You are a professional Java test case writer, please create a test case named `testBigDataSet` for the issue `Math-MATH-790`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-790 // // ## Issue-Title: // Mann-Whitney U Test Suffers From Integer Overflow With Large Data Sets // // ## Issue-Description: // // When performing a Mann-Whitney U Test on large data sets (the attached test uses two 1500 element sets), intermediate integer values used in calculateAsymptoticPValue can overflow, leading to invalid results, such as p-values of NaN, or incorrect calculations. // // // Attached is a patch, including a test, and a fix, which modifies the affected code to use doubles // // // // // @Test public void testBigDataSet() throws Exception {
113
30
103
src/test/java/org/apache/commons/math3/stat/inference/MannWhitneyUTestTest.java
src/test/java
```markdown ## Issue-ID: Math-MATH-790 ## Issue-Title: Mann-Whitney U Test Suffers From Integer Overflow With Large Data Sets ## Issue-Description: When performing a Mann-Whitney U Test on large data sets (the attached test uses two 1500 element sets), intermediate integer values used in calculateAsymptoticPValue can overflow, leading to invalid results, such as p-values of NaN, or incorrect calculations. Attached is a patch, including a test, and a fix, which modifies the affected code to use doubles ``` You are a professional Java test case writer, please create a test case named `testBigDataSet` for the issue `Math-MATH-790`, utilizing the provided issue report information and the following function signature. ```java @Test public void testBigDataSet() throws Exception { ```
103
[ "org.apache.commons.math3.stat.inference.MannWhitneyUTest" ]
e5adf127c05724e1dfb109eba2b13a8c2e99eeb6cf097ba5a3fd391d26d2a42e
@Test public void testBigDataSet() throws Exception
// You are a professional Java test case writer, please create a test case named `testBigDataSet` for the issue `Math-MATH-790`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Math-MATH-790 // // ## Issue-Title: // Mann-Whitney U Test Suffers From Integer Overflow With Large Data Sets // // ## Issue-Description: // // When performing a Mann-Whitney U Test on large data sets (the attached test uses two 1500 element sets), intermediate integer values used in calculateAsymptoticPValue can overflow, leading to invalid results, such as p-values of NaN, or incorrect calculations. // // // Attached is a patch, including a test, and a fix, which modifies the affected code to use doubles // // // // //
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.stat.inference; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.junit.Assert; import org.junit.Test; /** * Test cases for the MannWhitneyUTestImpl class. * * @version $Id$ */ public class MannWhitneyUTestTest { protected MannWhitneyUTest testStatistic = new MannWhitneyUTest(); @Test public void testMannWhitneyUSimple() throws Exception { /* Target values computed using R version 2.11.1 * x <- c(19, 22, 16, 29, 24) * y <- c(20, 11, 17, 12) * wilcox.test(x, y, alternative = "two.sided", mu = 0, paired = FALSE, exact = FALSE, correct = FALSE) * W = 17, p-value = 0.08641 */ final double x[] = {19, 22, 16, 29, 24}; final double y[] = {20, 11, 17, 12}; Assert.assertEquals(17, testStatistic.mannWhitneyU(x, y), 1e-10); Assert.assertEquals(0.08641, testStatistic.mannWhitneyUTest(x, y), 1e-5); } @Test public void testMannWhitneyUInputValidation() throws Exception { /* Samples must be present, i.e. length > 0 */ try { testStatistic.mannWhitneyUTest(new double[] { }, new double[] { 1.0 }); Assert.fail("x does not contain samples (exact), NoDataException expected"); } catch (NoDataException ex) { // expected } try { testStatistic.mannWhitneyUTest(new double[] { 1.0 }, new double[] { }); Assert.fail("y does not contain samples (exact), NoDataException expected"); } catch (NoDataException ex) { // expected } /* * x and y is null */ try { testStatistic.mannWhitneyUTest(null, null); Assert.fail("x and y is null (exact), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } try { testStatistic.mannWhitneyUTest(null, null); Assert.fail("x and y is null (asymptotic), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } /* * x or y is null */ try { testStatistic.mannWhitneyUTest(null, new double[] { 1.0 }); Assert.fail("x is null (exact), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } try { testStatistic.mannWhitneyUTest(new double[] { 1.0 }, null); Assert.fail("y is null (exact), NullArgumentException expected"); } catch (NullArgumentException ex) { // expected } } @Test public void testBigDataSet() throws Exception { double[] d1 = new double[1500]; double[] d2 = new double[1500]; for (int i = 0; i < 1500; i++) { d1[i] = 2 * i; d2[i] = 2 * i + 1; } double result = testStatistic.mannWhitneyUTest(d1, d2); Assert.assertTrue(result > 0.1); } }
@Test public void sameHeadersCombineWithComma() { Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> values = new ArrayList<String>(); values.add("no-cache"); values.add("no-store"); headers.put("Cache-Control", values); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals("no-cache, no-store", res.header("Cache-Control")); }
org.jsoup.helper.HttpConnectionTest::sameHeadersCombineWithComma
src/test/java/org/jsoup/helper/HttpConnectionTest.java
63
src/test/java/org/jsoup/helper/HttpConnectionTest.java
sameHeadersCombineWithComma
package org.jsoup.helper; import static org.junit.Assert.*; import org.jsoup.integration.ParseTest; import org.junit.Test; import org.jsoup.Connection; import java.io.IOException; import java.util.*; import java.net.URL; import java.net.MalformedURLException; public class HttpConnectionTest { /* most actual network http connection tests are in integration */ @Test(expected=IllegalArgumentException.class) public void throwsExceptionOnParseWithoutExecute() throws IOException { Connection con = HttpConnection.connect("http://example.com"); con.response().parse(); } @Test(expected=IllegalArgumentException.class) public void throwsExceptionOnBodyWithoutExecute() throws IOException { Connection con = HttpConnection.connect("http://example.com"); con.response().body(); } @Test(expected=IllegalArgumentException.class) public void throwsExceptionOnBodyAsBytesWithoutExecute() throws IOException { Connection con = HttpConnection.connect("http://example.com"); con.response().bodyAsBytes(); } @Test public void caseInsensitiveHeaders() { Connection.Response res = new HttpConnection.Response(); Map<String, String> headers = res.headers(); headers.put("Accept-Encoding", "gzip"); headers.put("content-type", "text/html"); headers.put("refErrer", "http://example.com"); assertTrue(res.hasHeader("Accept-Encoding")); assertTrue(res.hasHeader("accept-encoding")); assertTrue(res.hasHeader("accept-Encoding")); assertEquals("gzip", res.header("accept-Encoding")); assertEquals("text/html", res.header("Content-Type")); assertEquals("http://example.com", res.header("Referrer")); res.removeHeader("Content-Type"); assertFalse(res.hasHeader("content-type")); res.header("accept-encoding", "deflate"); assertEquals("deflate", res.header("Accept-Encoding")); assertEquals("deflate", res.header("accept-Encoding")); } @Test public void sameHeadersCombineWithComma() { Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> values = new ArrayList<String>(); values.add("no-cache"); values.add("no-store"); headers.put("Cache-Control", values); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals("no-cache, no-store", res.header("Cache-Control")); } @Test public void ignoresEmptySetCookies() { // prep http response header map Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Set-Cookie", Collections.<String>emptyList()); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals(0, res.cookies().size()); } @Test public void ignoresEmptyCookieNameAndVals() { // prep http response header map Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> cookieStrings = new ArrayList<String>(); cookieStrings.add(null); cookieStrings.add(""); cookieStrings.add("one"); cookieStrings.add("two="); cookieStrings.add("three=;"); cookieStrings.add("four=data; Domain=.example.com; Path=/"); headers.put("Set-Cookie", cookieStrings); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals(4, res.cookies().size()); assertEquals("", res.cookie("one")); assertEquals("", res.cookie("two")); assertEquals("", res.cookie("three")); assertEquals("data", res.cookie("four")); } @Test public void connectWithUrl() throws MalformedURLException { Connection con = HttpConnection.connect(new URL("http://example.com")); assertEquals("http://example.com", con.request().url().toExternalForm()); } @Test(expected=IllegalArgumentException.class) public void throwsOnMalformedUrl() { Connection con = HttpConnection.connect("bzzt"); } @Test public void userAgent() { Connection con = HttpConnection.connect("http://example.com/"); con.userAgent("Mozilla"); assertEquals("Mozilla", con.request().header("User-Agent")); } @Test public void timeout() { Connection con = HttpConnection.connect("http://example.com/"); con.timeout(1000); assertEquals(1000, con.request().timeout()); } @Test public void referrer() { Connection con = HttpConnection.connect("http://example.com/"); con.referrer("http://foo.com"); assertEquals("http://foo.com", con.request().header("Referer")); } @Test public void method() { Connection con = HttpConnection.connect("http://example.com/"); assertEquals(Connection.Method.GET, con.request().method()); con.method(Connection.Method.POST); assertEquals(Connection.Method.POST, con.request().method()); } @Test(expected=IllegalArgumentException.class) public void throwsOnOdddData() { Connection con = HttpConnection.connect("http://example.com/"); con.data("Name", "val", "what"); } @Test public void data() { Connection con = HttpConnection.connect("http://example.com/"); con.data("Name", "Val", "Foo", "bar"); Collection<Connection.KeyVal> values = con.request().data(); Object[] data = values.toArray(); Connection.KeyVal one = (Connection.KeyVal) data[0]; Connection.KeyVal two = (Connection.KeyVal) data[1]; assertEquals("Name", one.key()); assertEquals("Val", one.value()); assertEquals("Foo", two.key()); assertEquals("bar", two.value()); } @Test public void cookie() { Connection con = HttpConnection.connect("http://example.com/"); con.cookie("Name", "Val"); assertEquals("Val", con.request().cookie("Name")); } @Test public void inputStream() { Connection.KeyVal kv = HttpConnection.KeyVal.create("file", "thumb.jpg", ParseTest.inputStreamFrom("Check")); assertEquals("file", kv.key()); assertEquals("thumb.jpg", kv.value()); assertTrue(kv.hasInputStream()); kv = HttpConnection.KeyVal.create("one", "two"); assertEquals("one", kv.key()); assertEquals("two", kv.value()); assertFalse(kv.hasInputStream()); } }
// You are a professional Java test case writer, please create a test case named `sameHeadersCombineWithComma` for the issue `Jsoup-618`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-618 // // ## Issue-Title: // A small bug for duplicate tuple in response header // // ## Issue-Description: // for response headers have duplicate tuple, // // in this case // // X-Powered-By:PHP/5.2.8 // // X-Powered-By:ASP.NET // // // Jsoup can only get the second one // // if I run header(“X-powered-by”) // // I got Asp.NET // // // URL:<http://01pt.com/> // // // Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0 // // Content-Encoding:gzip // // Content-Length:16224 // // Content-Type:text/html;charset=gb2312 // // Date:Thu, 27 Aug 2015 09:22:40 GMT // // Expires:Thu, 19 Nov 1981 08:52:00 GMT // // Pragma:no-cache // // Server:Microsoft-IIS/7.5 // // Vary:Accept-Encoding // // X-Powered-By:PHP/5.2.8 // // X-Powered-By:ASP.NET // // // The bug is because // // if (!values.isEmpty()) header(name, values.get(0)); // // // I change it to // // if (!values.isEmpty()) { // // String val = ""; // // for(String str: values) { // // val = val.concat(str).concat(" "); // // // // ``` // } // header(name, val); // } // // ``` // // then I am able to get “PHP/5.2.8 ASP.NET” when I run header(“X-powered-by”) // // // void processResponseHeaders(Map<String, List> resHeaders) { // // for (Map.Entry<String, List> entry : resHeaders.entrySet()) { // // String name = entry.getKey(); // // if (name == null) // // continue; // http/1.1 line // // // // ``` // List<String> values = entry.getValue(); // if (name.equalsIgnoreCase("Set-Cookie")) { // for (String value : values) { // if (value == null) // continue; // TokenQueue cd = new TokenQueue(value); // String cookieName = cd.chompTo("=").trim(); // String cookieVal = cd.consumeTo(";").trim(); // // ignores path, date, domain, validateTLSCertificates et al. req'd? // // name not blank, value not null // if (cookieName.length() > 0) // cookie(cookieName, cookieVal); // } // } else { // only take the first instance of each header // if (!values.isEmpty()) // @Test public void sameHeadersCombineWithComma() {
63
48
54
src/test/java/org/jsoup/helper/HttpConnectionTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-618 ## Issue-Title: A small bug for duplicate tuple in response header ## Issue-Description: for response headers have duplicate tuple, in this case X-Powered-By:PHP/5.2.8 X-Powered-By:ASP.NET Jsoup can only get the second one if I run header(“X-powered-by”) I got Asp.NET URL:<http://01pt.com/> Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Content-Encoding:gzip Content-Length:16224 Content-Type:text/html;charset=gb2312 Date:Thu, 27 Aug 2015 09:22:40 GMT Expires:Thu, 19 Nov 1981 08:52:00 GMT Pragma:no-cache Server:Microsoft-IIS/7.5 Vary:Accept-Encoding X-Powered-By:PHP/5.2.8 X-Powered-By:ASP.NET The bug is because if (!values.isEmpty()) header(name, values.get(0)); I change it to if (!values.isEmpty()) { String val = ""; for(String str: values) { val = val.concat(str).concat(" "); ``` } header(name, val); } ``` then I am able to get “PHP/5.2.8 ASP.NET” when I run header(“X-powered-by”) void processResponseHeaders(Map<String, List> resHeaders) { for (Map.Entry<String, List> entry : resHeaders.entrySet()) { String name = entry.getKey(); if (name == null) continue; // http/1.1 line ``` List<String> values = entry.getValue(); if (name.equalsIgnoreCase("Set-Cookie")) { for (String value : values) { if (value == null) continue; TokenQueue cd = new TokenQueue(value); String cookieName = cd.chompTo("=").trim(); String cookieVal = cd.consumeTo(";").trim(); // ignores path, date, domain, validateTLSCertificates et al. req'd? // name not blank, value not null if (cookieName.length() > 0) cookie(cookieName, cookieVal); } } else { // only take the first instance of each header if (!values.isEmpty()) ``` You are a professional Java test case writer, please create a test case named `sameHeadersCombineWithComma` for the issue `Jsoup-618`, utilizing the provided issue report information and the following function signature. ```java @Test public void sameHeadersCombineWithComma() { ```
54
[ "org.jsoup.helper.HttpConnection" ]
e5fe1665abb51f85cbfad7c113df6114d4880f720c06ea9e28822fa403646fc6
@Test public void sameHeadersCombineWithComma()
// You are a professional Java test case writer, please create a test case named `sameHeadersCombineWithComma` for the issue `Jsoup-618`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-618 // // ## Issue-Title: // A small bug for duplicate tuple in response header // // ## Issue-Description: // for response headers have duplicate tuple, // // in this case // // X-Powered-By:PHP/5.2.8 // // X-Powered-By:ASP.NET // // // Jsoup can only get the second one // // if I run header(“X-powered-by”) // // I got Asp.NET // // // URL:<http://01pt.com/> // // // Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0 // // Content-Encoding:gzip // // Content-Length:16224 // // Content-Type:text/html;charset=gb2312 // // Date:Thu, 27 Aug 2015 09:22:40 GMT // // Expires:Thu, 19 Nov 1981 08:52:00 GMT // // Pragma:no-cache // // Server:Microsoft-IIS/7.5 // // Vary:Accept-Encoding // // X-Powered-By:PHP/5.2.8 // // X-Powered-By:ASP.NET // // // The bug is because // // if (!values.isEmpty()) header(name, values.get(0)); // // // I change it to // // if (!values.isEmpty()) { // // String val = ""; // // for(String str: values) { // // val = val.concat(str).concat(" "); // // // // ``` // } // header(name, val); // } // // ``` // // then I am able to get “PHP/5.2.8 ASP.NET” when I run header(“X-powered-by”) // // // void processResponseHeaders(Map<String, List> resHeaders) { // // for (Map.Entry<String, List> entry : resHeaders.entrySet()) { // // String name = entry.getKey(); // // if (name == null) // // continue; // http/1.1 line // // // // ``` // List<String> values = entry.getValue(); // if (name.equalsIgnoreCase("Set-Cookie")) { // for (String value : values) { // if (value == null) // continue; // TokenQueue cd = new TokenQueue(value); // String cookieName = cd.chompTo("=").trim(); // String cookieVal = cd.consumeTo(";").trim(); // // ignores path, date, domain, validateTLSCertificates et al. req'd? // // name not blank, value not null // if (cookieName.length() > 0) // cookie(cookieName, cookieVal); // } // } else { // only take the first instance of each header // if (!values.isEmpty()) //
Jsoup
package org.jsoup.helper; import static org.junit.Assert.*; import org.jsoup.integration.ParseTest; import org.junit.Test; import org.jsoup.Connection; import java.io.IOException; import java.util.*; import java.net.URL; import java.net.MalformedURLException; public class HttpConnectionTest { /* most actual network http connection tests are in integration */ @Test(expected=IllegalArgumentException.class) public void throwsExceptionOnParseWithoutExecute() throws IOException { Connection con = HttpConnection.connect("http://example.com"); con.response().parse(); } @Test(expected=IllegalArgumentException.class) public void throwsExceptionOnBodyWithoutExecute() throws IOException { Connection con = HttpConnection.connect("http://example.com"); con.response().body(); } @Test(expected=IllegalArgumentException.class) public void throwsExceptionOnBodyAsBytesWithoutExecute() throws IOException { Connection con = HttpConnection.connect("http://example.com"); con.response().bodyAsBytes(); } @Test public void caseInsensitiveHeaders() { Connection.Response res = new HttpConnection.Response(); Map<String, String> headers = res.headers(); headers.put("Accept-Encoding", "gzip"); headers.put("content-type", "text/html"); headers.put("refErrer", "http://example.com"); assertTrue(res.hasHeader("Accept-Encoding")); assertTrue(res.hasHeader("accept-encoding")); assertTrue(res.hasHeader("accept-Encoding")); assertEquals("gzip", res.header("accept-Encoding")); assertEquals("text/html", res.header("Content-Type")); assertEquals("http://example.com", res.header("Referrer")); res.removeHeader("Content-Type"); assertFalse(res.hasHeader("content-type")); res.header("accept-encoding", "deflate"); assertEquals("deflate", res.header("Accept-Encoding")); assertEquals("deflate", res.header("accept-Encoding")); } @Test public void sameHeadersCombineWithComma() { Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> values = new ArrayList<String>(); values.add("no-cache"); values.add("no-store"); headers.put("Cache-Control", values); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals("no-cache, no-store", res.header("Cache-Control")); } @Test public void ignoresEmptySetCookies() { // prep http response header map Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Set-Cookie", Collections.<String>emptyList()); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals(0, res.cookies().size()); } @Test public void ignoresEmptyCookieNameAndVals() { // prep http response header map Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> cookieStrings = new ArrayList<String>(); cookieStrings.add(null); cookieStrings.add(""); cookieStrings.add("one"); cookieStrings.add("two="); cookieStrings.add("three=;"); cookieStrings.add("four=data; Domain=.example.com; Path=/"); headers.put("Set-Cookie", cookieStrings); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals(4, res.cookies().size()); assertEquals("", res.cookie("one")); assertEquals("", res.cookie("two")); assertEquals("", res.cookie("three")); assertEquals("data", res.cookie("four")); } @Test public void connectWithUrl() throws MalformedURLException { Connection con = HttpConnection.connect(new URL("http://example.com")); assertEquals("http://example.com", con.request().url().toExternalForm()); } @Test(expected=IllegalArgumentException.class) public void throwsOnMalformedUrl() { Connection con = HttpConnection.connect("bzzt"); } @Test public void userAgent() { Connection con = HttpConnection.connect("http://example.com/"); con.userAgent("Mozilla"); assertEquals("Mozilla", con.request().header("User-Agent")); } @Test public void timeout() { Connection con = HttpConnection.connect("http://example.com/"); con.timeout(1000); assertEquals(1000, con.request().timeout()); } @Test public void referrer() { Connection con = HttpConnection.connect("http://example.com/"); con.referrer("http://foo.com"); assertEquals("http://foo.com", con.request().header("Referer")); } @Test public void method() { Connection con = HttpConnection.connect("http://example.com/"); assertEquals(Connection.Method.GET, con.request().method()); con.method(Connection.Method.POST); assertEquals(Connection.Method.POST, con.request().method()); } @Test(expected=IllegalArgumentException.class) public void throwsOnOdddData() { Connection con = HttpConnection.connect("http://example.com/"); con.data("Name", "val", "what"); } @Test public void data() { Connection con = HttpConnection.connect("http://example.com/"); con.data("Name", "Val", "Foo", "bar"); Collection<Connection.KeyVal> values = con.request().data(); Object[] data = values.toArray(); Connection.KeyVal one = (Connection.KeyVal) data[0]; Connection.KeyVal two = (Connection.KeyVal) data[1]; assertEquals("Name", one.key()); assertEquals("Val", one.value()); assertEquals("Foo", two.key()); assertEquals("bar", two.value()); } @Test public void cookie() { Connection con = HttpConnection.connect("http://example.com/"); con.cookie("Name", "Val"); assertEquals("Val", con.request().cookie("Name")); } @Test public void inputStream() { Connection.KeyVal kv = HttpConnection.KeyVal.create("file", "thumb.jpg", ParseTest.inputStreamFrom("Check")); assertEquals("file", kv.key()); assertEquals("thumb.jpg", kv.value()); assertTrue(kv.hasInputStream()); kv = HttpConnection.KeyVal.create("one", "two"); assertEquals("one", kv.key()); assertEquals("two", kv.value()); assertFalse(kv.hasInputStream()); } }
public void testGetMsgWiringNoWarnings() throws Exception { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("/** @desc A bad foo. */ var MSG_FOO = 1;", ""); }
com.google.javascript.jscomp.CommandLineRunnerTest::testGetMsgWiringNoWarnings
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
395
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
testGetMsgWiringNoWarnings
/* * 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.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.javascript.jscomp.AbstractCommandLineRunner.FlagUsageException; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.Map; /** * Tests for {@link CommandLineRunner}. * * @author [email protected] (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; private Map<Integer,String> filenames; // If set, this will be appended to the end of the args list. // For testing args parsing. private String lastArg = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<SourceFile> DEFAULT_EXTERNS = ImmutableList.of( SourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @nosideeffects\n" + " * @throws {Error}\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @constructor */ function Element() {}" + "Element.prototype.offsetWidth;" + "/** @nosideeffects */ function noSideEffects() {}\n" + "/** @param {...*} x */ function alert(x) {}\n") ); private List<SourceFile> externs; @Override public void setUp() throws Exception { super.setUp(); externs = DEFAULT_EXTERNS; filenames = Maps.newHashMap(); lastCompiler = null; lastArg = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testUnknownAnnotation() { args.add("--warning_level=VERBOSE"); test("/** @unknownTag */ function f() {}", RhinoErrorReporter.BAD_JSDOC_ANNOTATION); args.add("--extra_annotation_name=unknownTag"); testSame("/** @unknownTag */ function f() {}"); } public void testWarningGuardOrdering1() { args.add("--jscomp_error=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering2() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testWarningGuardOrdering3() { args.add("--jscomp_warning=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering4() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_warning=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testSimpleModeLeavesUnusedParams() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); testSame("window.f = function(a) {};"); } public void testAdvancedModeRemovesUnusedParams() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("window.f = function(a) {};", "window.a = function() {};"); } public void testCheckGlobalThisOffByDefault() { testSame("function f() { this.a = 3; }"); } public void testCheckGlobalThisOnWithAdvancedMode() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOnWithErrorFlag() { args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOff() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testReflectedMethods() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test( "/** @constructor */" + "function Foo() {}" + "Foo.prototype.handle = function(x, y) { alert(y); };" + "var x = goog.reflect.object(Foo, {handle: 1});" + "for (var i in x) { x[i].call(x); }" + "window['Foo'] = Foo;", "function a() {}" + "a.prototype.a = function(e, d) { alert(d); };" + "var b = goog.c.b(a, {a: 1}),c;" + "for (c in b) { b[c].call(b); }" + "window.Foo = a;"); } public void testInlineVariables() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); // Verify local var "val" in method "bar" is not inlined over the "inc" // method call (which has side-effects) but "c" is inlined (which can't be // modified by the call). test( "/** @constructor */ function F() { this.a = 0; }" + "F.prototype.inc = function() { this.a++; return 10; };" + "F.prototype.bar = function() { " + " var c = 3; var val = this.inc(); this.a += val + c;" + "};" + "window['f'] = new F();" + "window['f']['inc'] = window['f'].inc;" + "window['f']['bar'] = window['f'].bar;" + "use(window['f'].a)", "function a(){ this.a = 0; }" + "a.prototype.b = function(){ this.a++; return 10; };" + "a.prototype.c = function(){ var b=this.b(); this.a += b + 3; };" + "window.f = new a;" + "window.f.inc = window.f.b;" + "window.f.bar = window.f.c;" + "use(window.f.a);"); } public void testTypedAdvanced() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--use_types_for_optimization"); test( "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.handle1 = function(x, y) { alert(y); };\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype.handle1 = function(x, y) {};\n" + "new Foo().handle1(1, 2);\n" + "new Bar().handle1(1, 2);\n", "alert(2)"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeParsingOffByDefault() { testSame("/** @return {number */ function f(a) { return a; }"); } public void testTypeParsingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); test("/** @return {n} */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); } 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;", VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckSymbolsOverrideForQuiet() { args.add("--warning_level=QUIET"); args.add("--jscomp_error=undefinedVars"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); } public void testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {var x = {}; var y = x.bar;}", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function f(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 = !0, BAR = 5, CCC = !0, DDD = !0;"); } public void testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } 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("/** @const \n * @const */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @const \n * @const */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {dom:{}};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } public void testGetMsgWiring() throws Exception { test("var goog = {}; goog.getMsg = function(x) { return x; };" + "/** @desc A real foo. */ var MSG_FOO = goog.getMsg('foo');", "var goog={getMsg:function(a){return a}}, " + "MSG_FOO=goog.getMsg('foo');"); args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("var goog = {}; goog.getMsg = function(x) { return x; };" + "/** @desc A real foo. */ var MSG_FOO = goog.getMsg('foo');" + "window['foo'] = MSG_FOO;", "window.foo = 'foo';"); } public void testGetMsgWiringNoWarnings() throws Exception { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("/** @desc A bad foo. */ var MSG_FOO = 1;", ""); } public void testCssNameWiring() throws Exception { test("var goog = {}; goog.getCssName = function() {};" + "goog.setCssNameMapping = function() {};" + "goog.setCssNameMapping({'goog': 'a', 'button': 'b'});" + "var a = goog.getCssName('goog-button');" + "var b = goog.getCssName('css-button');" + "var c = goog.getCssName('goog-menu');" + "var d = goog.getCssName('css-menu');", "var goog = { getCssName: function() {}," + " setCssNameMapping: function() {} }," + " a = 'a-b'," + " b = 'css-b'," + " c = 'a-menu'," + " d = 'css-menu';"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70a() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue70b() { 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("--jscomp_off=es5Strict"); 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 testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1)))) && x>0;" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1)))) && 0<a;" + "}"); } public void testHiddenSideEffect() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("element.offsetWidth;", "element.offsetWidth", CheckSideEffects.USELESS_CODE_ERROR); } public void testIssue504() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("void function() { alert('hi'); }();", "alert('hi');void 0", CheckSideEffects.USELESS_CODE_ERROR); } public void testIssue601() { args.add("--compilation_level=WHITESPACE_ONLY"); test("function f() { return '\\v' == 'v'; } window['f'] = f;", "function f(){return'\\v'=='v'}window['f']=f"); } public void testIssue601b() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { return '\\v' == 'v'; } window['f'] = f;", "window.f=function(){return'\\v'=='v'}"); } public void testIssue601c() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { return '\\u000B' == 'v'; } window['f'] = f;", "window.f=function(){return'\\u000B'=='v'}"); } public void testIssue846() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); testSame( "try { new Function('this is an error'); } catch(a) { alert('x'); }"); } public void testSideEffectIntegration() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("/** @constructor */" + "var Foo = function() {};" + "Foo.prototype.blah = function() {" + " Foo.bar_(this)" + "};" + "Foo.bar_ = function(f) {" + " f.x = 5;" + "};" + "var y = new Foo();" + "Foo.bar_({});" + // We used to strip this too // due to bad side-effect propagation. "y.blah();" + "alert(y);", "var a = new function(){}; a.a = 5; alert(a);"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo(a) {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($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();", "throw (new function() {}).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();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { args.add("--compilation_level=WHITESPACE_ONLY"); testSame( new String[] { "goog.require('beer');", "goog.provide('beer');" }); } public void testSourceSortingOn() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingOn2() { test(new String[] { "goog.provide('a');", "goog.require('a');\n" + "var COMPILED = false;", }, new String[] { "var a={};", "var COMPILED=!1" }); } public void testSourceSortingOn3() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.addDependency('sym', [], []);\nvar x = 3;", "var COMPILED = false;", }, new String[] { "var COMPILED = !1;", "var x = 3;" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn7() { args.add("--manage_closure_dependencies=true"); test(new String[] { "var COMPILED = false;", }, new String[] { "var COMPILED = !1;", }); } public void testSourcePruningOn8() { args.add("--only_closure_dependencies"); args.add("--closure_entry_point=scotch"); args.add("--warning_level=VERBOSE"); test(new String[] { "/** @externs */\n" + "var externVar;", "goog.provide('scotch'); var x = externVar;" }, new String[] { "var scotch = {}, x = externVar;", }); } public void testModuleEntryPoint() throws Exception { useModules = ModulePattern.STAR; args.add("--only_closure_dependencies"); args.add("--closure_entry_point=m1:a"); test( new String[] { "goog.provide('a');", "goog.provide('b');" }, // Check that 'b' was stripped out, and 'a' was moved to the second // module (m1). new String[] { "", "var a = {};" }); } public void testNoCompile() { args.add("--warning_level=VERBOSE"); test(new String[] { "/** @nocompile */\n" + "goog.provide('x');\n" + "var dupeVar;", "var dupeVar;" }, new String[] { "var dupeVar;" }); } public void testDependencySortingWhitespaceMode() { args.add("--manage_closure_dependencies"); args.add("--compilation_level=WHITESPACE_ONLY"); test(new String[] { "goog.require('beer');", "goog.provide('beer');\ngoog.require('hops');", "goog.provide('hops');", }, new String[] { "goog.provide('hops');", "goog.provide('beer');\ngoog.require('hops');", "goog.require('beer');" }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f(a) {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f(a) {}", "" }, RhinoErrorReporter.TYPE_PARSE_ERROR); } public void testOnlyClosureDependenciesEmptyEntryPoints() throws Exception { // Prevents this from trying to load externs.zip args.add("--use_only_custom_externs=true"); args.add("--only_closure_dependencies=true"); try { CommandLineRunner runner = createCommandLineRunner(new String[0]); runner.doRun(); fail("Expected FlagUsageException"); } catch (FlagUsageException e) { assertTrue(e.getMessage(), e.getMessage().contains("only_closure_dependencies")); } } public void testOnlyClosureDependenciesOneEntryPoint() throws Exception { args.add("--only_closure_dependencies=true"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.require('beer'); var beerRequired = 1;", "goog.provide('beer');\ngoog.require('hops');\nvar beerProvided = 1;", "goog.provide('hops'); var hopsProvided = 1;", "goog.provide('scotch'); var scotchProvided = 1;", "goog.require('scotch');\nvar includeFileWithoutProvides = 1;", "/** This is base.js */\nvar COMPILED = false;", }, new String[] { "var COMPILED = !1;", "var hops = {}, hopsProvided = 1;", "var beer = {}, beerProvided = 1;" }); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.DEFAULT, lastCompiler.getOptions().sourceMapFormat); } public void testSourceMapFormat2() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--source_map_format=V3"); testSame("var x = 3;"); assertEquals(SourceMap.Format.V3, lastCompiler.getOptions().sourceMapFormat); } public void testModuleWrapperBaseNameExpansion() throws Exception { useModules = ModulePattern.CHAIN; args.add("--module_wrapper=m0:%s // %basename%"); testSame(new String[] { "var x = 3;", "var y = 4;" }); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.writeModuleOutput( builder, lastCompiler.getModuleGraph().getRootModule()); assertEquals("var x=3; // m0.js\n", builder.toString()); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testOutputModuleGraphJson() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphJsonTo(builder); assertTrue(builder.toString().indexOf("transitive-dependencies") != -1); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testVersionFlag2() { lastArg = "--version"; testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } public void testSyntheticExterns() { externs = ImmutableList.of( SourceFile.fromCode("externs", "myVar.property;")); test("var theirVar = {}; var myVar = {}; var yourVar = {};", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var yourVar = {};", "var theirVar={},myVar={},yourVar={};"); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var myVar = {};", VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testGoogAssertStripping() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("goog.asserts.assert(false)", ""); args.add("--debug"); test("goog.asserts.assert(false)", "goog.$asserts$.$assert$(!1)"); } public void testMissingReturnCheckOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number} */ function f() {f()} f();", CheckMissingReturn.MISSING_RETURN_STATEMENT); } public void testGenerateExports() { args.add("--generate_exports=true"); test("/** @export */ foo.prototype.x = function() {};", "foo.prototype.x=function(){};"+ "goog.exportSymbol(\"foo.prototype.x\",foo.prototype.x);"); } public void testDepreciationWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @deprecated */ function f() {}; f()", CheckAccessControls.DEPRECATED_NAME); } public void testTwoParseErrors() { // If parse errors are reported in different files, make // sure all of them are reported. Compiler compiler = compile(new String[] { "var a b;", "var b c;" }); assertEquals(2, compiler.getErrors().length); } public void testES3ByDefault() { useStringComparison = true; test( "var x = f.function", "var x=f[\"function\"];", RhinoErrorReporter.INVALID_ES3_PROP_NAME); } public void testES5ChecksByDefault() { testSame("var x = 3; delete x;"); } public void testES5ChecksInVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { delete x; }", StrictModeCheck.DELETE_VARIABLE); } public void testES5() { args.add("--language_in=ECMASCRIPT5"); test("var x = f.function", "var x = f.function"); test("var let", "var let"); } public void testES5Strict() { args.add("--language_in=ECMASCRIPT5_STRICT"); test("var x = f.function", "'use strict';var x = f.function"); test("var let", RhinoErrorReporter.PARSE_ERROR); test("function f(x) { delete x; }", StrictModeCheck.DELETE_VARIABLE); } public void testES5StrictUseStrict() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); } public void testES5StrictUseStrictMultipleInputs() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function", "var y = f.function", "var z = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); assertEquals(outputSource.substring(13).indexOf("'use strict'"), -1); } public void testWithKeywordDefault() { test("var x = {}; with (x) {}", ControlStructureCheck.USE_OF_WITH); } public void testWithKeywordWithEs5ChecksOff() { args.add("--jscomp_off=es5Strict"); testSame("var x = {}; with (x) {}"); } public void testNoSrCFilesWithManifest() throws IOException { args.add("--use_only_custom_externs=true"); args.add("--output_manifest=test.MF"); CommandLineRunner runner = createCommandLineRunner(new String[0]); String expectedMessage = ""; try { runner.doRun(); } catch (FlagUsageException e) { expectedMessage = e.getMessage(); } assertEquals(expectedMessage, "Bad --js flag. " + "Manifest files cannot be generated when the input is from stdin."); } public void testTransformAMD() { args.add("--transform_amd_modules"); test("define({test: 1})", "exports = {test: 1}"); } public void testProcessCJS() { useStringComparison = true; args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); setFilename(0, "foo/bar.js"); String expected = "var module$foo$bar={test:1};"; test("exports.test = 1", expected); assertEquals(expected + "\n", outReader.toString()); } public void testProcessCJSWithModuleOutput() { useStringComparison = true; args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); args.add("--module=auto"); setFilename(0, "foo/bar.js"); test("exports.test = 1", "var module$foo$bar={test:1};"); // With modules=auto no direct output is created. assertEquals("", outReader.toString()); } public void testFormattingSingleQuote() { testSame("var x = '';"); assertEquals("var x=\"\";", lastCompiler.toSource()); args.add("--formatting=SINGLE_QUOTES"); testSame("var x = '';"); assertEquals("var x='';", lastCompiler.toSource()); } public void testTransformAMDAndProcessCJS() { useStringComparison = true; args.add("--transform_amd_modules"); args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); setFilename(0, "foo/bar.js"); test("define({foo: 1})", "var module$foo$bar={},module$foo$bar={foo:1};"); } public void testModuleJSON() { useStringComparison = true; args.add("--transform_amd_modules"); args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); args.add("--output_module_dependencies=test.json"); setFilename(0, "foo/bar.js"); test("define({foo: 1})", "var module$foo$bar={},module$foo$bar={foo:1};"); } public void testOutputSameAsInput() { args.add("--js_output_file=" + getFilename(0)); test("", AbstractCommandLineRunner.OUTPUT_SAME_AS_INPUT_ERROR); } /* 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) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { 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); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } 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); } private void test(String original, String expected, DiagnosticType warning) { test(new String[] { original }, new String[] { expected }, 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); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("m" + i + ":1" + (i > 0 ? (":m" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("m" + i + ":1" + (i > 0 ? ":m0" : "")); } } if (lastArg != null) { args.add(lastArg); } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(new String(errReader.toByteArray()), runner.shouldRunCompiler()); Supplier<List<SourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode(getFilename(i), original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<SourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode(getFilename(i), original[i])); } CompilerOptions options = new CompilerOptions(); // ECMASCRIPT5 is the most forgiving. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.init(externs, inputs, options); Node all = compiler.parseInputs(); Preconditions.checkState(compiler.getErrorCount() == 0); Preconditions.checkNotNull(all); Node n = all.getLastChild(); return n; } private void setFilename(int i, String filename) { this.filenames.put(i, filename); } private String getFilename(int i) { if (filenames.isEmpty()) { return "input" + i; } return filenames.get(i); } }
// You are a professional Java test case writer, please create a test case named `testGetMsgWiringNoWarnings` for the issue `Closure-1135`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1135 // // ## Issue-Title: // Variable names prefixed with MSG_ cause error with advanced optimizations // // ## Issue-Description: // Variables named something with MSG\_ seem to cause problems with the module system, even if no modules are used in the code. // // $ echo "var MSG\_foo='bar'" | closure --compilation\_level ADVANCED\_OPTIMIZATIONS // stdin:1: ERROR - message not initialized using goog.getMsg // var MSG\_foo='bar' // ^ // // It works fine with msg\_foo, MSG2\_foo, etc. // // public void testGetMsgWiringNoWarnings() throws Exception {
395
107
392
test/com/google/javascript/jscomp/CommandLineRunnerTest.java
test
```markdown ## Issue-ID: Closure-1135 ## Issue-Title: Variable names prefixed with MSG_ cause error with advanced optimizations ## Issue-Description: Variables named something with MSG\_ seem to cause problems with the module system, even if no modules are used in the code. $ echo "var MSG\_foo='bar'" | closure --compilation\_level ADVANCED\_OPTIMIZATIONS stdin:1: ERROR - message not initialized using goog.getMsg var MSG\_foo='bar' ^ It works fine with msg\_foo, MSG2\_foo, etc. ``` You are a professional Java test case writer, please create a test case named `testGetMsgWiringNoWarnings` for the issue `Closure-1135`, utilizing the provided issue report information and the following function signature. ```java public void testGetMsgWiringNoWarnings() throws Exception { ```
392
[ "com.google.javascript.jscomp.CommandLineRunner" ]
e63954f5b95fe3de4fb85bdb6c4a6e8759398a8ae29a8384dec4ec6e35977d7a
public void testGetMsgWiringNoWarnings() throws Exception
// You are a professional Java test case writer, please create a test case named `testGetMsgWiringNoWarnings` for the issue `Closure-1135`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Closure-1135 // // ## Issue-Title: // Variable names prefixed with MSG_ cause error with advanced optimizations // // ## Issue-Description: // Variables named something with MSG\_ seem to cause problems with the module system, even if no modules are used in the code. // // $ echo "var MSG\_foo='bar'" | closure --compilation\_level ADVANCED\_OPTIMIZATIONS // stdin:1: ERROR - message not initialized using goog.getMsg // var MSG\_foo='bar' // ^ // // It works fine with msg\_foo, MSG2\_foo, etc. // //
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.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.javascript.jscomp.AbstractCommandLineRunner.FlagUsageException; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.rhino.Node; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.Map; /** * Tests for {@link CommandLineRunner}. * * @author [email protected] (Nick Santos) */ public class CommandLineRunnerTest extends TestCase { private Compiler lastCompiler = null; private CommandLineRunner lastCommandLineRunner = null; private List<Integer> exitCodes = null; private ByteArrayOutputStream outReader = null; private ByteArrayOutputStream errReader = null; private Map<Integer,String> filenames; // If set, this will be appended to the end of the args list. // For testing args parsing. private String lastArg = null; // If set to true, uses comparison by string instead of by AST. private boolean useStringComparison = false; private ModulePattern useModules = ModulePattern.NONE; private enum ModulePattern { NONE, CHAIN, STAR } private List<String> args = Lists.newArrayList(); /** Externs for the test */ private final List<SourceFile> DEFAULT_EXTERNS = ImmutableList.of( SourceFile.fromCode("externs", "var arguments;" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @nosideeffects\n" + " * @throws {Error}\n" + " */\n" + "function Function(var_args) {}\n" + "/**\n" + " * @param {...*} var_args\n" + " * @return {*}\n" + " */\n" + "Function.prototype.call = function(var_args) {};" + "/**\n" + " * @constructor\n" + " * @param {...*} var_args\n" + " * @return {!Array}\n" + " */\n" + "function Array(var_args) {}" + "/**\n" + " * @param {*=} opt_begin\n" + " * @param {*=} opt_end\n" + " * @return {!Array}\n" + " * @this {Object}\n" + " */\n" + "Array.prototype.slice = function(opt_begin, opt_end) {};" + "/** @constructor */ function Window() {}\n" + "/** @type {string} */ Window.prototype.name;\n" + "/** @type {Window} */ var window;" + "/** @constructor */ function Element() {}" + "Element.prototype.offsetWidth;" + "/** @nosideeffects */ function noSideEffects() {}\n" + "/** @param {...*} x */ function alert(x) {}\n") ); private List<SourceFile> externs; @Override public void setUp() throws Exception { super.setUp(); externs = DEFAULT_EXTERNS; filenames = Maps.newHashMap(); lastCompiler = null; lastArg = null; outReader = new ByteArrayOutputStream(); errReader = new ByteArrayOutputStream(); useStringComparison = false; useModules = ModulePattern.NONE; args.clear(); exitCodes = Lists.newArrayList(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testUnknownAnnotation() { args.add("--warning_level=VERBOSE"); test("/** @unknownTag */ function f() {}", RhinoErrorReporter.BAD_JSDOC_ANNOTATION); args.add("--extra_annotation_name=unknownTag"); testSame("/** @unknownTag */ function f() {}"); } public void testWarningGuardOrdering1() { args.add("--jscomp_error=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering2() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testWarningGuardOrdering3() { args.add("--jscomp_warning=globalThis"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testWarningGuardOrdering4() { args.add("--jscomp_off=globalThis"); args.add("--jscomp_warning=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testSimpleModeLeavesUnusedParams() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); testSame("window.f = function(a) {};"); } public void testAdvancedModeRemovesUnusedParams() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("window.f = function(a) {};", "window.a = function() {};"); } public void testCheckGlobalThisOffByDefault() { testSame("function f() { this.a = 3; }"); } public void testCheckGlobalThisOnWithAdvancedMode() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOnWithErrorFlag() { args.add("--jscomp_error=globalThis"); test("function f() { this.a = 3; }", CheckGlobalThis.GLOBAL_THIS); } public void testCheckGlobalThisOff() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=globalThis"); testSame("function f() { this.a = 3; }"); } public void testTypeCheckingOffByDefault() { test("function f(x) { return x; } f();", "function f(a) { return a; } f();"); } public void testReflectedMethods() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test( "/** @constructor */" + "function Foo() {}" + "Foo.prototype.handle = function(x, y) { alert(y); };" + "var x = goog.reflect.object(Foo, {handle: 1});" + "for (var i in x) { x[i].call(x); }" + "window['Foo'] = Foo;", "function a() {}" + "a.prototype.a = function(e, d) { alert(d); };" + "var b = goog.c.b(a, {a: 1}),c;" + "for (c in b) { b[c].call(b); }" + "window.Foo = a;"); } public void testInlineVariables() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); // Verify local var "val" in method "bar" is not inlined over the "inc" // method call (which has side-effects) but "c" is inlined (which can't be // modified by the call). test( "/** @constructor */ function F() { this.a = 0; }" + "F.prototype.inc = function() { this.a++; return 10; };" + "F.prototype.bar = function() { " + " var c = 3; var val = this.inc(); this.a += val + c;" + "};" + "window['f'] = new F();" + "window['f']['inc'] = window['f'].inc;" + "window['f']['bar'] = window['f'].bar;" + "use(window['f'].a)", "function a(){ this.a = 0; }" + "a.prototype.b = function(){ this.a++; return 10; };" + "a.prototype.c = function(){ var b=this.b(); this.a += b + 3; };" + "window.f = new a;" + "window.f.inc = window.f.b;" + "window.f.bar = window.f.c;" + "use(window.f.a);"); } public void testTypedAdvanced() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); args.add("--use_types_for_optimization"); test( "/** @constructor */\n" + "function Foo() {}\n" + "Foo.prototype.handle1 = function(x, y) { alert(y); };\n" + "/** @constructor */\n" + "function Bar() {}\n" + "Bar.prototype.handle1 = function(x, y) {};\n" + "new Foo().handle1(1, 2);\n" + "new Bar().handle1(1, 2);\n", "alert(2)"); } public void testTypeCheckingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { return x; } f();", TypeCheck.WRONG_ARGUMENT_COUNT); } public void testTypeParsingOffByDefault() { testSame("/** @return {number */ function f(a) { return a; }"); } public void testTypeParsingOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); test("/** @return {n} */ function f(a) { return a; }", RhinoErrorReporter.TYPE_PARSE_ERROR); } 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;", VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testCheckSymbolsOverrideForVerbose() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=undefinedVars"); testSame("x = 3;"); } public void testCheckSymbolsOverrideForQuiet() { args.add("--warning_level=QUIET"); args.add("--jscomp_error=undefinedVars"); test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR); } public void testCheckUndefinedProperties1() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_error=missingProperties"); test("var x = {}; var y = x.bar;", TypeCheck.INEXISTENT_PROPERTY); } public void testCheckUndefinedProperties2() { args.add("--warning_level=VERBOSE"); args.add("--jscomp_off=missingProperties"); test("var x = {}; var y = x.bar;", CheckGlobalNames.UNDEFINED_NAME_WARNING); } public void testCheckUndefinedProperties3() { args.add("--warning_level=VERBOSE"); test("function f() {var x = {}; var y = x.bar;}", TypeCheck.INEXISTENT_PROPERTY); } public void testDuplicateParams() { test("function f(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 = !0, BAR = 5, CCC = !0, DDD = !0;"); } public void testDefineFlag2() { args.add("--define=FOO='x\"'"); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x\\\"\";"); } public void testDefineFlag3() { args.add("--define=FOO=\"x'\""); test("/** @define {string} */ var FOO = \"a\";", "var FOO = \"x'\";"); } 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("/** @const \n * @const */ var x;", RhinoErrorReporter.PARSE_ERROR); args.add("--warning_level=QUIET"); testSame("/** @const \n * @const */ var x;"); } public void testProcessClosurePrimitives() { test("var goog = {}; goog.provide('goog.dom');", "var goog = {dom:{}};"); args.add("--process_closure_primitives=false"); testSame("var goog = {}; goog.provide('goog.dom');"); } public void testGetMsgWiring() throws Exception { test("var goog = {}; goog.getMsg = function(x) { return x; };" + "/** @desc A real foo. */ var MSG_FOO = goog.getMsg('foo');", "var goog={getMsg:function(a){return a}}, " + "MSG_FOO=goog.getMsg('foo');"); args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("var goog = {}; goog.getMsg = function(x) { return x; };" + "/** @desc A real foo. */ var MSG_FOO = goog.getMsg('foo');" + "window['foo'] = MSG_FOO;", "window.foo = 'foo';"); } public void testGetMsgWiringNoWarnings() throws Exception { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("/** @desc A bad foo. */ var MSG_FOO = 1;", ""); } public void testCssNameWiring() throws Exception { test("var goog = {}; goog.getCssName = function() {};" + "goog.setCssNameMapping = function() {};" + "goog.setCssNameMapping({'goog': 'a', 'button': 'b'});" + "var a = goog.getCssName('goog-button');" + "var b = goog.getCssName('css-button');" + "var c = goog.getCssName('goog-menu');" + "var d = goog.getCssName('css-menu');", "var goog = { getCssName: function() {}," + " setCssNameMapping: function() {} }," + " a = 'a-b'," + " b = 'css-b'," + " c = 'a-menu'," + " d = 'css-menu';"); } ////////////////////////////////////////////////////////////////////////////// // Integration tests public void testIssue70a() { test("function foo({}) {}", RhinoErrorReporter.PARSE_ERROR); } public void testIssue70b() { 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("--jscomp_off=es5Strict"); 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 testIssue297() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function f(p) {" + " var x;" + " return ((x=p.id) && (x=parseInt(x.substr(1)))) && x>0;" + "}", "function f(b) {" + " var a;" + " return ((a=b.id) && (a=parseInt(a.substr(1)))) && 0<a;" + "}"); } public void testHiddenSideEffect() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("element.offsetWidth;", "element.offsetWidth", CheckSideEffects.USELESS_CODE_ERROR); } public void testIssue504() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("void function() { alert('hi'); }();", "alert('hi');void 0", CheckSideEffects.USELESS_CODE_ERROR); } public void testIssue601() { args.add("--compilation_level=WHITESPACE_ONLY"); test("function f() { return '\\v' == 'v'; } window['f'] = f;", "function f(){return'\\v'=='v'}window['f']=f"); } public void testIssue601b() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { return '\\v' == 'v'; } window['f'] = f;", "window.f=function(){return'\\v'=='v'}"); } public void testIssue601c() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("function f() { return '\\u000B' == 'v'; } window['f'] = f;", "window.f=function(){return'\\u000B'=='v'}"); } public void testIssue846() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); testSame( "try { new Function('this is an error'); } catch(a) { alert('x'); }"); } public void testSideEffectIntegration() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("/** @constructor */" + "var Foo = function() {};" + "Foo.prototype.blah = function() {" + " Foo.bar_(this)" + "};" + "Foo.bar_ = function(f) {" + " f.x = 5;" + "};" + "var y = new Foo();" + "Foo.bar_({});" + // We used to strip this too // due to bad side-effect propagation. "y.blah();" + "alert(y);", "var a = new function(){}; a.a = 5; alert(a);"); } public void testDebugFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=false"); test("function foo(a) {}", "function foo(a) {}"); } public void testDebugFlag2() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug=true"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($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();", "throw (new function() {}).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();", "throw (new function Foo() {}).$x$;"); } public void testBooleanFlag1() { args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); args.add("--debug"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testBooleanFlag2() { args.add("--debug"); args.add("--compilation_level=SIMPLE_OPTIMIZATIONS"); test("function foo(a) {alert(a)}", "function foo($a$$) {alert($a$$)}"); } public void testHelpFlag() { args.add("--help"); assertFalse( createCommandLineRunner( new String[] {"function f() {}"}).shouldRunCompiler()); } public void testExternsLifting1() throws Exception{ String code = "/** @externs */ function f() {}"; test(new String[] {code}, new String[] {}); assertEquals(2, lastCompiler.getExternsForTesting().size()); CompilerInput extern = lastCompiler.getExternsForTesting().get(1); assertNull(extern.getModule()); assertTrue(extern.isExtern()); assertEquals(code, extern.getCode()); assertEquals(1, lastCompiler.getInputsForTesting().size()); CompilerInput input = lastCompiler.getInputsForTesting().get(0); assertNotNull(input.getModule()); assertFalse(input.isExtern()); assertEquals("", input.getCode()); } public void testExternsLifting2() { args.add("--warning_level=VERBOSE"); test(new String[] {"/** @externs */ function f() {}", "f(3);"}, new String[] {"f(3);"}, TypeCheck.WRONG_ARGUMENT_COUNT); } public void testSourceSortingOff() { args.add("--compilation_level=WHITESPACE_ONLY"); testSame( new String[] { "goog.require('beer');", "goog.provide('beer');" }); } public void testSourceSortingOn() { test(new String[] { "goog.require('beer');", "goog.provide('beer');" }, new String[] { "var beer = {};", "" }); } public void testSourceSortingOn2() { test(new String[] { "goog.provide('a');", "goog.require('a');\n" + "var COMPILED = false;", }, new String[] { "var a={};", "var COMPILED=!1" }); } public void testSourceSortingOn3() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.addDependency('sym', [], []);\nvar x = 3;", "var COMPILED = false;", }, new String[] { "var COMPILED = !1;", "var x = 3;" }); } public void testSourceSortingCircularDeps1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourceSortingCircularDeps2() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.provide('roses.lime.juice');", "goog.provide('gin'); goog.require('tonic'); var gin = {};", "goog.provide('tonic'); goog.require('gin'); var tonic = {};", "goog.require('gin'); goog.require('tonic');", "goog.provide('gimlet');" + " goog.require('gin'); goog.require('roses.lime.juice');" }, JSModule.CIRCULAR_DEPENDENCY_ERROR); } public void testSourcePruningOn1() { args.add("--manage_closure_dependencies=true"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "" }); } public void testSourcePruningOn2() { args.add("--closure_entry_point=guinness"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var guinness = {};" }); } public void testSourcePruningOn3() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var scotch = {}, x = 3;", }); } public void testSourcePruningOn4() { args.add("--closure_entry_point=scotch"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn5() { args.add("--closure_entry_point=shiraz"); test(new String[] { "goog.provide('guinness');\ngoog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, Compiler.MISSING_ENTRY_ERROR); } public void testSourcePruningOn6() { args.add("--closure_entry_point=scotch"); test(new String[] { "goog.require('beer');", "goog.provide('beer');", "goog.provide('scotch'); var x = 3;" }, new String[] { "var beer = {};", "", "var scotch = {}, x = 3;", }); } public void testSourcePruningOn7() { args.add("--manage_closure_dependencies=true"); test(new String[] { "var COMPILED = false;", }, new String[] { "var COMPILED = !1;", }); } public void testSourcePruningOn8() { args.add("--only_closure_dependencies"); args.add("--closure_entry_point=scotch"); args.add("--warning_level=VERBOSE"); test(new String[] { "/** @externs */\n" + "var externVar;", "goog.provide('scotch'); var x = externVar;" }, new String[] { "var scotch = {}, x = externVar;", }); } public void testModuleEntryPoint() throws Exception { useModules = ModulePattern.STAR; args.add("--only_closure_dependencies"); args.add("--closure_entry_point=m1:a"); test( new String[] { "goog.provide('a');", "goog.provide('b');" }, // Check that 'b' was stripped out, and 'a' was moved to the second // module (m1). new String[] { "", "var a = {};" }); } public void testNoCompile() { args.add("--warning_level=VERBOSE"); test(new String[] { "/** @nocompile */\n" + "goog.provide('x');\n" + "var dupeVar;", "var dupeVar;" }, new String[] { "var dupeVar;" }); } public void testDependencySortingWhitespaceMode() { args.add("--manage_closure_dependencies"); args.add("--compilation_level=WHITESPACE_ONLY"); test(new String[] { "goog.require('beer');", "goog.provide('beer');\ngoog.require('hops');", "goog.provide('hops');", }, new String[] { "goog.provide('hops');", "goog.provide('beer');\ngoog.require('hops');", "goog.require('beer');" }); } public void testForwardDeclareDroppedTypes() { args.add("--manage_closure_dependencies=true"); args.add("--warning_level=VERBOSE"); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}", "goog.provide('Scotch'); var x = 3;" }, new String[] { "var beer = {}; function f(a) {}", "" }); test(new String[] { "goog.require('beer');", "goog.provide('beer'); /** @param {Scotch} x */ function f(x) {}" }, new String[] { "var beer = {}; function f(a) {}", "" }, RhinoErrorReporter.TYPE_PARSE_ERROR); } public void testOnlyClosureDependenciesEmptyEntryPoints() throws Exception { // Prevents this from trying to load externs.zip args.add("--use_only_custom_externs=true"); args.add("--only_closure_dependencies=true"); try { CommandLineRunner runner = createCommandLineRunner(new String[0]); runner.doRun(); fail("Expected FlagUsageException"); } catch (FlagUsageException e) { assertTrue(e.getMessage(), e.getMessage().contains("only_closure_dependencies")); } } public void testOnlyClosureDependenciesOneEntryPoint() throws Exception { args.add("--only_closure_dependencies=true"); args.add("--closure_entry_point=beer"); test(new String[] { "goog.require('beer'); var beerRequired = 1;", "goog.provide('beer');\ngoog.require('hops');\nvar beerProvided = 1;", "goog.provide('hops'); var hopsProvided = 1;", "goog.provide('scotch'); var scotchProvided = 1;", "goog.require('scotch');\nvar includeFileWithoutProvides = 1;", "/** This is base.js */\nvar COMPILED = false;", }, new String[] { "var COMPILED = !1;", "var hops = {}, hopsProvided = 1;", "var beer = {}, beerProvided = 1;" }); } public void testSourceMapExpansion1() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--create_source_map=%outname%.map"); testSame("var x = 3;"); assertEquals("/path/to/out.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion2() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), null)); } public void testSourceMapExpansion3() { useModules = ModulePattern.CHAIN; args.add("--create_source_map=%outname%.map"); args.add("--module_output_path_prefix=foo_"); testSame(new String[] {"var x = 3;", "var y = 5;"}); assertEquals("foo_m0.js.map", lastCommandLineRunner.expandSourceMapPath( lastCompiler.getOptions(), lastCompiler.getModuleGraph().getRootModule())); } public void testSourceMapFormat1() { args.add("--js_output_file"); args.add("/path/to/out.js"); testSame("var x = 3;"); assertEquals(SourceMap.Format.DEFAULT, lastCompiler.getOptions().sourceMapFormat); } public void testSourceMapFormat2() { args.add("--js_output_file"); args.add("/path/to/out.js"); args.add("--source_map_format=V3"); testSame("var x = 3;"); assertEquals(SourceMap.Format.V3, lastCompiler.getOptions().sourceMapFormat); } public void testModuleWrapperBaseNameExpansion() throws Exception { useModules = ModulePattern.CHAIN; args.add("--module_wrapper=m0:%s // %basename%"); testSame(new String[] { "var x = 3;", "var y = 4;" }); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.writeModuleOutput( builder, lastCompiler.getModuleGraph().getRootModule()); assertEquals("var x=3; // m0.js\n", builder.toString()); } public void testCharSetExpansion() { testSame(""); assertEquals("US-ASCII", lastCompiler.getOptions().outputCharset); args.add("--charset=UTF-8"); testSame(""); assertEquals("UTF-8", lastCompiler.getOptions().outputCharset); } public void testChainModuleManifest() throws Exception { useModules = ModulePattern.CHAIN; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m1}\n" + "i2\n" + "\n" + "{m3:m2}\n" + "i3\n", builder.toString()); } public void testStarModuleManifest() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphManifestOrBundleTo( lastCompiler.getModuleGraph(), builder, true); assertEquals( "{m0}\n" + "i0\n" + "\n" + "{m1:m0}\n" + "i1\n" + "\n" + "{m2:m0}\n" + "i2\n" + "\n" + "{m3:m0}\n" + "i3\n", builder.toString()); } public void testOutputModuleGraphJson() throws Exception { useModules = ModulePattern.STAR; testSame(new String[] { "var x = 3;", "var y = 5;", "var z = 7;", "var a = 9;"}); StringBuilder builder = new StringBuilder(); lastCommandLineRunner.printModuleGraphJsonTo(builder); assertTrue(builder.toString().indexOf("transitive-dependencies") != -1); } public void testVersionFlag() { args.add("--version"); testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testVersionFlag2() { lastArg = "--version"; testSame(""); assertEquals( 0, new String(errReader.toByteArray()).indexOf( "Closure Compiler (http://code.google.com/closure/compiler)\n" + "Version: ")); } public void testPrintAstFlag() { args.add("--print_ast=true"); testSame(""); assertEquals( "digraph AST {\n" + " node [color=lightblue2, style=filled];\n" + " node0 [label=\"BLOCK\"];\n" + " node1 [label=\"SCRIPT\"];\n" + " node0 -> node1 [weight=1];\n" + " node1 -> RETURN [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> RETURN [label=\"SYN_BLOCK\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + " node0 -> node1 [label=\"UNCOND\", " + "fontcolor=\"red\", weight=0.01, color=\"red\"];\n" + "}\n\n", new String(outReader.toByteArray())); } public void testSyntheticExterns() { externs = ImmutableList.of( SourceFile.fromCode("externs", "myVar.property;")); test("var theirVar = {}; var myVar = {}; var yourVar = {};", VarCheck.UNDEFINED_EXTERN_VAR_ERROR); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var yourVar = {};", "var theirVar={},myVar={},yourVar={};"); args.add("--jscomp_off=externsValidation"); args.add("--warning_level=VERBOSE"); test("var theirVar = {}; var myVar = {}; var myVar = {};", VarCheck.VAR_MULTIPLY_DECLARED_ERROR); } public void testGoogAssertStripping() { args.add("--compilation_level=ADVANCED_OPTIMIZATIONS"); test("goog.asserts.assert(false)", ""); args.add("--debug"); test("goog.asserts.assert(false)", "goog.$asserts$.$assert$(!1)"); } public void testMissingReturnCheckOnWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @return {number} */ function f() {f()} f();", CheckMissingReturn.MISSING_RETURN_STATEMENT); } public void testGenerateExports() { args.add("--generate_exports=true"); test("/** @export */ foo.prototype.x = function() {};", "foo.prototype.x=function(){};"+ "goog.exportSymbol(\"foo.prototype.x\",foo.prototype.x);"); } public void testDepreciationWithVerbose() { args.add("--warning_level=VERBOSE"); test("/** @deprecated */ function f() {}; f()", CheckAccessControls.DEPRECATED_NAME); } public void testTwoParseErrors() { // If parse errors are reported in different files, make // sure all of them are reported. Compiler compiler = compile(new String[] { "var a b;", "var b c;" }); assertEquals(2, compiler.getErrors().length); } public void testES3ByDefault() { useStringComparison = true; test( "var x = f.function", "var x=f[\"function\"];", RhinoErrorReporter.INVALID_ES3_PROP_NAME); } public void testES5ChecksByDefault() { testSame("var x = 3; delete x;"); } public void testES5ChecksInVerbose() { args.add("--warning_level=VERBOSE"); test("function f(x) { delete x; }", StrictModeCheck.DELETE_VARIABLE); } public void testES5() { args.add("--language_in=ECMASCRIPT5"); test("var x = f.function", "var x = f.function"); test("var let", "var let"); } public void testES5Strict() { args.add("--language_in=ECMASCRIPT5_STRICT"); test("var x = f.function", "'use strict';var x = f.function"); test("var let", RhinoErrorReporter.PARSE_ERROR); test("function f(x) { delete x; }", StrictModeCheck.DELETE_VARIABLE); } public void testES5StrictUseStrict() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); } public void testES5StrictUseStrictMultipleInputs() { args.add("--language_in=ECMASCRIPT5_STRICT"); Compiler compiler = compile(new String[] {"var x = f.function", "var y = f.function", "var z = f.function"}); String outputSource = compiler.toSource(); assertEquals("'use strict'", outputSource.substring(0, 12)); assertEquals(outputSource.substring(13).indexOf("'use strict'"), -1); } public void testWithKeywordDefault() { test("var x = {}; with (x) {}", ControlStructureCheck.USE_OF_WITH); } public void testWithKeywordWithEs5ChecksOff() { args.add("--jscomp_off=es5Strict"); testSame("var x = {}; with (x) {}"); } public void testNoSrCFilesWithManifest() throws IOException { args.add("--use_only_custom_externs=true"); args.add("--output_manifest=test.MF"); CommandLineRunner runner = createCommandLineRunner(new String[0]); String expectedMessage = ""; try { runner.doRun(); } catch (FlagUsageException e) { expectedMessage = e.getMessage(); } assertEquals(expectedMessage, "Bad --js flag. " + "Manifest files cannot be generated when the input is from stdin."); } public void testTransformAMD() { args.add("--transform_amd_modules"); test("define({test: 1})", "exports = {test: 1}"); } public void testProcessCJS() { useStringComparison = true; args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); setFilename(0, "foo/bar.js"); String expected = "var module$foo$bar={test:1};"; test("exports.test = 1", expected); assertEquals(expected + "\n", outReader.toString()); } public void testProcessCJSWithModuleOutput() { useStringComparison = true; args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); args.add("--module=auto"); setFilename(0, "foo/bar.js"); test("exports.test = 1", "var module$foo$bar={test:1};"); // With modules=auto no direct output is created. assertEquals("", outReader.toString()); } public void testFormattingSingleQuote() { testSame("var x = '';"); assertEquals("var x=\"\";", lastCompiler.toSource()); args.add("--formatting=SINGLE_QUOTES"); testSame("var x = '';"); assertEquals("var x='';", lastCompiler.toSource()); } public void testTransformAMDAndProcessCJS() { useStringComparison = true; args.add("--transform_amd_modules"); args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); setFilename(0, "foo/bar.js"); test("define({foo: 1})", "var module$foo$bar={},module$foo$bar={foo:1};"); } public void testModuleJSON() { useStringComparison = true; args.add("--transform_amd_modules"); args.add("--process_common_js_modules"); args.add("--common_js_entry_module=foo/bar"); args.add("--output_module_dependencies=test.json"); setFilename(0, "foo/bar.js"); test("define({foo: 1})", "var module$foo$bar={},module$foo$bar={foo:1};"); } public void testOutputSameAsInput() { args.add("--js_output_file=" + getFilename(0)); test("", AbstractCommandLineRunner.OUTPUT_SAME_AS_INPUT_ERROR); } /* 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) { test(original, compiled, null); } /** * Asserts that when compiling with the given compiler options, * {@code original} is transformed into {@code compiled}. * If {@code warning} is non-null, we will also check if the given * warning type was emitted. */ private void test(String[] original, String[] compiled, DiagnosticType warning) { Compiler compiler = compile(original); if (warning == null) { 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); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); } 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); } private void test(String original, String expected, DiagnosticType warning) { test(new String[] { original }, new String[] { expected }, 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); assertTrue(exitCodes.size() > 0); int lastExitCode = exitCodes.get(exitCodes.size() - 1); if (compiler.getErrors().length > 0) { assertEquals(1, compiler.getErrors().length); assertEquals(warning, compiler.getErrors()[0].getType()); assertEquals(1, lastExitCode); } else { assertEquals(1, compiler.getWarnings().length); assertEquals(warning, compiler.getWarnings()[0].getType()); assertEquals(0, lastExitCode); } } private CommandLineRunner createCommandLineRunner(String[] original) { for (int i = 0; i < original.length; i++) { args.add("--js"); args.add("/path/to/input" + i + ".js"); if (useModules == ModulePattern.CHAIN) { args.add("--module"); args.add("m" + i + ":1" + (i > 0 ? (":m" + (i - 1)) : "")); } else if (useModules == ModulePattern.STAR) { args.add("--module"); args.add("m" + i + ":1" + (i > 0 ? ":m0" : "")); } } if (lastArg != null) { args.add(lastArg); } String[] argStrings = args.toArray(new String[] {}); return new CommandLineRunner( argStrings, new PrintStream(outReader), new PrintStream(errReader)); } private Compiler compile(String[] original) { CommandLineRunner runner = createCommandLineRunner(original); assertTrue(new String(errReader.toByteArray()), runner.shouldRunCompiler()); Supplier<List<SourceFile>> inputsSupplier = null; Supplier<List<JSModule>> modulesSupplier = null; if (useModules == ModulePattern.NONE) { List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode(getFilename(i), original[i])); } inputsSupplier = Suppliers.ofInstance(inputs); } else if (useModules == ModulePattern.STAR) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleStar(original))); } else if (useModules == ModulePattern.CHAIN) { modulesSupplier = Suppliers.<List<JSModule>>ofInstance( Lists.<JSModule>newArrayList( CompilerTestCase.createModuleChain(original))); } else { throw new IllegalArgumentException("Unknown module type: " + useModules); } runner.enableTestMode( Suppliers.<List<SourceFile>>ofInstance(externs), inputsSupplier, modulesSupplier, new Function<Integer, Boolean>() { @Override public Boolean apply(Integer code) { return exitCodes.add(code); } }); runner.run(); lastCompiler = runner.getCompiler(); lastCommandLineRunner = runner; return lastCompiler; } private Node parse(String[] original) { String[] argStrings = args.toArray(new String[] {}); CommandLineRunner runner = new CommandLineRunner(argStrings); Compiler compiler = runner.createCompiler(); List<SourceFile> inputs = Lists.newArrayList(); for (int i = 0; i < original.length; i++) { inputs.add(SourceFile.fromCode(getFilename(i), original[i])); } CompilerOptions options = new CompilerOptions(); // ECMASCRIPT5 is the most forgiving. options.setLanguageIn(LanguageMode.ECMASCRIPT5); compiler.init(externs, inputs, options); Node all = compiler.parseInputs(); Preconditions.checkState(compiler.getErrorCount() == 0); Preconditions.checkNotNull(all); Node n = all.getLastChild(); return n; } private void setFilename(int i, String filename) { this.filenames.put(i, filename); } private String getFilename(int i) { if (filenames.isEmpty()) { return "input" + i; } return filenames.get(i); } }
public void testDateFormatConfig() throws Exception { ObjectMapper mapper = new ObjectMapper(); TimeZone tz1 = TimeZone.getTimeZone("America/Los_Angeles"); TimeZone tz2 = TimeZone.getTimeZone("Central Standard Time"); // sanity checks assertEquals(tz1, tz1); assertEquals(tz2, tz2); if (tz1.equals(tz2)) { fail(); } mapper.setTimeZone(tz1); assertEquals(tz1, mapper.getSerializationConfig().getTimeZone()); assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone()); // also better stick via reader/writer as well assertEquals(tz1, mapper.writer().getConfig().getTimeZone()); assertEquals(tz1, mapper.reader().getConfig().getTimeZone()); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); f.setTimeZone(tz2); mapper.setDateFormat(f); // should not change the timezone tho assertEquals(tz1, mapper.getSerializationConfig().getTimeZone()); assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone()); assertEquals(tz1, mapper.writer().getConfig().getTimeZone()); assertEquals(tz1, mapper.reader().getConfig().getTimeZone()); }
com.fasterxml.jackson.databind.ser.TestConfig::testDateFormatConfig
src/test/java/com/fasterxml/jackson/databind/ser/TestConfig.java
224
src/test/java/com/fasterxml/jackson/databind/ser/TestConfig.java
testDateFormatConfig
package com.fasterxml.jackson.databind.ser; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.introspect.ClassIntrospector; /** * Unit tests for checking handling of SerializationConfig. */ public class TestConfig extends BaseMapTest { /* /********************************************************** /* Helper beans /********************************************************** */ @JsonInclude(JsonInclude.Include.NON_DEFAULT) @JsonSerialize(typing=JsonSerialize.Typing.STATIC) final static class Config { } final static class ConfigNone { } static class AnnoBean { public int getX() { return 1; } @JsonProperty("y") private int getY() { return 2; } } static class Indentable { public int a = 3; } public static class SimpleBean { public int x = 1; } /* /********************************************************** /* Main tests /********************************************************** */ final static ObjectMapper MAPPER = new ObjectMapper(); /* Test to verify that we don't overflow number of features; if we * hit the limit, need to change implementation -- this test just * gives low-water mark */ public void testEnumIndexes() { int max = 0; for (SerializationFeature f : SerializationFeature.values()) { max = Math.max(max, f.ordinal()); } if (max >= 31) { // 31 is actually ok; 32 not fail("Max number of SerializationFeature enums reached: "+max); } } public void testDefaults() { SerializationConfig cfg = MAPPER.getSerializationConfig(); // First, defaults: assertTrue(cfg.isEnabled(MapperFeature.USE_ANNOTATIONS)); assertTrue(cfg.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertTrue(cfg.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)); assertTrue(cfg.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)); assertFalse(cfg.isEnabled(SerializationFeature.INDENT_OUTPUT)); assertFalse(cfg.isEnabled(MapperFeature.USE_STATIC_TYPING)); // since 1.3: assertTrue(cfg.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)); // since 1.4 assertTrue(cfg.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); // since 1.5 assertTrue(cfg.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); } public void testOverrideIntrospectors() { SerializationConfig cfg = MAPPER.getSerializationConfig(); // and finally, ensure we could override introspectors cfg = cfg.with((ClassIntrospector) null); // no way to verify tho cfg = cfg.with((AnnotationIntrospector) null); assertNull(cfg.getAnnotationIntrospector()); } public void testMisc() { ObjectMapper m = new ObjectMapper(); m.setDateFormat(null); // just to execute the code path assertNotNull(m.getSerializationConfig().toString()); // ditto } public void testIndentation() throws Exception { Map<String,Integer> map = new HashMap<String,Integer>(); map.put("a", Integer.valueOf(2)); String result = MAPPER.writer().with(SerializationFeature.INDENT_OUTPUT) .writeValueAsString(map); // 02-Jun-2009, tatu: not really a clean way but... String lf = getLF(); assertEquals("{"+lf+" \"a\" : 2"+lf+"}", result); } public void testAnnotationsDisabled() throws Exception { // first: verify that annotation introspection is enabled by default assertTrue(MAPPER.isEnabled(MapperFeature.USE_ANNOTATIONS)); Map<String,Object> result = writeAndMap(MAPPER, new AnnoBean()); assertEquals(2, result.size()); ObjectMapper m2 = new ObjectMapper(); m2.configure(MapperFeature.USE_ANNOTATIONS, false); result = writeAndMap(m2, new AnnoBean()); assertEquals(1, result.size()); } /** * Test for verifying working of [JACKSON-191] */ public void testProviderConfig() throws Exception { ObjectMapper mapper = new ObjectMapper(); DefaultSerializerProvider prov = (DefaultSerializerProvider) mapper.getSerializerProvider(); assertEquals(0, prov.cachedSerializersCount()); // and then should get one constructed for: Map<String,Object> result = this.writeAndMap(mapper, new AnnoBean()); assertEquals(2, result.size()); assertEquals(Integer.valueOf(1), result.get("x")); assertEquals(Integer.valueOf(2), result.get("y")); /* Note: it is 2 because we'll also get serializer for basic 'int', not * just AnnoBean */ /* 12-Jan-2010, tatus: Actually, probably more, if and when we typing * aspects are considered (depending on what is cached) */ int count = prov.cachedSerializersCount(); if (count < 2) { fail("Should have at least 2 cached serializers, got "+count); } prov.flushCachedSerializers(); assertEquals(0, prov.cachedSerializersCount()); } // Test for [Issue#12] public void testIndentWithPassedGenerator() throws Exception { Indentable input = new Indentable(); assertEquals("{\"a\":3}", MAPPER.writeValueAsString(input)); String LF = getLF(); String INDENTED = "{"+LF+" \"a\" : 3"+LF+"}"; final ObjectWriter indentWriter = MAPPER.writer().with(SerializationFeature.INDENT_OUTPUT); assertEquals(INDENTED, indentWriter.writeValueAsString(input)); // [Issue#12] StringWriter sw = new StringWriter(); JsonGenerator jgen = MAPPER.getFactory().createGenerator(sw); indentWriter.writeValue(jgen, input); jgen.close(); assertEquals(INDENTED, sw.toString()); // and also with ObjectMapper itself sw = new StringWriter(); ObjectMapper m2 = new ObjectMapper(); m2.enable(SerializationFeature.INDENT_OUTPUT); jgen = m2.getFactory().createGenerator(sw); m2.writeValue(jgen, input); jgen.close(); assertEquals(INDENTED, sw.toString()); } public void testNoAccessOverrides() throws Exception { ObjectMapper m = new ObjectMapper(); m.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); assertEquals("{\"x\":1}", m.writeValueAsString(new SimpleBean())); } public void testDateFormatConfig() throws Exception { ObjectMapper mapper = new ObjectMapper(); TimeZone tz1 = TimeZone.getTimeZone("America/Los_Angeles"); TimeZone tz2 = TimeZone.getTimeZone("Central Standard Time"); // sanity checks assertEquals(tz1, tz1); assertEquals(tz2, tz2); if (tz1.equals(tz2)) { fail(); } mapper.setTimeZone(tz1); assertEquals(tz1, mapper.getSerializationConfig().getTimeZone()); assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone()); // also better stick via reader/writer as well assertEquals(tz1, mapper.writer().getConfig().getTimeZone()); assertEquals(tz1, mapper.reader().getConfig().getTimeZone()); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); f.setTimeZone(tz2); mapper.setDateFormat(f); // should not change the timezone tho assertEquals(tz1, mapper.getSerializationConfig().getTimeZone()); assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone()); assertEquals(tz1, mapper.writer().getConfig().getTimeZone()); assertEquals(tz1, mapper.reader().getConfig().getTimeZone()); } private final static String getLF() { return System.getProperty("line.separator"); } }
// You are a professional Java test case writer, please create a test case named `testDateFormatConfig` for the issue `JacksonDatabind-889`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-889 // // ## Issue-Title: // Configuring an ObjectMapper's DateFormat changes time zone when serialising Joda DateTime // // ## Issue-Description: // The serialisation of Joda `DateTime` instances behaves differently in 2.6.0 vs 2.5.4 when the `ObjectMapper`'s had its `DateFormat` configured. The behaviour change is illustrated by the following code: // // // // ``` // public static void main(String[] args) throws JsonProcessingException { // System.out.println(createObjectMapper() // .writeValueAsString(new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC))); // } // // private static ObjectMapper createObjectMapper() { // ObjectMapper mapper = new ObjectMapper(); // mapper.registerModule(createJodaModule()); // mapper.configure(SerializationFeature.WRITE\_DATES\_AS\_TIMESTAMPS, false); // System.out.println(mapper.getSerializationConfig().getTimeZone()); // mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // System.out.println(mapper.getSerializationConfig().getTimeZone()); // return mapper; // } // // private static SimpleModule createJodaModule() { // SimpleModule module = new SimpleModule(); // module.addSerializer(DateTime.class, new DateTimeSerializer( // new JacksonJodaDateFormat(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") // .withZoneUTC()))); // return module; // } // ``` // // When run with Jackson 2.5.4 the output is: // // // // ``` // sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] // sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] // "1988-06-25 20:30:00" // // ``` // // When run with Jackson 2.6.0 the output is: // // // // ``` // sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] // sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]] // "1988-06-25 21:30:00" // // ``` // // It looks like the fix for [#824](https://github.com/FasterXML/jackson-databind/issues/824) is the cause. In 2.6, the call to `mapper.setDateFormat` causes the `ObjectMapper`'s time zone to be set to the JVM's default time zone. In 2.5.x, calling `mapper.setDateFormat` has no effect on its time zone. // // // // public void testDateFormatConfig() throws Exception {
224
24
194
src/test/java/com/fasterxml/jackson/databind/ser/TestConfig.java
src/test/java
```markdown ## Issue-ID: JacksonDatabind-889 ## Issue-Title: Configuring an ObjectMapper's DateFormat changes time zone when serialising Joda DateTime ## Issue-Description: The serialisation of Joda `DateTime` instances behaves differently in 2.6.0 vs 2.5.4 when the `ObjectMapper`'s had its `DateFormat` configured. The behaviour change is illustrated by the following code: ``` public static void main(String[] args) throws JsonProcessingException { System.out.println(createObjectMapper() .writeValueAsString(new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC))); } private static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(createJodaModule()); mapper.configure(SerializationFeature.WRITE\_DATES\_AS\_TIMESTAMPS, false); System.out.println(mapper.getSerializationConfig().getTimeZone()); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); System.out.println(mapper.getSerializationConfig().getTimeZone()); return mapper; } private static SimpleModule createJodaModule() { SimpleModule module = new SimpleModule(); module.addSerializer(DateTime.class, new DateTimeSerializer( new JacksonJodaDateFormat(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") .withZoneUTC()))); return module; } ``` When run with Jackson 2.5.4 the output is: ``` sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] "1988-06-25 20:30:00" ``` When run with Jackson 2.6.0 the output is: ``` sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]] "1988-06-25 21:30:00" ``` It looks like the fix for [#824](https://github.com/FasterXML/jackson-databind/issues/824) is the cause. In 2.6, the call to `mapper.setDateFormat` causes the `ObjectMapper`'s time zone to be set to the JVM's default time zone. In 2.5.x, calling `mapper.setDateFormat` has no effect on its time zone. ``` You are a professional Java test case writer, please create a test case named `testDateFormatConfig` for the issue `JacksonDatabind-889`, utilizing the provided issue report information and the following function signature. ```java public void testDateFormatConfig() throws Exception { ```
194
[ "com.fasterxml.jackson.databind.cfg.BaseSettings" ]
e6623ad4cfc6a3e680bca00438de1240b149b519fcf0785b9f3c8cc91b13f658
public void testDateFormatConfig() throws Exception
// You are a professional Java test case writer, please create a test case named `testDateFormatConfig` for the issue `JacksonDatabind-889`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: JacksonDatabind-889 // // ## Issue-Title: // Configuring an ObjectMapper's DateFormat changes time zone when serialising Joda DateTime // // ## Issue-Description: // The serialisation of Joda `DateTime` instances behaves differently in 2.6.0 vs 2.5.4 when the `ObjectMapper`'s had its `DateFormat` configured. The behaviour change is illustrated by the following code: // // // // ``` // public static void main(String[] args) throws JsonProcessingException { // System.out.println(createObjectMapper() // .writeValueAsString(new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC))); // } // // private static ObjectMapper createObjectMapper() { // ObjectMapper mapper = new ObjectMapper(); // mapper.registerModule(createJodaModule()); // mapper.configure(SerializationFeature.WRITE\_DATES\_AS\_TIMESTAMPS, false); // System.out.println(mapper.getSerializationConfig().getTimeZone()); // mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // System.out.println(mapper.getSerializationConfig().getTimeZone()); // return mapper; // } // // private static SimpleModule createJodaModule() { // SimpleModule module = new SimpleModule(); // module.addSerializer(DateTime.class, new DateTimeSerializer( // new JacksonJodaDateFormat(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") // .withZoneUTC()))); // return module; // } // ``` // // When run with Jackson 2.5.4 the output is: // // // // ``` // sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] // sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] // "1988-06-25 20:30:00" // // ``` // // When run with Jackson 2.6.0 the output is: // // // // ``` // sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] // sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]] // "1988-06-25 21:30:00" // // ``` // // It looks like the fix for [#824](https://github.com/FasterXML/jackson-databind/issues/824) is the cause. In 2.6, the call to `mapper.setDateFormat` causes the `ObjectMapper`'s time zone to be set to the JVM's default time zone. In 2.5.x, calling `mapper.setDateFormat` has no effect on its time zone. // // // //
JacksonDatabind
package com.fasterxml.jackson.databind.ser; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.introspect.ClassIntrospector; /** * Unit tests for checking handling of SerializationConfig. */ public class TestConfig extends BaseMapTest { /* /********************************************************** /* Helper beans /********************************************************** */ @JsonInclude(JsonInclude.Include.NON_DEFAULT) @JsonSerialize(typing=JsonSerialize.Typing.STATIC) final static class Config { } final static class ConfigNone { } static class AnnoBean { public int getX() { return 1; } @JsonProperty("y") private int getY() { return 2; } } static class Indentable { public int a = 3; } public static class SimpleBean { public int x = 1; } /* /********************************************************** /* Main tests /********************************************************** */ final static ObjectMapper MAPPER = new ObjectMapper(); /* Test to verify that we don't overflow number of features; if we * hit the limit, need to change implementation -- this test just * gives low-water mark */ public void testEnumIndexes() { int max = 0; for (SerializationFeature f : SerializationFeature.values()) { max = Math.max(max, f.ordinal()); } if (max >= 31) { // 31 is actually ok; 32 not fail("Max number of SerializationFeature enums reached: "+max); } } public void testDefaults() { SerializationConfig cfg = MAPPER.getSerializationConfig(); // First, defaults: assertTrue(cfg.isEnabled(MapperFeature.USE_ANNOTATIONS)); assertTrue(cfg.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertTrue(cfg.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)); assertTrue(cfg.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)); assertFalse(cfg.isEnabled(SerializationFeature.INDENT_OUTPUT)); assertFalse(cfg.isEnabled(MapperFeature.USE_STATIC_TYPING)); // since 1.3: assertTrue(cfg.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)); // since 1.4 assertTrue(cfg.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); // since 1.5 assertTrue(cfg.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); } public void testOverrideIntrospectors() { SerializationConfig cfg = MAPPER.getSerializationConfig(); // and finally, ensure we could override introspectors cfg = cfg.with((ClassIntrospector) null); // no way to verify tho cfg = cfg.with((AnnotationIntrospector) null); assertNull(cfg.getAnnotationIntrospector()); } public void testMisc() { ObjectMapper m = new ObjectMapper(); m.setDateFormat(null); // just to execute the code path assertNotNull(m.getSerializationConfig().toString()); // ditto } public void testIndentation() throws Exception { Map<String,Integer> map = new HashMap<String,Integer>(); map.put("a", Integer.valueOf(2)); String result = MAPPER.writer().with(SerializationFeature.INDENT_OUTPUT) .writeValueAsString(map); // 02-Jun-2009, tatu: not really a clean way but... String lf = getLF(); assertEquals("{"+lf+" \"a\" : 2"+lf+"}", result); } public void testAnnotationsDisabled() throws Exception { // first: verify that annotation introspection is enabled by default assertTrue(MAPPER.isEnabled(MapperFeature.USE_ANNOTATIONS)); Map<String,Object> result = writeAndMap(MAPPER, new AnnoBean()); assertEquals(2, result.size()); ObjectMapper m2 = new ObjectMapper(); m2.configure(MapperFeature.USE_ANNOTATIONS, false); result = writeAndMap(m2, new AnnoBean()); assertEquals(1, result.size()); } /** * Test for verifying working of [JACKSON-191] */ public void testProviderConfig() throws Exception { ObjectMapper mapper = new ObjectMapper(); DefaultSerializerProvider prov = (DefaultSerializerProvider) mapper.getSerializerProvider(); assertEquals(0, prov.cachedSerializersCount()); // and then should get one constructed for: Map<String,Object> result = this.writeAndMap(mapper, new AnnoBean()); assertEquals(2, result.size()); assertEquals(Integer.valueOf(1), result.get("x")); assertEquals(Integer.valueOf(2), result.get("y")); /* Note: it is 2 because we'll also get serializer for basic 'int', not * just AnnoBean */ /* 12-Jan-2010, tatus: Actually, probably more, if and when we typing * aspects are considered (depending on what is cached) */ int count = prov.cachedSerializersCount(); if (count < 2) { fail("Should have at least 2 cached serializers, got "+count); } prov.flushCachedSerializers(); assertEquals(0, prov.cachedSerializersCount()); } // Test for [Issue#12] public void testIndentWithPassedGenerator() throws Exception { Indentable input = new Indentable(); assertEquals("{\"a\":3}", MAPPER.writeValueAsString(input)); String LF = getLF(); String INDENTED = "{"+LF+" \"a\" : 3"+LF+"}"; final ObjectWriter indentWriter = MAPPER.writer().with(SerializationFeature.INDENT_OUTPUT); assertEquals(INDENTED, indentWriter.writeValueAsString(input)); // [Issue#12] StringWriter sw = new StringWriter(); JsonGenerator jgen = MAPPER.getFactory().createGenerator(sw); indentWriter.writeValue(jgen, input); jgen.close(); assertEquals(INDENTED, sw.toString()); // and also with ObjectMapper itself sw = new StringWriter(); ObjectMapper m2 = new ObjectMapper(); m2.enable(SerializationFeature.INDENT_OUTPUT); jgen = m2.getFactory().createGenerator(sw); m2.writeValue(jgen, input); jgen.close(); assertEquals(INDENTED, sw.toString()); } public void testNoAccessOverrides() throws Exception { ObjectMapper m = new ObjectMapper(); m.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); assertEquals("{\"x\":1}", m.writeValueAsString(new SimpleBean())); } public void testDateFormatConfig() throws Exception { ObjectMapper mapper = new ObjectMapper(); TimeZone tz1 = TimeZone.getTimeZone("America/Los_Angeles"); TimeZone tz2 = TimeZone.getTimeZone("Central Standard Time"); // sanity checks assertEquals(tz1, tz1); assertEquals(tz2, tz2); if (tz1.equals(tz2)) { fail(); } mapper.setTimeZone(tz1); assertEquals(tz1, mapper.getSerializationConfig().getTimeZone()); assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone()); // also better stick via reader/writer as well assertEquals(tz1, mapper.writer().getConfig().getTimeZone()); assertEquals(tz1, mapper.reader().getConfig().getTimeZone()); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); f.setTimeZone(tz2); mapper.setDateFormat(f); // should not change the timezone tho assertEquals(tz1, mapper.getSerializationConfig().getTimeZone()); assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone()); assertEquals(tz1, mapper.writer().getConfig().getTimeZone()); assertEquals(tz1, mapper.reader().getConfig().getTimeZone()); } private final static String getLF() { return System.getProperty("line.separator"); } }
public void testParseInto_monthDay_feb29_newYork_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, NEWYORK), result); }
org.joda.time.format.TestDateTimeFormatter::testParseInto_monthDay_feb29_newYork_startOfYear
src/test/java/org/joda/time/format/TestDateTimeFormatter.java
933
src/test/java/org/joda/time/format/TestDateTimeFormatter.java
testParseInto_monthDay_feb29_newYork_startOfYear
/* * Copyright 2001-2011 Stephen Colebourne * * 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 org.joda.time.format; import java.io.CharArrayWriter; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; import org.joda.time.MutableDateTime; import org.joda.time.ReadablePartial; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for DateTime Formating. * * @author Stephen Colebourne */ public class TestDateTimeFormatter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final DateTimeZone NEWYORK = DateTimeZone.forID("America/New_York"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; private DateTimeFormatter f = null; private DateTimeFormatter g = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFormatter.class); } public TestDateTimeFormatter(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); f = new DateTimeFormatterBuilder() .appendDayOfWeekShortText() .appendLiteral(' ') .append(ISODateTimeFormat.dateTimeNoMillis()) .toFormatter(); g = ISODateTimeFormat.dateTimeNoMillis(); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; f = null; g = null; } //----------------------------------------------------------------------- public void testPrint_simple() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T10:20:30Z", f.print(dt)); dt = dt.withZone(PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.print(dt)); } //----------------------------------------------------------------------- public void testPrint_locale() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("mer. 2004-06-09T10:20:30Z", f.withLocale(Locale.FRENCH).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withLocale(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_zone() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withZone(null).print(dt)); dt = dt.withZone(NEWYORK); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withZoneUTC().print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_chrono() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(BUDDHIST_PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(null).print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(BUDDHIST_PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(ISO_UTC).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_bufferMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); StringBuffer buf = new StringBuffer(); f.printTo(buf, dt); assertEquals("Wed 2004-06-09T10:20:30Z", buf.toString()); buf = new StringBuffer(); f.printTo(buf, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", buf.toString()); buf = new StringBuffer(); ISODateTimeFormat.yearMonthDay().printTo(buf, dt.toYearMonthDay()); assertEquals("2004-06-09", buf.toString()); buf = new StringBuffer(); try { ISODateTimeFormat.yearMonthDay().printTo(buf, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_writerMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); CharArrayWriter out = new CharArrayWriter(); f.printTo(out, dt); assertEquals("Wed 2004-06-09T10:20:30Z", out.toString()); out = new CharArrayWriter(); f.printTo(out, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", out.toString()); out = new CharArrayWriter(); ISODateTimeFormat.yearMonthDay().printTo(out, dt.toYearMonthDay()); assertEquals("2004-06-09", out.toString()); out = new CharArrayWriter(); try { ISODateTimeFormat.yearMonthDay().printTo(out, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_appendableMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); StringBuilder buf = new StringBuilder(); f.printTo(buf, dt); assertEquals("Wed 2004-06-09T10:20:30Z", buf.toString()); buf = new StringBuilder(); f.printTo(buf, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", buf.toString()); buf = new StringBuilder(); ISODateTimeFormat.yearMonthDay().printTo(buf, dt.toLocalDate()); assertEquals("2004-06-09", buf.toString()); buf = new StringBuilder(); try { ISODateTimeFormat.yearMonthDay().printTo(buf, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_chrono_and_zone() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); dt = dt.withChronology(ISO_PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2547-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); } public void testWithGetLocale() { DateTimeFormatter f2 = f.withLocale(Locale.FRENCH); assertEquals(Locale.FRENCH, f2.getLocale()); assertSame(f2, f2.withLocale(Locale.FRENCH)); f2 = f.withLocale(null); assertEquals(null, f2.getLocale()); assertSame(f2, f2.withLocale(null)); } public void testWithGetZone() { DateTimeFormatter f2 = f.withZone(PARIS); assertEquals(PARIS, f2.getZone()); assertSame(f2, f2.withZone(PARIS)); f2 = f.withZone(null); assertEquals(null, f2.getZone()); assertSame(f2, f2.withZone(null)); } public void testWithGetChronology() { DateTimeFormatter f2 = f.withChronology(BUDDHIST_PARIS); assertEquals(BUDDHIST_PARIS, f2.getChronology()); assertSame(f2, f2.withChronology(BUDDHIST_PARIS)); f2 = f.withChronology(null); assertEquals(null, f2.getChronology()); assertSame(f2, f2.withChronology(null)); } public void testWithGetPivotYear() { DateTimeFormatter f2 = f.withPivotYear(13); assertEquals(new Integer(13), f2.getPivotYear()); assertSame(f2, f2.withPivotYear(13)); f2 = f.withPivotYear(new Integer(14)); assertEquals(new Integer(14), f2.getPivotYear()); assertSame(f2, f2.withPivotYear(new Integer(14))); f2 = f.withPivotYear(null); assertEquals(null, f2.getPivotYear()); assertSame(f2, f2.withPivotYear(null)); } public void testWithGetOffsetParsedMethods() { DateTimeFormatter f2 = f; assertEquals(false, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f.withOffsetParsed(); assertEquals(true, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f2.withZone(PARIS); assertEquals(false, f2.isOffsetParsed()); assertEquals(PARIS, f2.getZone()); f2 = f2.withOffsetParsed(); assertEquals(true, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f.withOffsetParsed(); assertNotSame(f, f2); DateTimeFormatter f3 = f2.withOffsetParsed(); assertSame(f2, f3); } public void testPrinterParserMethods() { DateTimeFormatter f2 = new DateTimeFormatter(f.getPrinter(), f.getParser()); assertEquals(f.getPrinter(), f2.getPrinter()); assertEquals(f.getParser(), f2.getParser()); assertEquals(true, f2.isPrinter()); assertEquals(true, f2.isParser()); assertNotNull(f2.print(0L)); assertNotNull(f2.parseDateTime("Thu 1970-01-01T00:00:00Z")); f2 = new DateTimeFormatter(f.getPrinter(), null); assertEquals(f.getPrinter(), f2.getPrinter()); assertEquals(null, f2.getParser()); assertEquals(true, f2.isPrinter()); assertEquals(false, f2.isParser()); assertNotNull(f2.print(0L)); try { f2.parseDateTime("Thu 1970-01-01T00:00:00Z"); fail(); } catch (UnsupportedOperationException ex) {} f2 = new DateTimeFormatter(null, f.getParser()); assertEquals(null, f2.getPrinter()); assertEquals(f.getParser(), f2.getParser()); assertEquals(false, f2.isPrinter()); assertEquals(true, f2.isParser()); try { f2.print(0L); fail(); } catch (UnsupportedOperationException ex) {} assertNotNull(f2.parseDateTime("Thu 1970-01-01T00:00:00Z")); } //----------------------------------------------------------------------- public void testParseLocalDate_simple() { assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30Z")); assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30+18:00")); assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30-18:00")); assertEquals(new LocalDate(2004, 6, 9, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalDate("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseLocalDate_yearOfEra() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("YYYY-MM GG") .withChronology(chrono) .withLocale(Locale.UK); LocalDate date = new LocalDate(2005, 10, 1, chrono); assertEquals(date, f.parseLocalDate("2005-10 AD")); assertEquals(date, f.parseLocalDate("2005-10 CE")); date = new LocalDate(-2005, 10, 1, chrono); assertEquals(date, f.parseLocalDate("2005-10 BC")); assertEquals(date, f.parseLocalDate("2005-10 BCE")); } public void testParseLocalDate_yearOfCentury() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("yy M d") .withChronology(chrono) .withLocale(Locale.UK) .withPivotYear(2050); LocalDate date = new LocalDate(2050, 8, 4, chrono); assertEquals(date, f.parseLocalDate("50 8 4")); } public void testParseLocalDate_monthDay_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d") .withChronology(chrono) .withLocale(Locale.UK); assertEquals(new LocalDate(2000, 2, 29, chrono), f.parseLocalDate("2 29")); } public void testParseLocalDate_monthDay_withDefaultYear_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d") .withChronology(chrono) .withLocale(Locale.UK) .withDefaultYear(2012); assertEquals(new LocalDate(2012, 2, 29, chrono), f.parseLocalDate("2 29")); } public void testParseLocalDate_weekyear_month_week_2010() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2010, 1, 4, chrono), f.parseLocalDate("2010-01-01")); } public void testParseLocalDate_weekyear_month_week_2011() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2011, 1, 3, chrono), f.parseLocalDate("2011-01-01")); } public void testParseLocalDate_weekyear_month_week_2012() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 1, 2, chrono), f.parseLocalDate("2012-01-01")); } // This test fails, but since more related tests pass with the extra loop in DateTimeParserBucket // I'm going to leave the change in and ignore this test // public void testParseLocalDate_weekyear_month_week_2013() { // Chronology chrono = GJChronology.getInstanceUTC(); // DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); // assertEquals(new LocalDate(2012, 12, 31, chrono), f.parseLocalDate("2013-01-01")); // } public void testParseLocalDate_year_month_week_2010() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2010, 1, 4, chrono), f.parseLocalDate("2010-01-01")); } public void testParseLocalDate_year_month_week_2011() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2011, 1, 3, chrono), f.parseLocalDate("2011-01-01")); } public void testParseLocalDate_year_month_week_2012() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 1, 2, chrono), f.parseLocalDate("2012-01-01")); } public void testParseLocalDate_year_month_week_2013() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 12, 31, chrono), f.parseLocalDate("2013-01-01")); // 2013-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2014() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2013, 12, 30, chrono), f.parseLocalDate("2014-01-01")); // 2014-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2015() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2014, 12, 29, chrono), f.parseLocalDate("2015-01-01")); // 2015-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2016() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2016, 1, 4, chrono), f.parseLocalDate("2016-01-01")); } //----------------------------------------------------------------------- public void testParseLocalTime_simple() { assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30Z")); assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30+18:00")); assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30-18:00")); assertEquals(new LocalTime(10, 20, 30, 0, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseLocalDateTime_simple() { assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30Z")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30+18:00")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30-18:00")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30, 0, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalDateTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseLocalDateTime_monthDay_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d H m") .withChronology(chrono) .withLocale(Locale.UK); assertEquals(new LocalDateTime(2000, 2, 29, 13, 40, 0, 0, chrono), f.parseLocalDateTime("2 29 13 40")); } public void testParseLocalDateTime_monthDay_withDefaultYear_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d H m") .withChronology(chrono) .withLocale(Locale.UK) .withDefaultYear(2012); assertEquals(new LocalDateTime(2012, 2, 29, 13, 40, 0, 0, chrono), f.parseLocalDateTime("2 29 13 40")); } //----------------------------------------------------------------------- public void testParseDateTime_simple() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.parseDateTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseDateTime_zone() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseDateTime("2004-06-09T10:20:30Z")); } public void testParseDateTime_zone2() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseDateTime("2004-06-09T06:20:30-04:00")); } public void testParseDateTime_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); DateTime expect = null; expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(LONDON).parseDateTime("2004-06-09T10:20:30")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(null).parseDateTime("2004-06-09T10:20:30")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); assertEquals(expect, h.withZone(PARIS).parseDateTime("2004-06-09T10:20:30")); } public void testParseDateTime_simple_precedence() { DateTime expect = null; // use correct day of week expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, f.parseDateTime("Wed 2004-06-09T10:20:30Z")); // use wrong day of week expect = new DateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); // DayOfWeek takes precedence, because week < month in length assertEquals(expect, f.parseDateTime("Mon 2004-06-09T10:20:30Z")); } public void testParseDateTime_offsetParsed() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withZone(PARIS).withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withOffsetParsed().withZone(PARIS).parseDateTime("2004-06-09T10:20:30Z")); } public void testParseDateTime_chrono() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withChronology(ISO_PARIS).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0,LONDON); assertEquals(expect, g.withChronology(null).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2547-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); // zone is +00:09:21 in 1451 assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2004-06-09T10:20:30Z")); } //----------------------------------------------------------------------- public void testParseMutableDateTime_simple() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.parseMutableDateTime("2004-06-09T10:20:30Z")); try { g.parseMutableDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseMutableDateTime_zone() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_zone2() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseMutableDateTime("2004-06-09T06:20:30-04:00")); } public void testParseMutableDateTime_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(LONDON).parseMutableDateTime("2004-06-09T10:20:30")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(null).parseMutableDateTime("2004-06-09T10:20:30")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); assertEquals(expect, h.withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30")); } public void testParseMutableDateTime_simple_precedence() { MutableDateTime expect = null; // use correct day of week expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, f.parseDateTime("Wed 2004-06-09T10:20:30Z")); // use wrong day of week expect = new MutableDateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); // DayOfWeek takes precedence, because week < month in length assertEquals(expect, f.parseDateTime("Mon 2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_offsetParsed() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withOffsetParsed().parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); assertEquals(expect, g.withOffsetParsed().parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withZone(PARIS).withOffsetParsed().parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withOffsetParsed().withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_chrono() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withChronology(ISO_PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0,LONDON); assertEquals(expect, g.withChronology(null).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseMutableDateTime("2547-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); // zone is +00:09:21 in 1451 assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } //----------------------------------------------------------------------- public void testParseInto_simple() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); MutableDateTime result = new MutableDateTime(0L); assertEquals(20, g.parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); try { g.parseInto(null, "2004-06-09T10:20:30Z", 0); fail(); } catch (IllegalArgumentException ex) {} assertEquals(~0, g.parseInto(result, "ABC", 0)); assertEquals(~10, g.parseInto(result, "2004-06-09", 0)); assertEquals(~13, g.parseInto(result, "XX2004-06-09T", 2)); } public void testParseInto_zone() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withZone(LONDON).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withZone(null).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withZone(PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_zone2() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(25, g.withZone(LONDON).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(25, g.withZone(null).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(25, g.withZone(PARIS).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); } public void testParseInto_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(19, h.withZone(LONDON).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(19, h.withZone(null).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(19, h.withZone(PARIS).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); } public void testParseInto_simple_precedence() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); // DayOfWeek takes precedence, because week < month in length assertEquals(24, f.parseInto(result, "Mon 2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_offsetParsed() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); result = new MutableDateTime(0L); assertEquals(20, g.withOffsetParsed().parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); result = new MutableDateTime(0L); assertEquals(25, g.withOffsetParsed().parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); result = new MutableDateTime(0L); assertEquals(20, g.withZone(PARIS).withOffsetParsed().parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withOffsetParsed().withZone(PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_chrono() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(ISO_PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(null).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(BUDDHIST_PARIS).parseInto(result, "2547-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(BUDDHIST_PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_monthOnly() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 9, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthOnly_baseStartYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 1, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_parseStartYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 2, 1, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "1", 0)); assertEquals(new MutableDateTime(2004, 1, 1, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_baseEndYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 31, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_parseEndYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 31, 12, 20, 30, 0,TOKYO); assertEquals(2, f.parseInto(result, "12", 0)); assertEquals(new MutableDateTime(2004, 12, 31, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthDay_feb29() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthDay_feb29_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, LONDON), result); } public void testParseInto_monthDay_feb29_OfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, LONDON), result); } public void testParseInto_monthDay_feb29_newYork() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseInto_monthDay_feb29_newYork_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, NEWYORK), result); } public void testParseInto_monthDay_feb29_newYork_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, NEWYORK), result); } public void testParseInto_monthDay_feb29_tokyo() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthDay_feb29_tokyo_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, TOKYO), result); } public void testParseInto_monthDay_feb29_tokyo_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, TOKYO), result); } public void testParseInto_monthDay_withDefaultYear_feb29() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthDay_withDefaultYear_feb29_newYork() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseInto_monthDay_withDefaultYear_feb29_newYork_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 12, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseMillis_fractionOfSecondLong() { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendSecondOfDay(2).appendLiteral('.').appendFractionOfSecond(1, 9) .toFormatter().withZoneUTC(); assertEquals(10512, f.parseMillis("10.5123456")); assertEquals(10512, f.parseMillis("10.512999")); } //----------------------------------------------------------------------- // Ensure time zone name switches properly at the zone DST transition. public void testZoneNameNearTransition() {} // Defects4J: flaky method // public void testZoneNameNearTransition() { // DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK); // DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK); // DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK); // DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK); // DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK); // // DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S zzzz"); // assertEquals("2005-10-30 01:00:00.0 Eastern Daylight Time", fmt.print(inDST_1)); // assertEquals("2005-10-30 01:59:59.9 Eastern Daylight Time", fmt.print(inDST_2)); // assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(onDST)); // assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(outDST)); // assertEquals("2005-10-30 02:00:01.0 Eastern Standard Time", fmt.print(outDST_2)); // } // Ensure time zone name switches properly at the zone DST transition. public void testZoneShortNameNearTransition() {} // Defects4J: flaky method // public void testZoneShortNameNearTransition() { // DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK); // DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK); // DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK); // DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK); // DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK); // // DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S z"); // assertEquals("2005-10-30 01:00:00.0 EDT", fmt.print(inDST_1)); // assertEquals("2005-10-30 01:59:59.9 EDT", fmt.print(inDST_2)); // assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(onDST)); // assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(outDST)); // assertEquals("2005-10-30 02:00:01.0 EST", fmt.print(outDST_2)); // } }
// You are a professional Java test case writer, please create a test case named `testParseInto_monthDay_feb29_newYork_startOfYear` for the issue `Time-21`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-21 // // ## Issue-Title: // DateTimeFormat.parseInto sometimes miscalculates year (2.2) // // ## Issue-Description: // There appears to be a bug in the fix to <http://sourceforge.net/p/joda-time/bugs/148> (which I also reported). // // // The following code (which can be added to org.joda.time.format.TestDateTimeFormatter) breaks, because the input mutable date time's millis appear to be mishandled and the year for the parse is changed to 1999: // // // // ``` // public void testParseInto\_monthDay\_feb29\_startOfYear() { // DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); // MutableDateTime result = new MutableDateTime(2000, 1, 1, 0, 0, 0, 0, NEWYORK); // assertEquals(4, f.parseInto(result, "2 29", 0)); // assertEquals(new MutableDateTime(2000, 2, 29, 0, 0, 0, 0, NEWYORK), result); // } // ``` // // // public void testParseInto_monthDay_feb29_newYork_startOfYear() {
933
7
928
src/test/java/org/joda/time/format/TestDateTimeFormatter.java
src/test/java
```markdown ## Issue-ID: Time-21 ## Issue-Title: DateTimeFormat.parseInto sometimes miscalculates year (2.2) ## Issue-Description: There appears to be a bug in the fix to <http://sourceforge.net/p/joda-time/bugs/148> (which I also reported). The following code (which can be added to org.joda.time.format.TestDateTimeFormatter) breaks, because the input mutable date time's millis appear to be mishandled and the year for the parse is changed to 1999: ``` public void testParseInto\_monthDay\_feb29\_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2000, 1, 1, 0, 0, 0, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2000, 2, 29, 0, 0, 0, 0, NEWYORK), result); } ``` ``` You are a professional Java test case writer, please create a test case named `testParseInto_monthDay_feb29_newYork_startOfYear` for the issue `Time-21`, utilizing the provided issue report information and the following function signature. ```java public void testParseInto_monthDay_feb29_newYork_startOfYear() { ```
928
[ "org.joda.time.format.DateTimeFormatter" ]
e6e9388dcae2ba1cd6f30af922dad93dc16f6e99953e0a3f278e4c314b492a07
public void testParseInto_monthDay_feb29_newYork_startOfYear()
// You are a professional Java test case writer, please create a test case named `testParseInto_monthDay_feb29_newYork_startOfYear` for the issue `Time-21`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Time-21 // // ## Issue-Title: // DateTimeFormat.parseInto sometimes miscalculates year (2.2) // // ## Issue-Description: // There appears to be a bug in the fix to <http://sourceforge.net/p/joda-time/bugs/148> (which I also reported). // // // The following code (which can be added to org.joda.time.format.TestDateTimeFormatter) breaks, because the input mutable date time's millis appear to be mishandled and the year for the parse is changed to 1999: // // // // ``` // public void testParseInto\_monthDay\_feb29\_startOfYear() { // DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); // MutableDateTime result = new MutableDateTime(2000, 1, 1, 0, 0, 0, 0, NEWYORK); // assertEquals(4, f.parseInto(result, "2 29", 0)); // assertEquals(new MutableDateTime(2000, 2, 29, 0, 0, 0, 0, NEWYORK), result); // } // ``` // // //
Time
/* * Copyright 2001-2011 Stephen Colebourne * * 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 org.joda.time.format; import java.io.CharArrayWriter; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; import org.joda.time.MutableDateTime; import org.joda.time.ReadablePartial; import org.joda.time.chrono.BuddhistChronology; import org.joda.time.chrono.GJChronology; import org.joda.time.chrono.ISOChronology; /** * This class is a Junit unit test for DateTime Formating. * * @author Stephen Colebourne */ public class TestDateTimeFormatter extends TestCase { private static final DateTimeZone UTC = DateTimeZone.UTC; private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris"); private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London"); private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo"); private static final DateTimeZone NEWYORK = DateTimeZone.forID("America/New_York"); private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC(); private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS); private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS); long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365; // 2002-06-09 private long TEST_TIME_NOW = (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY; private DateTimeZone originalDateTimeZone = null; private TimeZone originalTimeZone = null; private Locale originalLocale = null; private DateTimeFormatter f = null; private DateTimeFormatter g = null; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFormatter.class); } public TestDateTimeFormatter(String name) { super(name); } protected void setUp() throws Exception { DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW); originalDateTimeZone = DateTimeZone.getDefault(); originalTimeZone = TimeZone.getDefault(); originalLocale = Locale.getDefault(); DateTimeZone.setDefault(LONDON); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Locale.setDefault(Locale.UK); f = new DateTimeFormatterBuilder() .appendDayOfWeekShortText() .appendLiteral(' ') .append(ISODateTimeFormat.dateTimeNoMillis()) .toFormatter(); g = ISODateTimeFormat.dateTimeNoMillis(); } protected void tearDown() throws Exception { DateTimeUtils.setCurrentMillisSystem(); DateTimeZone.setDefault(originalDateTimeZone); TimeZone.setDefault(originalTimeZone); Locale.setDefault(originalLocale); originalDateTimeZone = null; originalTimeZone = null; originalLocale = null; f = null; g = null; } //----------------------------------------------------------------------- public void testPrint_simple() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T10:20:30Z", f.print(dt)); dt = dt.withZone(PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.print(dt)); dt = dt.withZone(NEWYORK); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.print(dt)); } //----------------------------------------------------------------------- public void testPrint_locale() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("mer. 2004-06-09T10:20:30Z", f.withLocale(Locale.FRENCH).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withLocale(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_zone() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withZone(null).print(dt)); dt = dt.withZone(NEWYORK); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withZoneUTC().print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withZone(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_chrono() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(BUDDHIST_PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(null).print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(BUDDHIST_PARIS).print(dt)); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(ISO_UTC).print(dt)); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(null).print(dt)); } //----------------------------------------------------------------------- public void testPrint_bufferMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); StringBuffer buf = new StringBuffer(); f.printTo(buf, dt); assertEquals("Wed 2004-06-09T10:20:30Z", buf.toString()); buf = new StringBuffer(); f.printTo(buf, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", buf.toString()); buf = new StringBuffer(); ISODateTimeFormat.yearMonthDay().printTo(buf, dt.toYearMonthDay()); assertEquals("2004-06-09", buf.toString()); buf = new StringBuffer(); try { ISODateTimeFormat.yearMonthDay().printTo(buf, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_writerMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); CharArrayWriter out = new CharArrayWriter(); f.printTo(out, dt); assertEquals("Wed 2004-06-09T10:20:30Z", out.toString()); out = new CharArrayWriter(); f.printTo(out, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", out.toString()); out = new CharArrayWriter(); ISODateTimeFormat.yearMonthDay().printTo(out, dt.toYearMonthDay()); assertEquals("2004-06-09", out.toString()); out = new CharArrayWriter(); try { ISODateTimeFormat.yearMonthDay().printTo(out, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_appendableMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); StringBuilder buf = new StringBuilder(); f.printTo(buf, dt); assertEquals("Wed 2004-06-09T10:20:30Z", buf.toString()); buf = new StringBuilder(); f.printTo(buf, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", buf.toString()); buf = new StringBuilder(); ISODateTimeFormat.yearMonthDay().printTo(buf, dt.toLocalDate()); assertEquals("2004-06-09", buf.toString()); buf = new StringBuilder(); try { ISODateTimeFormat.yearMonthDay().printTo(buf, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testPrint_chrono_and_zone() { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); assertEquals("Wed 2004-06-09T10:20:30Z", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); dt = dt.withChronology(ISO_PARIS); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); dt = dt.withChronology(BUDDHIST_PARIS); assertEquals("Wed 2547-06-09T12:20:30+02:00", f.withChronology(null).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(null).print(dt)); assertEquals("Wed 2004-06-09T12:20:30+02:00", f.withChronology(ISO_PARIS).withZone(PARIS).print(dt)); assertEquals("Wed 2004-06-09T06:20:30-04:00", f.withChronology(ISO_PARIS).withZone(NEWYORK).print(dt)); assertEquals("Wed 2547-06-09T06:20:30-04:00", f.withChronology(null).withZone(NEWYORK).print(dt)); } public void testWithGetLocale() { DateTimeFormatter f2 = f.withLocale(Locale.FRENCH); assertEquals(Locale.FRENCH, f2.getLocale()); assertSame(f2, f2.withLocale(Locale.FRENCH)); f2 = f.withLocale(null); assertEquals(null, f2.getLocale()); assertSame(f2, f2.withLocale(null)); } public void testWithGetZone() { DateTimeFormatter f2 = f.withZone(PARIS); assertEquals(PARIS, f2.getZone()); assertSame(f2, f2.withZone(PARIS)); f2 = f.withZone(null); assertEquals(null, f2.getZone()); assertSame(f2, f2.withZone(null)); } public void testWithGetChronology() { DateTimeFormatter f2 = f.withChronology(BUDDHIST_PARIS); assertEquals(BUDDHIST_PARIS, f2.getChronology()); assertSame(f2, f2.withChronology(BUDDHIST_PARIS)); f2 = f.withChronology(null); assertEquals(null, f2.getChronology()); assertSame(f2, f2.withChronology(null)); } public void testWithGetPivotYear() { DateTimeFormatter f2 = f.withPivotYear(13); assertEquals(new Integer(13), f2.getPivotYear()); assertSame(f2, f2.withPivotYear(13)); f2 = f.withPivotYear(new Integer(14)); assertEquals(new Integer(14), f2.getPivotYear()); assertSame(f2, f2.withPivotYear(new Integer(14))); f2 = f.withPivotYear(null); assertEquals(null, f2.getPivotYear()); assertSame(f2, f2.withPivotYear(null)); } public void testWithGetOffsetParsedMethods() { DateTimeFormatter f2 = f; assertEquals(false, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f.withOffsetParsed(); assertEquals(true, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f2.withZone(PARIS); assertEquals(false, f2.isOffsetParsed()); assertEquals(PARIS, f2.getZone()); f2 = f2.withOffsetParsed(); assertEquals(true, f2.isOffsetParsed()); assertEquals(null, f2.getZone()); f2 = f.withOffsetParsed(); assertNotSame(f, f2); DateTimeFormatter f3 = f2.withOffsetParsed(); assertSame(f2, f3); } public void testPrinterParserMethods() { DateTimeFormatter f2 = new DateTimeFormatter(f.getPrinter(), f.getParser()); assertEquals(f.getPrinter(), f2.getPrinter()); assertEquals(f.getParser(), f2.getParser()); assertEquals(true, f2.isPrinter()); assertEquals(true, f2.isParser()); assertNotNull(f2.print(0L)); assertNotNull(f2.parseDateTime("Thu 1970-01-01T00:00:00Z")); f2 = new DateTimeFormatter(f.getPrinter(), null); assertEquals(f.getPrinter(), f2.getPrinter()); assertEquals(null, f2.getParser()); assertEquals(true, f2.isPrinter()); assertEquals(false, f2.isParser()); assertNotNull(f2.print(0L)); try { f2.parseDateTime("Thu 1970-01-01T00:00:00Z"); fail(); } catch (UnsupportedOperationException ex) {} f2 = new DateTimeFormatter(null, f.getParser()); assertEquals(null, f2.getPrinter()); assertEquals(f.getParser(), f2.getParser()); assertEquals(false, f2.isPrinter()); assertEquals(true, f2.isParser()); try { f2.print(0L); fail(); } catch (UnsupportedOperationException ex) {} assertNotNull(f2.parseDateTime("Thu 1970-01-01T00:00:00Z")); } //----------------------------------------------------------------------- public void testParseLocalDate_simple() { assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30Z")); assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30+18:00")); assertEquals(new LocalDate(2004, 6, 9), g.parseLocalDate("2004-06-09T10:20:30-18:00")); assertEquals(new LocalDate(2004, 6, 9, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalDate("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseLocalDate_yearOfEra() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("YYYY-MM GG") .withChronology(chrono) .withLocale(Locale.UK); LocalDate date = new LocalDate(2005, 10, 1, chrono); assertEquals(date, f.parseLocalDate("2005-10 AD")); assertEquals(date, f.parseLocalDate("2005-10 CE")); date = new LocalDate(-2005, 10, 1, chrono); assertEquals(date, f.parseLocalDate("2005-10 BC")); assertEquals(date, f.parseLocalDate("2005-10 BCE")); } public void testParseLocalDate_yearOfCentury() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("yy M d") .withChronology(chrono) .withLocale(Locale.UK) .withPivotYear(2050); LocalDate date = new LocalDate(2050, 8, 4, chrono); assertEquals(date, f.parseLocalDate("50 8 4")); } public void testParseLocalDate_monthDay_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d") .withChronology(chrono) .withLocale(Locale.UK); assertEquals(new LocalDate(2000, 2, 29, chrono), f.parseLocalDate("2 29")); } public void testParseLocalDate_monthDay_withDefaultYear_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d") .withChronology(chrono) .withLocale(Locale.UK) .withDefaultYear(2012); assertEquals(new LocalDate(2012, 2, 29, chrono), f.parseLocalDate("2 29")); } public void testParseLocalDate_weekyear_month_week_2010() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2010, 1, 4, chrono), f.parseLocalDate("2010-01-01")); } public void testParseLocalDate_weekyear_month_week_2011() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2011, 1, 3, chrono), f.parseLocalDate("2011-01-01")); } public void testParseLocalDate_weekyear_month_week_2012() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 1, 2, chrono), f.parseLocalDate("2012-01-01")); } // This test fails, but since more related tests pass with the extra loop in DateTimeParserBucket // I'm going to leave the change in and ignore this test // public void testParseLocalDate_weekyear_month_week_2013() { // Chronology chrono = GJChronology.getInstanceUTC(); // DateTimeFormatter f = DateTimeFormat.forPattern("xxxx-MM-ww").withChronology(chrono); // assertEquals(new LocalDate(2012, 12, 31, chrono), f.parseLocalDate("2013-01-01")); // } public void testParseLocalDate_year_month_week_2010() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2010, 1, 4, chrono), f.parseLocalDate("2010-01-01")); } public void testParseLocalDate_year_month_week_2011() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2011, 1, 3, chrono), f.parseLocalDate("2011-01-01")); } public void testParseLocalDate_year_month_week_2012() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 1, 2, chrono), f.parseLocalDate("2012-01-01")); } public void testParseLocalDate_year_month_week_2013() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2012, 12, 31, chrono), f.parseLocalDate("2013-01-01")); // 2013-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2014() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2013, 12, 30, chrono), f.parseLocalDate("2014-01-01")); // 2014-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2015() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2014, 12, 29, chrono), f.parseLocalDate("2015-01-01")); // 2015-01-01 would be better, but this is OK } public void testParseLocalDate_year_month_week_2016() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-ww").withChronology(chrono); assertEquals(new LocalDate(2016, 1, 4, chrono), f.parseLocalDate("2016-01-01")); } //----------------------------------------------------------------------- public void testParseLocalTime_simple() { assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30Z")); assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30+18:00")); assertEquals(new LocalTime(10, 20, 30), g.parseLocalTime("2004-06-09T10:20:30-18:00")); assertEquals(new LocalTime(10, 20, 30, 0, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseLocalDateTime_simple() { assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30Z")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30+18:00")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30-18:00")); assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30, 0, BUDDHIST_PARIS), g.withChronology(BUDDHIST_PARIS).parseLocalDateTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseLocalDateTime_monthDay_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d H m") .withChronology(chrono) .withLocale(Locale.UK); assertEquals(new LocalDateTime(2000, 2, 29, 13, 40, 0, 0, chrono), f.parseLocalDateTime("2 29 13 40")); } public void testParseLocalDateTime_monthDay_withDefaultYear_feb29() { Chronology chrono = GJChronology.getInstanceUTC(); DateTimeFormatter f = DateTimeFormat .forPattern("M d H m") .withChronology(chrono) .withLocale(Locale.UK) .withDefaultYear(2012); assertEquals(new LocalDateTime(2012, 2, 29, 13, 40, 0, 0, chrono), f.parseLocalDateTime("2 29 13 40")); } //----------------------------------------------------------------------- public void testParseDateTime_simple() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.parseDateTime("2004-06-09T10:20:30Z")); try { g.parseDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseDateTime_zone() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseDateTime("2004-06-09T10:20:30Z")); } public void testParseDateTime_zone2() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseDateTime("2004-06-09T06:20:30-04:00")); } public void testParseDateTime_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); DateTime expect = null; expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(LONDON).parseDateTime("2004-06-09T10:20:30")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(null).parseDateTime("2004-06-09T10:20:30")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); assertEquals(expect, h.withZone(PARIS).parseDateTime("2004-06-09T10:20:30")); } public void testParseDateTime_simple_precedence() { DateTime expect = null; // use correct day of week expect = new DateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, f.parseDateTime("Wed 2004-06-09T10:20:30Z")); // use wrong day of week expect = new DateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); // DayOfWeek takes precedence, because week < month in length assertEquals(expect, f.parseDateTime("Mon 2004-06-09T10:20:30Z")); } public void testParseDateTime_offsetParsed() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); assertEquals(expect, g.withOffsetParsed().parseDateTime("2004-06-09T06:20:30-04:00")); expect = new DateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withZone(PARIS).withOffsetParsed().parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withOffsetParsed().withZone(PARIS).parseDateTime("2004-06-09T10:20:30Z")); } public void testParseDateTime_chrono() { DateTime expect = null; expect = new DateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withChronology(ISO_PARIS).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 11, 20, 30, 0,LONDON); assertEquals(expect, g.withChronology(null).parseDateTime("2004-06-09T10:20:30Z")); expect = new DateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2547-06-09T10:20:30Z")); expect = new DateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); // zone is +00:09:21 in 1451 assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseDateTime("2004-06-09T10:20:30Z")); } //----------------------------------------------------------------------- public void testParseMutableDateTime_simple() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.parseMutableDateTime("2004-06-09T10:20:30Z")); try { g.parseMutableDateTime("ABC"); fail(); } catch (IllegalArgumentException ex) {} } public void testParseMutableDateTime_zone() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_zone2() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(LONDON).parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, g.withZone(null).parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withZone(PARIS).parseMutableDateTime("2004-06-09T06:20:30-04:00")); } public void testParseMutableDateTime_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(LONDON).parseMutableDateTime("2004-06-09T10:20:30")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); assertEquals(expect, h.withZone(null).parseMutableDateTime("2004-06-09T10:20:30")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); assertEquals(expect, h.withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30")); } public void testParseMutableDateTime_simple_precedence() { MutableDateTime expect = null; // use correct day of week expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(expect, f.parseDateTime("Wed 2004-06-09T10:20:30Z")); // use wrong day of week expect = new MutableDateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); // DayOfWeek takes precedence, because week < month in length assertEquals(expect, f.parseDateTime("Mon 2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_offsetParsed() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withOffsetParsed().parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); assertEquals(expect, g.withOffsetParsed().parseMutableDateTime("2004-06-09T06:20:30-04:00")); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); assertEquals(expect, g.withZone(PARIS).withOffsetParsed().parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withOffsetParsed().withZone(PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } public void testParseMutableDateTime_chrono() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(expect, g.withChronology(ISO_PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0,LONDON); assertEquals(expect, g.withChronology(null).parseMutableDateTime("2004-06-09T10:20:30Z")); expect = new MutableDateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseMutableDateTime("2547-06-09T10:20:30Z")); expect = new MutableDateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); // zone is +00:09:21 in 1451 assertEquals(expect, g.withChronology(BUDDHIST_PARIS).parseMutableDateTime("2004-06-09T10:20:30Z")); } //----------------------------------------------------------------------- public void testParseInto_simple() { MutableDateTime expect = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); MutableDateTime result = new MutableDateTime(0L); assertEquals(20, g.parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); try { g.parseInto(null, "2004-06-09T10:20:30Z", 0); fail(); } catch (IllegalArgumentException ex) {} assertEquals(~0, g.parseInto(result, "ABC", 0)); assertEquals(~10, g.parseInto(result, "2004-06-09", 0)); assertEquals(~13, g.parseInto(result, "XX2004-06-09T", 2)); } public void testParseInto_zone() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withZone(LONDON).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withZone(null).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withZone(PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_zone2() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(25, g.withZone(LONDON).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); assertEquals(25, g.withZone(null).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); assertEquals(25, g.withZone(PARIS).parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); } public void testParseInto_zone3() { DateTimeFormatter h = new DateTimeFormatterBuilder() .append(ISODateTimeFormat.date()) .appendLiteral('T') .append(ISODateTimeFormat.timeElementParser()) .toFormatter(); MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(19, h.withZone(LONDON).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(19, h.withZone(null).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(19, h.withZone(PARIS).parseInto(result, "2004-06-09T10:20:30", 0)); assertEquals(expect, result); } public void testParseInto_simple_precedence() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 7, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); // DayOfWeek takes precedence, because week < month in length assertEquals(24, f.parseInto(result, "Mon 2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_offsetParsed() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); result = new MutableDateTime(0L); assertEquals(20, g.withOffsetParsed().parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 6, 20, 30, 0, DateTimeZone.forOffsetHours(-4)); result = new MutableDateTime(0L); assertEquals(25, g.withOffsetParsed().parseInto(result, "2004-06-09T06:20:30-04:00", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 20, 30, 0, UTC); result = new MutableDateTime(0L); assertEquals(20, g.withZone(PARIS).withOffsetParsed().parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withOffsetParsed().withZone(PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_chrono() { MutableDateTime expect = null; MutableDateTime result = null; expect = new MutableDateTime(2004, 6, 9, 12, 20, 30, 0, PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(ISO_PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 11, 20, 30, 0, LONDON); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(null).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2547, 6, 9, 12, 20, 30, 0, BUDDHIST_PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(BUDDHIST_PARIS).parseInto(result, "2547-06-09T10:20:30Z", 0)); assertEquals(expect, result); expect = new MutableDateTime(2004, 6, 9, 10, 29, 51, 0, BUDDHIST_PARIS); result = new MutableDateTime(0L); assertEquals(20, g.withChronology(BUDDHIST_PARIS).parseInto(result, "2004-06-09T10:20:30Z", 0)); assertEquals(expect, result); } public void testParseInto_monthOnly() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 9, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthOnly_baseStartYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 1, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_parseStartYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 2, 1, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "1", 0)); assertEquals(new MutableDateTime(2004, 1, 1, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_baseEndYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 12, 20, 30, 0, TOKYO); assertEquals(1, f.parseInto(result, "5", 0)); assertEquals(new MutableDateTime(2004, 5, 31, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthOnly_parseEndYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 31, 12, 20, 30, 0,TOKYO); assertEquals(2, f.parseInto(result, "12", 0)); assertEquals(new MutableDateTime(2004, 12, 31, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthDay_feb29() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthDay_feb29_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, LONDON), result); } public void testParseInto_monthDay_feb29_OfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, LONDON), result); } public void testParseInto_monthDay_feb29_newYork() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseInto_monthDay_feb29_newYork_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, NEWYORK), result); } public void testParseInto_monthDay_feb29_newYork_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, NEWYORK), result); } public void testParseInto_monthDay_feb29_tokyo() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, TOKYO), result); } public void testParseInto_monthDay_feb29_tokyo_startOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 1, 1, 0, 0, 0, 0, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 0, 0, 0, 0, TOKYO), result); } public void testParseInto_monthDay_feb29_tokyo_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withLocale(Locale.UK); MutableDateTime result = new MutableDateTime(2004, 12, 31, 23, 59, 59, 999, TOKYO); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 23, 59, 59, 999, TOKYO), result); } public void testParseInto_monthDay_withDefaultYear_feb29() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, LONDON); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, LONDON), result); } public void testParseInto_monthDay_withDefaultYear_feb29_newYork() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 1, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseInto_monthDay_withDefaultYear_feb29_newYork_endOfYear() { DateTimeFormatter f = DateTimeFormat.forPattern("M d").withDefaultYear(2012); MutableDateTime result = new MutableDateTime(2004, 12, 9, 12, 20, 30, 0, NEWYORK); assertEquals(4, f.parseInto(result, "2 29", 0)); assertEquals(new MutableDateTime(2004, 2, 29, 12, 20, 30, 0, NEWYORK), result); } public void testParseMillis_fractionOfSecondLong() { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendSecondOfDay(2).appendLiteral('.').appendFractionOfSecond(1, 9) .toFormatter().withZoneUTC(); assertEquals(10512, f.parseMillis("10.5123456")); assertEquals(10512, f.parseMillis("10.512999")); } //----------------------------------------------------------------------- // Ensure time zone name switches properly at the zone DST transition. public void testZoneNameNearTransition() {} // Defects4J: flaky method // public void testZoneNameNearTransition() { // DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK); // DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK); // DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK); // DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK); // DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK); // // DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S zzzz"); // assertEquals("2005-10-30 01:00:00.0 Eastern Daylight Time", fmt.print(inDST_1)); // assertEquals("2005-10-30 01:59:59.9 Eastern Daylight Time", fmt.print(inDST_2)); // assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(onDST)); // assertEquals("2005-10-30 02:00:00.0 Eastern Standard Time", fmt.print(outDST)); // assertEquals("2005-10-30 02:00:01.0 Eastern Standard Time", fmt.print(outDST_2)); // } // Ensure time zone name switches properly at the zone DST transition. public void testZoneShortNameNearTransition() {} // Defects4J: flaky method // public void testZoneShortNameNearTransition() { // DateTime inDST_1 = new DateTime(2005, 10, 30, 1, 0, 0, 0, NEWYORK); // DateTime inDST_2 = new DateTime(2005, 10, 30, 1, 59, 59, 999, NEWYORK); // DateTime onDST = new DateTime(2005, 10, 30, 2, 0, 0, 0, NEWYORK); // DateTime outDST = new DateTime(2005, 10, 30, 2, 0, 0, 1, NEWYORK); // DateTime outDST_2 = new DateTime(2005, 10, 30, 2, 0, 1, 0, NEWYORK); // // DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss.S z"); // assertEquals("2005-10-30 01:00:00.0 EDT", fmt.print(inDST_1)); // assertEquals("2005-10-30 01:59:59.9 EDT", fmt.print(inDST_2)); // assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(onDST)); // assertEquals("2005-10-30 02:00:00.0 EST", fmt.print(outDST)); // assertEquals("2005-10-30 02:00:01.0 EST", fmt.print(outDST_2)); // } }